@vkontakte/videoplayer-core 2.0.117-dev.d9cc3d97.0 → 2.0.118-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2018.esm.js CHANGED
@@ -1,71 +1,72 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.117-dev.d9cc3d97.0
3
- * Thu, 14 Nov 2024 06:33:52 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-117/doc/
2
+ * @vkontakte/videoplayer-core v2.0.118-beta.0
3
+ * Thu, 21 Nov 2024 21:19:06 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-118/doc/
5
5
  */
6
- var Av=Object.create;var sc=Object.defineProperty;var wv=Object.getOwnPropertyDescriptor;var kv=Object.getOwnPropertyNames;var Rv=Object.getPrototypeOf,$v=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var Lv=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of kv(e))!$v.call(a,r)&&r!==t&&sc(a,r,{get:()=>e[r],enumerable:!(i=wv(e,r))||i.enumerable});return a};var Ue=(a,e,t)=>(t=a!=null?Av(Rv(a)):{},Lv(e||!a||!a.__esModule?sc(t,"default",{value:a,enumerable:!0}):t,a));var Ee=b((qL,hc)=>{"use strict";hc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ji=b((HL,fc)=>{"use strict";var Nv=Ee();fc.exports=!Nv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var pe=b((jL,gc)=>{"use strict";var mc=Ji(),bc=Function.prototype,kn=bc.call,Fv=mc&&bc.bind.bind(kn,kn);gc.exports=mc?Fv:function(a){return function(){return kn.apply(a,arguments)}}});var mi=b((GL,vc)=>{"use strict";var Sc=pe(),Uv=Sc({}.toString),qv=Sc("".slice);vc.exports=function(a){return qv(Uv(a),8,-1)}});var Tc=b((QL,yc)=>{"use strict";var Hv=pe(),jv=Ee(),Gv=mi(),Rn=Object,Qv=Hv("".split);yc.exports=jv(function(){return!Rn("z").propertyIsEnumerable(0)})?function(a){return Gv(a)==="String"?Qv(a,""):Rn(a)}:Rn});var bi=b((WL,Ic)=>{"use strict";Ic.exports=function(a){return a==null}});var Zi=b((YL,Ec)=>{"use strict";var Wv=bi(),Yv=TypeError;Ec.exports=function(a){if(Wv(a))throw new Yv("Can't call method on "+a);return a}});var gi=b((zL,xc)=>{"use strict";var zv=Tc(),Kv=Zi();xc.exports=function(a){return zv(Kv(a))}});var $n=b((KL,Pc)=>{"use strict";Pc.exports=function(){}});var qt=b((XL,Ac)=>{"use strict";Ac.exports={}});var Y=b((Ln,wc)=>{"use strict";var er=function(a){return a&&a.Math===Math&&a};wc.exports=er(typeof globalThis=="object"&&globalThis)||er(typeof window=="object"&&window)||er(typeof self=="object"&&self)||er(typeof global=="object"&&global)||er(typeof Ln=="object"&&Ln)||function(){return this}()||Function("return this")()});var W=b((JL,kc)=>{"use strict";var Mn=typeof document=="object"&&document.all;kc.exports=typeof Mn=="undefined"&&Mn!==void 0?function(a){return typeof a=="function"||a===Mn}:function(a){return typeof a=="function"}});var Lc=b((ZL,$c)=>{"use strict";var Xv=Y(),Jv=W(),Rc=Xv.WeakMap;$c.exports=Jv(Rc)&&/native code/.test(String(Rc))});var Le=b((eM,Mc)=>{"use strict";var Zv=W();Mc.exports=function(a){return typeof a=="object"?a!==null:Zv(a)}});var Me=b((tM,Dc)=>{"use strict";var ey=Ee();Dc.exports=!ey(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ga=b((iM,Vc)=>{"use strict";var ty=Y(),Cc=Le(),Dn=ty.document,iy=Cc(Dn)&&Cc(Dn.createElement);Vc.exports=function(a){return iy?Dn.createElement(a):{}}});var Cn=b((rM,Bc)=>{"use strict";var ry=Me(),ay=Ee(),sy=Ga();Bc.exports=!ry&&!ay(function(){return Object.defineProperty(sy("div"),"a",{get:function(){return 7}}).a!==7})});var Vn=b((aM,Oc)=>{"use strict";var ny=Me(),oy=Ee();Oc.exports=ny&&oy(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Xe=b((sM,_c)=>{"use strict";var uy=Le(),ly=String,cy=TypeError;_c.exports=function(a){if(uy(a))return a;throw new cy(ly(a)+" is not an object")}});var xe=b((nM,Nc)=>{"use strict";var dy=Ji(),Qa=Function.prototype.call;Nc.exports=dy?Qa.bind(Qa):function(){return Qa.apply(Qa,arguments)}});var Wa=b((oM,Fc)=>{"use strict";Fc.exports={}});var rt=b((uM,qc)=>{"use strict";var Bn=Wa(),On=Y(),py=W(),Uc=function(a){return py(a)?a:void 0};qc.exports=function(a,e){return arguments.length<2?Uc(Bn[a])||Uc(On[a]):Bn[a]&&Bn[a][e]||On[a]&&On[a][e]}});var tr=b((lM,Hc)=>{"use strict";var hy=pe();Hc.exports=hy({}.isPrototypeOf)});var Si=b((cM,Qc)=>{"use strict";var fy=Y(),jc=fy.navigator,Gc=jc&&jc.userAgent;Qc.exports=Gc?String(Gc):""});var Nn=b((dM,Jc)=>{"use strict";var Xc=Y(),_n=Si(),Wc=Xc.process,Yc=Xc.Deno,zc=Wc&&Wc.versions||Yc&&Yc.version,Kc=zc&&zc.v8,qe,Ya;Kc&&(qe=Kc.split("."),Ya=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!Ya&&_n&&(qe=_n.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=_n.match(/Chrome\/(\d+)/),qe&&(Ya=+qe[1])));Jc.exports=Ya});var Fn=b((pM,ed)=>{"use strict";var Zc=Nn(),my=Ee(),by=Y(),gy=by.String;ed.exports=!!Object.getOwnPropertySymbols&&!my(function(){var a=Symbol("symbol detection");return!gy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Zc&&Zc<41})});var Un=b((hM,td)=>{"use strict";var Sy=Fn();td.exports=Sy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var qn=b((fM,id)=>{"use strict";var vy=rt(),yy=W(),Ty=tr(),Iy=Un(),Ey=Object;id.exports=Iy?function(a){return typeof a=="symbol"}:function(a){var e=vy("Symbol");return yy(e)&&Ty(e.prototype,Ey(a))}});var ir=b((mM,rd)=>{"use strict";var xy=String;rd.exports=function(a){try{return xy(a)}catch(e){return"Object"}}});var at=b((bM,ad)=>{"use strict";var Py=W(),Ay=ir(),wy=TypeError;ad.exports=function(a){if(Py(a))return a;throw new wy(Ay(a)+" is not a function")}});var rr=b((gM,sd)=>{"use strict";var ky=at(),Ry=bi();sd.exports=function(a,e){var t=a[e];return Ry(t)?void 0:ky(t)}});var od=b((SM,nd)=>{"use strict";var Hn=xe(),jn=W(),Gn=Le(),$y=TypeError;nd.exports=function(a,e){var t,i;if(e==="string"&&jn(t=a.toString)&&!Gn(i=Hn(t,a))||jn(t=a.valueOf)&&!Gn(i=Hn(t,a))||e!=="string"&&jn(t=a.toString)&&!Gn(i=Hn(t,a)))return i;throw new $y("Can't convert object to primitive value")}});var He=b((vM,ud)=>{"use strict";ud.exports=!0});var dd=b((yM,cd)=>{"use strict";var ld=Y(),Ly=Object.defineProperty;cd.exports=function(a,e){try{Ly(ld,a,{value:e,configurable:!0,writable:!0})}catch(t){ld[a]=e}return e}});var ar=b((TM,fd)=>{"use strict";var My=He(),Dy=Y(),Cy=dd(),pd="__core-js_shared__",hd=fd.exports=Dy[pd]||Cy(pd,{});(hd.versions||(hd.versions=[])).push({version:"3.38.0",mode:My?"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 Qn=b((IM,bd)=>{"use strict";var md=ar();bd.exports=function(a,e){return md[a]||(md[a]=e||{})}});var sr=b((EM,gd)=>{"use strict";var Vy=Zi(),By=Object;gd.exports=function(a){return By(Vy(a))}});var je=b((xM,Sd)=>{"use strict";var Oy=pe(),_y=sr(),Ny=Oy({}.hasOwnProperty);Sd.exports=Object.hasOwn||function(e,t){return Ny(_y(e),t)}});var Wn=b((PM,vd)=>{"use strict";var Fy=pe(),Uy=0,qy=Math.random(),Hy=Fy(1 .toString);vd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Hy(++Uy+qy,36)}});var ue=b((AM,Td)=>{"use strict";var jy=Y(),Gy=Qn(),yd=je(),Qy=Wn(),Wy=Fn(),Yy=Un(),vi=jy.Symbol,Yn=Gy("wks"),zy=Yy?vi.for||vi:vi&&vi.withoutSetter||Qy;Td.exports=function(a){return yd(Yn,a)||(Yn[a]=Wy&&yd(vi,a)?vi[a]:zy("Symbol."+a)),Yn[a]}});var Pd=b((wM,xd)=>{"use strict";var Ky=xe(),Id=Le(),Ed=qn(),Xy=rr(),Jy=od(),Zy=ue(),eT=TypeError,tT=Zy("toPrimitive");xd.exports=function(a,e){if(!Id(a)||Ed(a))return a;var t=Xy(a,tT),i;if(t){if(e===void 0&&(e="default"),i=Ky(t,a,e),!Id(i)||Ed(i))return i;throw new eT("Can't convert object to primitive value")}return e===void 0&&(e="number"),Jy(a,e)}});var zn=b((kM,Ad)=>{"use strict";var iT=Pd(),rT=qn();Ad.exports=function(a){var e=iT(a,"string");return rT(e)?e:e+""}});var Ht=b(kd=>{"use strict";var aT=Me(),sT=Cn(),nT=Vn(),za=Xe(),wd=zn(),oT=TypeError,Kn=Object.defineProperty,uT=Object.getOwnPropertyDescriptor,Xn="enumerable",Jn="configurable",Zn="writable";kd.f=aT?nT?function(e,t,i){if(za(e),t=wd(t),za(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Zn in i&&!i[Zn]){var r=uT(e,t);r&&r[Zn]&&(e[t]=i.value,i={configurable:Jn in i?i[Jn]:r[Jn],enumerable:Xn in i?i[Xn]:r[Xn],writable:!1})}return Kn(e,t,i)}:Kn:function(e,t,i){if(za(e),t=wd(t),za(i),sT)try{return Kn(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new oT("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var nr=b(($M,Rd)=>{"use strict";Rd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var yi=b((LM,$d)=>{"use strict";var lT=Me(),cT=Ht(),dT=nr();$d.exports=lT?function(a,e,t){return cT.f(a,e,dT(1,t))}:function(a,e,t){return a[e]=t,a}});var Ka=b((MM,Md)=>{"use strict";var pT=Qn(),hT=Wn(),Ld=pT("keys");Md.exports=function(a){return Ld[a]||(Ld[a]=hT(a))}});var Xa=b((DM,Dd)=>{"use strict";Dd.exports={}});var ro=b((CM,Bd)=>{"use strict";var fT=Lc(),Vd=Y(),mT=Le(),bT=yi(),eo=je(),to=ar(),gT=Ka(),ST=Xa(),Cd="Object already initialized",io=Vd.TypeError,vT=Vd.WeakMap,Ja,or,Za,yT=function(a){return Za(a)?or(a):Ja(a,{})},TT=function(a){return function(e){var t;if(!mT(e)||(t=or(e)).type!==a)throw new io("Incompatible receiver, "+a+" required");return t}};fT||to.state?(Ge=to.state||(to.state=new vT),Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,Ja=function(a,e){if(Ge.has(a))throw new io(Cd);return e.facade=a,Ge.set(a,e),e},or=function(a){return Ge.get(a)||{}},Za=function(a){return Ge.has(a)}):(jt=gT("state"),ST[jt]=!0,Ja=function(a,e){if(eo(a,jt))throw new io(Cd);return e.facade=a,bT(a,jt,e),e},or=function(a){return eo(a,jt)?a[jt]:{}},Za=function(a){return eo(a,jt)});var Ge,jt;Bd.exports={set:Ja,get:or,has:Za,enforce:yT,getterFor:TT}});var ao=b((VM,Fd)=>{"use strict";var IT=Ji(),Nd=Function.prototype,Od=Nd.apply,_d=Nd.call;Fd.exports=typeof Reflect=="object"&&Reflect.apply||(IT?_d.bind(Od):function(){return _d.apply(Od,arguments)})});var so=b((BM,Ud)=>{"use strict";var ET=mi(),xT=pe();Ud.exports=function(a){if(ET(a)==="Function")return xT(a)}});var Gd=b(jd=>{"use strict";var qd={}.propertyIsEnumerable,Hd=Object.getOwnPropertyDescriptor,PT=Hd&&!qd.call({1:2},1);jd.f=PT?function(e){var t=Hd(this,e);return!!t&&t.enumerable}:qd});var Yd=b(Wd=>{"use strict";var AT=Me(),wT=xe(),kT=Gd(),RT=nr(),$T=gi(),LT=zn(),MT=je(),DT=Cn(),Qd=Object.getOwnPropertyDescriptor;Wd.f=AT?Qd:function(e,t){if(e=$T(e),t=LT(t),DT)try{return Qd(e,t)}catch(i){}if(MT(e,t))return RT(!wT(kT.f,e,t),e[t])}});var no=b((NM,zd)=>{"use strict";var CT=Ee(),VT=W(),BT=/#|\.prototype\./,ur=function(a,e){var t=_T[OT(a)];return t===FT?!0:t===NT?!1:VT(e)?CT(e):!!e},OT=ur.normalize=function(a){return String(a).replace(BT,".").toLowerCase()},_T=ur.data={},NT=ur.NATIVE="N",FT=ur.POLYFILL="P";zd.exports=ur});var lr=b((FM,Xd)=>{"use strict";var Kd=so(),UT=at(),qT=Ji(),HT=Kd(Kd.bind);Xd.exports=function(a,e){return UT(a),e===void 0?a:qT?HT(a,e):function(){return a.apply(e,arguments)}}});var De=b((UM,Zd)=>{"use strict";var cr=Y(),jT=ao(),GT=so(),QT=W(),WT=Yd().f,YT=no(),Ti=Wa(),zT=lr(),Ii=yi(),Jd=je();ar();var KT=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return jT(a,this,arguments)};return e.prototype=a.prototype,e};Zd.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?cr:r?cr[t]:cr[t]&&cr[t].prototype,o=i?Ti:Ti[t]||Ii(Ti,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,v;for(h in e)l=YT(i?h:t+(r?".":"#")+h,a.forced),d=!l&&n&&Jd(n,h),f=o[h],d&&(a.dontCallGetSet?(v=WT(n,h),m=v&&v.value):m=n[h]),p=d&&m?m:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&d?g=zT(p,cr):a.wrap&&d?g=KT(p):s&&QT(p)?g=GT(p):g=p,(a.sham||p&&p.sham||f&&f.sham)&&Ii(g,"sham",!0),Ii(o,h,g),s&&(c=t+"Prototype",Jd(Ti,c)||Ii(Ti,c,{}),Ii(Ti[c],h,p),a.real&&u&&(l||!u[h])&&Ii(u,h,p)))}});var ip=b((qM,tp)=>{"use strict";var oo=Me(),XT=je(),ep=Function.prototype,JT=oo&&Object.getOwnPropertyDescriptor,uo=XT(ep,"name"),ZT=uo&&function(){}.name==="something",eI=uo&&(!oo||oo&&JT(ep,"name").configurable);tp.exports={EXISTS:uo,PROPER:ZT,CONFIGURABLE:eI}});var ap=b((HM,rp)=>{"use strict";var tI=Math.ceil,iI=Math.floor;rp.exports=Math.trunc||function(e){var t=+e;return(t>0?iI:tI)(t)}});var es=b((jM,sp)=>{"use strict";var rI=ap();sp.exports=function(a){var e=+a;return e!==e||e===0?0:rI(e)}});var op=b((GM,np)=>{"use strict";var aI=es(),sI=Math.max,nI=Math.min;np.exports=function(a,e){var t=aI(a);return t<0?sI(t+e,0):nI(t,e)}});var lp=b((QM,up)=>{"use strict";var oI=es(),uI=Math.min;up.exports=function(a){var e=oI(a);return e>0?uI(e,9007199254740991):0}});var ts=b((WM,cp)=>{"use strict";var lI=lp();cp.exports=function(a){return lI(a.length)}});var hp=b((YM,pp)=>{"use strict";var cI=gi(),dI=op(),pI=ts(),dp=function(a){return function(e,t,i){var r=cI(e),s=pI(r);if(s===0)return!a&&-1;var n=dI(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};pp.exports={includes:dp(!0),indexOf:dp(!1)}});var bp=b((zM,mp)=>{"use strict";var hI=pe(),lo=je(),fI=gi(),mI=hp().indexOf,bI=Xa(),fp=hI([].push);mp.exports=function(a,e){var t=fI(a),i=0,r=[],s;for(s in t)!lo(bI,s)&&lo(t,s)&&fp(r,s);for(;e.length>i;)lo(t,s=e[i++])&&(~mI(r,s)||fp(r,s));return r}});var co=b((KM,gp)=>{"use strict";gp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var vp=b((XM,Sp)=>{"use strict";var gI=bp(),SI=co();Sp.exports=Object.keys||function(e){return gI(e,SI)}});var Tp=b(yp=>{"use strict";var vI=Me(),yI=Vn(),TI=Ht(),II=Xe(),EI=gi(),xI=vp();yp.f=vI&&!yI?Object.defineProperties:function(e,t){II(e);for(var i=EI(t),r=xI(t),s=r.length,n=0,o;s>n;)TI.f(e,o=r[n++],i[o]);return e}});var po=b((ZM,Ip)=>{"use strict";var PI=rt();Ip.exports=PI("document","documentElement")});var bo=b((eD,Rp)=>{"use strict";var AI=Xe(),wI=Tp(),Ep=co(),kI=Xa(),RI=po(),$I=Ga(),LI=Ka(),xp=">",Pp="<",fo="prototype",mo="script",wp=LI("IE_PROTO"),ho=function(){},kp=function(a){return Pp+mo+xp+a+Pp+"/"+mo+xp},Ap=function(a){a.write(kp("")),a.close();var e=a.parentWindow.Object;return a=null,e},MI=function(){var a=$I("iframe"),e="java"+mo+":",t;return a.style.display="none",RI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(kp("document.F=Object")),t.close(),t.F},is,rs=function(){try{is=new ActiveXObject("htmlfile")}catch(e){}rs=typeof document!="undefined"?document.domain&&is?Ap(is):MI():Ap(is);for(var a=Ep.length;a--;)delete rs[fo][Ep[a]];return rs()};kI[wp]=!0;Rp.exports=Object.create||function(e,t){var i;return e!==null?(ho[fo]=AI(e),i=new ho,ho[fo]=null,i[wp]=e):i=rs(),t===void 0?i:wI.f(i,t)}});var Lp=b((tD,$p)=>{"use strict";var DI=Ee();$p.exports=!DI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var So=b((iD,Dp)=>{"use strict";var CI=je(),VI=W(),BI=sr(),OI=Ka(),_I=Lp(),Mp=OI("IE_PROTO"),go=Object,NI=go.prototype;Dp.exports=_I?go.getPrototypeOf:function(a){var e=BI(a);if(CI(e,Mp))return e[Mp];var t=e.constructor;return VI(t)&&e instanceof t?t.prototype:e instanceof go?NI:null}});var Ei=b((rD,Cp)=>{"use strict";var FI=yi();Cp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:FI(a,e,t),a}});var Io=b((aD,Op)=>{"use strict";var UI=Ee(),qI=W(),HI=Le(),jI=bo(),Vp=So(),GI=Ei(),QI=ue(),WI=He(),To=QI("iterator"),Bp=!1,st,vo,yo;[].keys&&(yo=[].keys(),"next"in yo?(vo=Vp(Vp(yo)),vo!==Object.prototype&&(st=vo)):Bp=!0);var YI=!HI(st)||UI(function(){var a={};return st[To].call(a)!==a});YI?st={}:WI&&(st=jI(st));qI(st[To])||GI(st,To,function(){return this});Op.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:Bp}});var as=b((sD,Np)=>{"use strict";var zI=ue(),KI=zI("toStringTag"),_p={};_p[KI]="z";Np.exports=String(_p)==="[object z]"});var dr=b((nD,Fp)=>{"use strict";var XI=as(),JI=W(),ss=mi(),ZI=ue(),eE=ZI("toStringTag"),tE=Object,iE=ss(function(){return arguments}())==="Arguments",rE=function(a,e){try{return a[e]}catch(t){}};Fp.exports=XI?ss:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=rE(e=tE(a),eE))=="string"?t:iE?ss(e):(i=ss(e))==="Object"&&JI(e.callee)?"Arguments":i}});var qp=b((oD,Up)=>{"use strict";var aE=as(),sE=dr();Up.exports=aE?{}.toString:function(){return"[object "+sE(this)+"]"}});var pr=b((uD,jp)=>{"use strict";var nE=as(),oE=Ht().f,uE=yi(),lE=je(),cE=qp(),dE=ue(),Hp=dE("toStringTag");jp.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(lE(r,Hp)||oE(r,Hp,{configurable:!0,value:e}),i&&!nE&&uE(r,"toString",cE))}});var Qp=b((lD,Gp)=>{"use strict";var pE=Io().IteratorPrototype,hE=bo(),fE=nr(),mE=pr(),bE=qt(),gE=function(){return this};Gp.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=hE(pE,{next:fE(+!i,t)}),mE(a,r,!1,!0),bE[r]=gE,a}});var Yp=b((cD,Wp)=>{"use strict";var SE=pe(),vE=at();Wp.exports=function(a,e,t){try{return SE(vE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Kp=b((dD,zp)=>{"use strict";var yE=Le();zp.exports=function(a){return yE(a)||a===null}});var Jp=b((pD,Xp)=>{"use strict";var TE=Kp(),IE=String,EE=TypeError;Xp.exports=function(a){if(TE(a))return a;throw new EE("Can't set "+IE(a)+" as a prototype")}});var Eo=b((hD,Zp)=>{"use strict";var xE=Yp(),PE=Le(),AE=Zi(),wE=Jp();Zp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=xE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return AE(r),wE(s),PE(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var ch=b((fD,lh)=>{"use strict";var kE=De(),RE=xe(),ns=He(),oh=ip(),$E=W(),LE=Qp(),eh=So(),th=Eo(),ME=pr(),DE=yi(),xo=Ei(),CE=ue(),ih=qt(),uh=Io(),VE=oh.PROPER,BE=oh.CONFIGURABLE,rh=uh.IteratorPrototype,os=uh.BUGGY_SAFARI_ITERATORS,hr=CE("iterator"),ah="keys",fr="values",sh="entries",nh=function(){return this};lh.exports=function(a,e,t,i,r,s,n){LE(t,e,i);var o=function(v){if(v===r&&h)return h;if(!os&&v&&v in d)return d[v];switch(v){case ah:return function(){return new t(this,v)};case fr:return function(){return new t(this,v)};case sh:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[hr]||d["@@iterator"]||r&&d[r],h=!os&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=eh(p.call(new a)),f!==Object.prototype&&f.next&&(!ns&&eh(f)!==rh&&(th?th(f,rh):$E(f[hr])||xo(f,hr,nh)),ME(f,u,!0,!0),ns&&(ih[u]=nh))),VE&&r===fr&&c&&c.name!==fr&&(!ns&&BE?DE(d,"name",fr):(l=!0,h=function(){return RE(c,this)})),r)if(m={values:o(fr),keys:s?h:o(ah),entries:o(sh)},n)for(g in m)(os||l||!(g in d))&&xo(d,g,m[g]);else kE({target:e,proto:!0,forced:os||l},m);return(!ns||n)&&d[hr]!==h&&xo(d,hr,h,{name:r}),ih[e]=h,m}});var ph=b((mD,dh)=>{"use strict";dh.exports=function(a,e){return{value:a,done:e}}});var Ao=b((bD,gh)=>{"use strict";var OE=gi(),Po=$n(),hh=qt(),mh=ro(),_E=Ht().f,NE=ch(),us=ph(),FE=He(),UE=Me(),bh="Array Iterator",qE=mh.set,HE=mh.getterFor(bh);gh.exports=NE(Array,"Array",function(a,e){qE(this,{type:bh,target:OE(a),index:0,kind:e})},function(){var a=HE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,us(void 0,!0);switch(a.kind){case"keys":return us(t,!1);case"values":return us(e[t],!1)}return us([t,e[t]],!1)},"values");var fh=hh.Arguments=hh.Array;Po("keys");Po("values");Po("entries");if(!FE&&UE&&fh.name!=="values")try{_E(fh,"name",{value:"values"})}catch(a){}});var vh=b((gD,Sh)=>{"use strict";var jE=ue(),GE=qt(),QE=jE("iterator"),WE=Array.prototype;Sh.exports=function(a){return a!==void 0&&(GE.Array===a||WE[QE]===a)}});var wo=b((SD,Th)=>{"use strict";var YE=dr(),yh=rr(),zE=bi(),KE=qt(),XE=ue(),JE=XE("iterator");Th.exports=function(a){if(!zE(a))return yh(a,JE)||yh(a,"@@iterator")||KE[YE(a)]}});var Eh=b((vD,Ih)=>{"use strict";var ZE=xe(),ex=at(),tx=Xe(),ix=ir(),rx=wo(),ax=TypeError;Ih.exports=function(a,e){var t=arguments.length<2?rx(a):e;if(ex(t))return tx(ZE(t,a));throw new ax(ix(a)+" is not iterable")}});var Ah=b((yD,Ph)=>{"use strict";var sx=xe(),xh=Xe(),nx=rr();Ph.exports=function(a,e,t){var i,r;xh(a);try{if(i=nx(a,"return"),!i){if(e==="throw")throw t;return t}i=sx(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return xh(i),t}});var cs=b((TD,$h)=>{"use strict";var ox=lr(),ux=xe(),lx=Xe(),cx=ir(),dx=vh(),px=ts(),wh=tr(),hx=Eh(),fx=wo(),kh=Ah(),mx=TypeError,ls=function(a,e){this.stopped=a,this.result=e},Rh=ls.prototype;$h.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=ox(e,i),l,d,c,h,p,f,m,g=function(S){return l&&kh(l,"normal",S),new ls(!0,S)},v=function(S){return r?(lx(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(d=fx(a),!d)throw new mx(cx(a)+" is not iterable");if(dx(d)){for(c=0,h=px(a);h>c;c++)if(p=v(a[c]),p&&wh(Rh,p))return p;return new ls(!1)}l=hx(a,d)}for(f=s?a.next:l.next;!(m=ux(f,l)).done;){try{p=v(m.value)}catch(S){kh(l,"throw",S)}if(typeof p=="object"&&p&&wh(Rh,p))return p}return new ls(!1)}});var Mh=b((ID,Lh)=>{"use strict";var bx=Me(),gx=Ht(),Sx=nr();Lh.exports=function(a,e,t){bx?gx.f(a,e,Sx(0,t)):a[e]=t}});var Dh=b(()=>{"use strict";var vx=De(),yx=cs(),Tx=Mh();vx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return yx(e,function(i,r){Tx(t,i,r)},{AS_ENTRIES:!0}),t}})});var Vh=b((PD,Ch)=>{"use strict";Ao();Dh();var Ix=Wa();Ch.exports=Ix.Object.fromEntries});var Oh=b((AD,Bh)=>{"use strict";Bh.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 Nh=b(()=>{"use strict";Ao();var Ex=Oh(),xx=Y(),Px=pr(),_h=qt();for(ds in Ex)Px(xx[ds],ds),_h[ds]=_h.Array;var ds});var Uh=b((RD,Fh)=>{"use strict";var Ax=Vh();Nh();Fh.exports=Ax});var ko=b(($D,qh)=>{"use strict";var wx=Uh();qh.exports=wx});var Hh=b(()=>{"use strict"});var Ro=b((DD,jh)=>{"use strict";var mr=Y(),kx=Si(),Rx=mi(),ps=function(a){return kx.slice(0,a.length)===a};jh.exports=function(){return ps("Bun/")?"BUN":ps("Cloudflare-Workers")?"CLOUDFLARE":ps("Deno/")?"DENO":ps("Node.js/")?"NODE":mr.Bun&&typeof Bun.version=="string"?"BUN":mr.Deno&&typeof Deno.version=="object"?"DENO":Rx(mr.process)==="process"?"NODE":mr.window&&mr.document?"BROWSER":"REST"}()});var hs=b((CD,Gh)=>{"use strict";var $x=Ro();Gh.exports=$x==="NODE"});var Wh=b((VD,Qh)=>{"use strict";var Lx=Ht();Qh.exports=function(a,e,t){return Lx.f(a,e,t)}});var Kh=b((BD,zh)=>{"use strict";var Mx=rt(),Dx=Wh(),Cx=ue(),Vx=Me(),Yh=Cx("species");zh.exports=function(a){var e=Mx(a);Vx&&e&&!e[Yh]&&Dx(e,Yh,{configurable:!0,get:function(){return this}})}});var Jh=b((OD,Xh)=>{"use strict";var Bx=tr(),Ox=TypeError;Xh.exports=function(a,e){if(Bx(e,a))return a;throw new Ox("Incorrect invocation")}});var Lo=b((_D,Zh)=>{"use strict";var _x=pe(),Nx=W(),$o=ar(),Fx=_x(Function.toString);Nx($o.inspectSource)||($o.inspectSource=function(a){return Fx(a)});Zh.exports=$o.inspectSource});var nf=b((ND,sf)=>{"use strict";var Ux=pe(),qx=Ee(),ef=W(),Hx=dr(),jx=rt(),Gx=Lo(),tf=function(){},rf=jx("Reflect","construct"),Mo=/^\s*(?:class|function)\b/,Qx=Ux(Mo.exec),Wx=!Mo.test(tf),br=function(e){if(!ef(e))return!1;try{return rf(tf,[],e),!0}catch(t){return!1}},af=function(e){if(!ef(e))return!1;switch(Hx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Wx||!!Qx(Mo,Gx(e))}catch(t){return!0}};af.sham=!0;sf.exports=!rf||qx(function(){var a;return br(br.call)||!br(Object)||!br(function(){a=!0})||a})?af:br});var uf=b((FD,of)=>{"use strict";var Yx=nf(),zx=ir(),Kx=TypeError;of.exports=function(a){if(Yx(a))return a;throw new Kx(zx(a)+" is not a constructor")}});var Do=b((UD,cf)=>{"use strict";var lf=Xe(),Xx=uf(),Jx=bi(),Zx=ue(),eP=Zx("species");cf.exports=function(a,e){var t=lf(a).constructor,i;return t===void 0||Jx(i=lf(t)[eP])?e:Xx(i)}});var pf=b((qD,df)=>{"use strict";var tP=pe();df.exports=tP([].slice)});var ff=b((HD,hf)=>{"use strict";var iP=TypeError;hf.exports=function(a,e){if(a<e)throw new iP("Not enough arguments");return a}});var Co=b((jD,mf)=>{"use strict";var rP=Si();mf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(rP)});var Ho=b((GD,xf)=>{"use strict";var Pe=Y(),aP=ao(),sP=lr(),bf=W(),nP=je(),Ef=Ee(),gf=po(),oP=pf(),Sf=Ga(),uP=ff(),lP=Co(),cP=hs(),Fo=Pe.setImmediate,Uo=Pe.clearImmediate,dP=Pe.process,Vo=Pe.Dispatch,pP=Pe.Function,vf=Pe.MessageChannel,hP=Pe.String,Bo=0,gr={},yf="onreadystatechange",Sr,Gt,Oo,_o;Ef(function(){Sr=Pe.location});var qo=function(a){if(nP(gr,a)){var e=gr[a];delete gr[a],e()}},No=function(a){return function(){qo(a)}},Tf=function(a){qo(a.data)},If=function(a){Pe.postMessage(hP(a),Sr.protocol+"//"+Sr.host)};(!Fo||!Uo)&&(Fo=function(e){uP(arguments.length,1);var t=bf(e)?e:pP(e),i=oP(arguments,1);return gr[++Bo]=function(){aP(t,void 0,i)},Gt(Bo),Bo},Uo=function(e){delete gr[e]},cP?Gt=function(a){dP.nextTick(No(a))}:Vo&&Vo.now?Gt=function(a){Vo.now(No(a))}:vf&&!lP?(Oo=new vf,_o=Oo.port2,Oo.port1.onmessage=Tf,Gt=sP(_o.postMessage,_o)):Pe.addEventListener&&bf(Pe.postMessage)&&!Pe.importScripts&&Sr&&Sr.protocol!=="file:"&&!Ef(If)?(Gt=If,Pe.addEventListener("message",Tf,!1)):yf in Sf("script")?Gt=function(a){gf.appendChild(Sf("script"))[yf]=function(){gf.removeChild(this),qo(a)}}:Gt=function(a){setTimeout(No(a),0)});xf.exports={set:Fo,clear:Uo}});var wf=b((QD,Af)=>{"use strict";var Pf=Y(),fP=Me(),mP=Object.getOwnPropertyDescriptor;Af.exports=function(a){if(!fP)return Pf[a];var e=mP(Pf,a);return e&&e.value}});var jo=b((WD,Rf)=>{"use strict";var kf=function(){this.head=null,this.tail=null};kf.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}}};Rf.exports=kf});var Lf=b((YD,$f)=>{"use strict";var bP=Si();$f.exports=/ipad|iphone|ipod/i.test(bP)&&typeof Pebble!="undefined"});var Df=b((zD,Mf)=>{"use strict";var gP=Si();Mf.exports=/web0s(?!.*chrome)/i.test(gP)});var Ff=b((KD,Nf)=>{"use strict";var Pi=Y(),SP=wf(),Cf=lr(),Go=Ho().set,vP=jo(),yP=Co(),TP=Lf(),IP=Df(),Qo=hs(),Vf=Pi.MutationObserver||Pi.WebKitMutationObserver,Bf=Pi.document,Of=Pi.process,fs=Pi.Promise,zo=SP("queueMicrotask"),xi,Wo,Yo,ms,_f;zo||(vr=new vP,yr=function(){var a,e;for(Qo&&(a=Of.domain)&&a.exit();e=vr.get();)try{e()}catch(t){throw vr.head&&xi(),t}a&&a.enter()},!yP&&!Qo&&!IP&&Vf&&Bf?(Wo=!0,Yo=Bf.createTextNode(""),new Vf(yr).observe(Yo,{characterData:!0}),xi=function(){Yo.data=Wo=!Wo}):!TP&&fs&&fs.resolve?(ms=fs.resolve(void 0),ms.constructor=fs,_f=Cf(ms.then,ms),xi=function(){_f(yr)}):Qo?xi=function(){Of.nextTick(yr)}:(Go=Cf(Go,Pi),xi=function(){Go(yr)}),zo=function(a){vr.head||xi(),vr.add(a)});var vr,yr;Nf.exports=zo});var qf=b((XD,Uf)=>{"use strict";Uf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var bs=b((JD,Hf)=>{"use strict";Hf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Qt=b((ZD,jf)=>{"use strict";var EP=Y();jf.exports=EP.Promise});var Ai=b((eC,Yf)=>{"use strict";var xP=Y(),Tr=Qt(),PP=W(),AP=no(),wP=Lo(),kP=ue(),Gf=Ro(),RP=He(),Ko=Nn(),Qf=Tr&&Tr.prototype,$P=kP("species"),Xo=!1,Wf=PP(xP.PromiseRejectionEvent),LP=AP("Promise",function(){var a=wP(Tr),e=a!==String(Tr);if(!e&&Ko===66||RP&&!(Qf.catch&&Qf.finally))return!0;if(!Ko||Ko<51||!/native code/.test(a)){var t=new Tr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[$P]=i,Xo=t.then(function(){})instanceof i,!Xo)return!0}return!e&&(Gf==="BROWSER"||Gf==="DENO")&&!Wf});Yf.exports={CONSTRUCTOR:LP,REJECTION_EVENT:Wf,SUBCLASSING:Xo}});var wi=b((tC,Kf)=>{"use strict";var zf=at(),MP=TypeError,DP=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new MP("Bad Promise constructor");e=i,t=r}),this.resolve=zf(e),this.reject=zf(t)};Kf.exports.f=function(a){return new DP(a)}});var mm=b(()=>{"use strict";var CP=De(),VP=He(),ys=hs(),yt=Y(),Li=xe(),Xf=Ei(),Jf=Eo(),BP=pr(),OP=Kh(),_P=at(),vs=W(),NP=Le(),FP=Jh(),UP=Do(),rm=Ho().set,iu=Ff(),qP=qf(),HP=bs(),jP=jo(),am=ro(),Ts=Qt(),ru=Ai(),sm=wi(),Is="Promise",nm=ru.CONSTRUCTOR,GP=ru.REJECTION_EVENT,QP=ru.SUBCLASSING,Jo=am.getterFor(Is),WP=am.set,ki=Ts&&Ts.prototype,Wt=Ts,gs=ki,om=yt.TypeError,Zo=yt.document,au=yt.process,eu=sm.f,YP=eu,zP=!!(Zo&&Zo.createEvent&&yt.dispatchEvent),um="unhandledrejection",KP="rejectionhandled",Zf=0,lm=1,XP=2,su=1,cm=2,Ss,em,JP,tm,dm=function(a){var e;return NP(a)&&vs(e=a.then)?e:!1},pm=function(a,e){var t=e.value,i=e.state===lm,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{r?(i||(e.rejection===cm&&eA(e),e.rejection=su),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new om("Promise-chain cycle")):(l=dm(u))?Li(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},hm=function(a,e){a.notified||(a.notified=!0,iu(function(){for(var t=a.reactions,i;i=t.get();)pm(i,a);a.notified=!1,e&&!a.rejection&&ZP(a)}))},fm=function(a,e,t){var i,r;zP?(i=Zo.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),yt.dispatchEvent(i)):i={promise:e,reason:t},!GP&&(r=yt["on"+a])?r(i):a===um&&qP("Unhandled promise rejection",t)},ZP=function(a){Li(rm,yt,function(){var e=a.facade,t=a.value,i=im(a),r;if(i&&(r=HP(function(){ys?au.emit("unhandledRejection",t,e):fm(um,e,t)}),a.rejection=ys||im(a)?cm:su,r.error))throw r.value})},im=function(a){return a.rejection!==su&&!a.parent},eA=function(a){Li(rm,yt,function(){var e=a.facade;ys?au.emit("rejectionHandled",e):fm(KP,e,a.value)})},Ri=function(a,e,t){return function(i){a(e,i,t)}},$i=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=XP,hm(a,!0))},tu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new om("Promise can't be resolved itself");var i=dm(e);i?iu(function(){var r={done:!1};try{Li(i,e,Ri(tu,r,a),Ri($i,r,a))}catch(s){$i(r,s,a)}}):(a.value=e,a.state=lm,hm(a,!1))}catch(r){$i({done:!1},r,a)}}};if(nm&&(Wt=function(e){FP(this,gs),_P(e),Li(Ss,this);var t=Jo(this);try{e(Ri(tu,t),Ri($i,t))}catch(i){$i(t,i)}},gs=Wt.prototype,Ss=function(e){WP(this,{type:Is,done:!1,notified:!1,parent:!1,reactions:new jP,rejection:!1,state:Zf,value:void 0})},Ss.prototype=Xf(gs,"then",function(e,t){var i=Jo(this),r=eu(UP(this,Wt));return i.parent=!0,r.ok=vs(e)?e:!0,r.fail=vs(t)&&t,r.domain=ys?au.domain:void 0,i.state===Zf?i.reactions.add(r):iu(function(){pm(r,i)}),r.promise}),em=function(){var a=new Ss,e=Jo(a);this.promise=a,this.resolve=Ri(tu,e),this.reject=Ri($i,e)},sm.f=eu=function(a){return a===Wt||a===JP?new em(a):YP(a)},!VP&&vs(Ts)&&ki!==Object.prototype)){tm=ki.then,QP||Xf(ki,"then",function(e,t){var i=this;return new Wt(function(r,s){Li(tm,i,r,s)}).then(e,t)},{unsafe:!0});try{delete ki.constructor}catch(a){}Jf&&Jf(ki,gs)}CP({global:!0,constructor:!0,wrap:!0,forced:nm},{Promise:Wt});BP(Wt,Is,!1,!0);OP(Is)});var ym=b((aC,vm)=>{"use strict";var tA=ue(),gm=tA("iterator"),Sm=!1;try{bm=0,nu={next:function(){return{done:!!bm++}},return:function(){Sm=!0}},nu[gm]=function(){return this},Array.from(nu,function(){throw 2})}catch(a){}var bm,nu;vm.exports=function(a,e){try{if(!e&&!Sm)return!1}catch(r){return!1}var t=!1;try{var i={};i[gm]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var ou=b((sC,Tm)=>{"use strict";var iA=Qt(),rA=ym(),aA=Ai().CONSTRUCTOR;Tm.exports=aA||!rA(function(a){iA.all(a).then(void 0,function(){})})});var Im=b(()=>{"use strict";var sA=De(),nA=xe(),oA=at(),uA=wi(),lA=bs(),cA=cs(),dA=ou();sA({target:"Promise",stat:!0,forced:dA},{all:function(e){var t=this,i=uA.f(t),r=i.resolve,s=i.reject,n=lA(function(){var o=oA(t.resolve),u=[],l=0,d=1;cA(e,function(c){var h=l++,p=!1;d++,nA(o,t,c).then(function(f){p||(p=!0,u[h]=f,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var xm=b(()=>{"use strict";var pA=De(),hA=He(),fA=Ai().CONSTRUCTOR,lu=Qt(),mA=rt(),bA=W(),gA=Ei(),Em=lu&&lu.prototype;pA({target:"Promise",proto:!0,forced:fA,real:!0},{catch:function(a){return this.then(void 0,a)}});!hA&&bA(lu)&&(uu=mA("Promise").prototype.catch,Em.catch!==uu&&gA(Em,"catch",uu,{unsafe:!0}));var uu});var Pm=b(()=>{"use strict";var SA=De(),vA=xe(),yA=at(),TA=wi(),IA=bs(),EA=cs(),xA=ou();SA({target:"Promise",stat:!0,forced:xA},{race:function(e){var t=this,i=TA.f(t),r=i.reject,s=IA(function(){var n=yA(t.resolve);EA(e,function(o){vA(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Am=b(()=>{"use strict";var PA=De(),AA=wi(),wA=Ai().CONSTRUCTOR;PA({target:"Promise",stat:!0,forced:wA},{reject:function(e){var t=AA.f(this),i=t.reject;return i(e),t.promise}})});var cu=b((fC,wm)=>{"use strict";var kA=Xe(),RA=Le(),$A=wi();wm.exports=function(a,e){if(kA(a),RA(e)&&e.constructor===a)return e;var t=$A.f(a),i=t.resolve;return i(e),t.promise}});var $m=b(()=>{"use strict";var LA=De(),MA=rt(),km=He(),DA=Qt(),Rm=Ai().CONSTRUCTOR,CA=cu(),VA=MA("Promise"),BA=km&&!Rm;LA({target:"Promise",stat:!0,forced:km||Rm},{resolve:function(e){return CA(BA&&this===VA?DA:this,e)}})});var Lm=b(()=>{"use strict";mm();Im();xm();Pm();Am();$m()});var Vm=b(()=>{"use strict";var OA=De(),_A=He(),Es=Qt(),NA=Ee(),Dm=rt(),Cm=W(),FA=Do(),Mm=cu(),UA=Ei(),pu=Es&&Es.prototype,qA=!!Es&&NA(function(){pu.finally.call({then:function(){}},function(){})});OA({target:"Promise",proto:!0,real:!0,forced:qA},{finally:function(a){var e=FA(this,Dm("Promise")),t=Cm(a);return this.then(t?function(i){return Mm(e,a()).then(function(){return i})}:a,t?function(i){return Mm(e,a()).then(function(){throw i})}:a)}});!_A&&Cm(Es)&&(du=Dm("Promise").prototype.finally,pu.finally!==du&&UA(pu,"finally",du,{unsafe:!0}));var du});var xs=b((TC,Bm)=>{"use strict";var HA=rt();Bm.exports=HA});var _m=b((IC,Om)=>{"use strict";Hh();Lm();Vm();var jA=xs();Om.exports=jA("Promise","finally")});var Fm=b((EC,Nm)=>{"use strict";var GA=_m();Nm.exports=GA});var Ps=b((xC,Um)=>{"use strict";var QA=Fm();Um.exports=QA});var pb=b(()=>{"use strict";var Tw=De(),Iw=sr(),Ew=ts(),xw=es(),Pw=$n();Tw({target:"Array",proto:!0},{at:function(e){var t=Iw(this),i=Ew(t),r=xw(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});Pw("at")});var fb=b((D0,hb)=>{"use strict";pb();var Aw=xs();hb.exports=Aw("Array","at")});var bb=b((C0,mb)=>{"use strict";var ww=fb();mb.exports=ww});var Ci=b((V0,gb)=>{"use strict";var kw=bb();gb.exports=kw});var Ig=b(()=>{"use strict"});var Eg=b(()=>{"use strict"});var Pg=b((N_,xg)=>{"use strict";var Ok=Le(),_k=mi(),Nk=ue(),Fk=Nk("match");xg.exports=function(a){var e;return Ok(a)&&((e=a[Fk])!==void 0?!!e:_k(a)==="RegExp")}});var wg=b((F_,Ag)=>{"use strict";var Uk=dr(),qk=String;Ag.exports=function(a){if(Uk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return qk(a)}});var Rg=b((U_,kg)=>{"use strict";var Hk=Xe();kg.exports=function(){var a=Hk(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 Mg=b((q_,Lg)=>{"use strict";var jk=xe(),Gk=je(),Qk=tr(),Wk=Rg(),$g=RegExp.prototype;Lg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in $g)&&!Gk(a,"flags")&&Qk($g,a)?jk(Wk,a):e}});var Cg=b((H_,Dg)=>{"use strict";var Hu=pe(),Yk=sr(),zk=Math.floor,Uu=Hu("".charAt),Kk=Hu("".replace),qu=Hu("".slice),Xk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Jk=/\$([$&'`]|\d{1,2})/g;Dg.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=Jk;return r!==void 0&&(r=Yk(r),u=Xk),Kk(s,u,function(l,d){var c;switch(Uu(d,0)){case"$":return"$";case"&":return a;case"`":return qu(e,0,t);case"'":return qu(e,n);case"<":c=r[qu(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=zk(h/10);return p===0?l:p<=o?i[p-1]===void 0?Uu(d,1):i[p-1]+Uu(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var Og=b(()=>{"use strict";var Zk=De(),eR=xe(),Gu=pe(),Vg=Zi(),tR=W(),iR=bi(),rR=Pg(),Fi=wg(),aR=rr(),sR=Mg(),nR=Cg(),oR=ue(),uR=He(),lR=oR("replace"),cR=TypeError,ju=Gu("".indexOf),dR=Gu("".replace),Bg=Gu("".slice),pR=Math.max;Zk({target:"String",proto:!0},{replaceAll:function(e,t){var i=Vg(this),r,s,n,o,u,l,d,c,h,p,f=0,m="";if(!iR(e)){if(r=rR(e),r&&(s=Fi(Vg(sR(e))),!~ju(s,"g")))throw new cR("`.replaceAll` does not allow non-global regexes");if(n=aR(e,lR),n)return eR(n,e,i,t);if(uR&&r)return dR(Fi(i),e,t)}for(o=Fi(i),u=Fi(e),l=tR(t),l||(t=Fi(t)),d=u.length,c=pR(1,d),h=ju(o,u);h!==-1;)p=l?Fi(t(u,h,o)):nR(u,o,h,[],void 0,t),m+=Bg(o,f,h)+p,f=h+d,h=h+c>o.length?-1:ju(o,u,h+c);return f<o.length&&(m+=Bg(o,f)),m}})});var Ng=b((Q_,_g)=>{"use strict";Ig();Eg();Og();var hR=xs();_g.exports=hR("String","replaceAll")});var Ug=b((W_,Fg)=>{"use strict";var fR=Ng();Fg.exports=fR});var Hg=b((Y_,qg)=>{"use strict";var mR=Ug();qg.exports=mR});var nc="2.0.117-dev.d9cc3d97.0";var de=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(de||{}),vt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(vt||{});var qa=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(qa||{}),xn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(xn||{});var Pn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Pn||{});import{assertNever as pc,assertNonNullable as Mv,isNonNullable as Ha,ValueSubject as An,Subject as Dv,Subscription as Cv,merge as Vv,observableFrom as Bv,fromEvent as uc,map as lc,tap as cc,filterChanged as Ov,isNullable as wn,ErrorCategory as dc}from"@vkontakte/videoplayer-shared";var oc=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var ja=class{constructor(e){this.connection$=new An(void 0);this.castState$=new An("NOT_AVAILABLE");this.errorEvent$=new Dv;this.realCastState$=new An("NOT_AVAILABLE");this.subscription=new Cv;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 i=Ha((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},r||oc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:dc.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 i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ha(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();wn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();wn(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),i=cast.framework.CastContext.getInstance();this.subscription.add(uc(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.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 pc(r.sessionState)}})).add(Vv(uc(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(cc(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),lc(r=>r.castState)),Bv([i.getCastState()])).pipe(Ov(),lc(_v),cc(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=Ha(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();Mv(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(wn(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Ha(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:dc.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},_v=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 pc(a)}};var KS=Ue(ko(),1);var Xm=Ue(Ps(),1);import{assertNever as qm}from"@vkontakte/videoplayer-shared";var se=(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 i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:qm(t)}return a},hu=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:qm(e)}};var x=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as WA,Subject as As,merge as Hm}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new As;this.transitionEnded$=new As;this.transitionUpdated$=new As;this.forceChanged$=new As;this.stateChangeStarted$=Hm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Hm(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||WA(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as YA}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 YA(a)}};import{assertNever as Mi,assertNonNullable as Yt,debounce as Gm,ErrorCategory as Qm,fromEvent as zt,isNonNullable as Wm,map as Ym,merge as zm,observableFrom as zA,Subject as KA,Subscription as fu,timeout as XA,getHighestQuality as JA}from"@vkontakte/videoplayer-shared";var ZA=5,ew=5,tw=500,Km=7e3,Ir=class{constructor(e){this.subscription=new fu;this.loadMediaTimeoutSubscription=new fu;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Mi(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:Mi(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:Mi(e)}break}default:Mi(i)}}};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 fu;this.subscription.add(e),this.subscription.add(zm(this.videoState.stateChangeStarted$.pipe(Ym(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Ym(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new KA;e.add(r.pipe(Gm(tw)).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)>ZA)&&r.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),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.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<ew&&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:Mi(n)}}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=zm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zA(["init"])).pipe(Gm(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),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 r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let d=t[e];Yt(d);let c=JA(Object.keys(d));Yt(c);let h=d[c];Yt(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];Yt(d),i=d.url,r="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 d=t[e];Yt(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];Yt(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];Yt(d),i=se(d.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Qm.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Mi(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Wm(o)&&(n.metadata.title=o),Wm(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(XA(Km).subscribe(()=>s(`timeout(${Km})`)))});(0,Xm.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Qm.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Zm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as iw}from"@vkontakte/videoplayer-shared";var Jm=a=>{try{a.pause(),a.playbackRate=0,iw(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as rw,Subscription as aw}from"@vkontakte/videoplayer-shared";var mu=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)}},bu=window.WeakMap?new WeakMap:new mu,gu=window.WeakMap?new WeakMap:new Map,sw=(a,e=20)=>{let t=0;return rw(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},he=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),i=!!t;t?Zm(t):(t=document.createElement("video"),a.appendChild(t)),bu.set(t,i);let r=new aw;return r.add(sw(t,e)),gu.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},fe=a=>{let e=gu.get(a);e==null||e.unsubscribe(),gu.delete(a);let t=bu.get(a);bu.delete(a),t?Zm(a):Jm(a)};import{assertNonNullable as Er,isNonNullable as Ze,isNullable as uw,fromEvent as Di,merge as eb,observableFrom as tb,filterChanged as ib,map as xr,Subject as rb,Subscription as lw,ValueSubject as cw,ErrorCategory as dw}from"@vkontakte/videoplayer-shared";import{isNonNullable as Su,isNullable as nw,Subscription as ow}from"@vkontakte/videoplayer-shared";var ws=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=nw(r),l=new ow;return r&&l.add(r.subscribe(d=>{let c=a.getState();i(d,c)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},Je=(a,e,t)=>ws(e,()=>a.loop,i=>{Su(i)&&(a.loop=i)},{onError:t}),me=(a,e,t,i)=>ws(e,()=>({muted:a.muted,volume:a.volume}),r=>{Su(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ce=(a,e,t,i)=>ws(e,()=>a.playbackRate,r=>{Su(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Tt=ws;var pw=a=>["__",a.language,a.label].join("|"),hw=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},vu=class a{constructor(){this.available$=new rb;this.current$=new cw(void 0);this.error$=new rb;this.subscription=new lw;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:dw.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Tt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ze(s)&&this.setInternal(s)},{equal:(s,n)=>Ze(s)&&Ze(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(xr(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Tt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ze(s)&&this.setExternal(s)},{equal:(s,n)=>Ze(s)&&Ze(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(xr(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Tt(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:r})),this.subscription.add(Tt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Er(this.video);let{textTracks:e}=this.video;this.subscription.add(Di(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(eb(Di(e,"addtrack"),Di(e,"removetrack"),tb(["init"])).pipe(xr(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ib((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(eb(Di(e,"change"),tb(["init"])).pipe(xr(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),xr(i=>i&&this.htmlTextTrackToITextTrack(i).id),ib()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Di(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,d,c,h,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Di(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Ze(t.align)&&(r.align=t.align),Ze(t.position)&&(r.position=t.position),Ze(t.size)&&(r.size=t.size),Ze(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Er(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:pw(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Er(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(uw(e)||!hw(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){Er(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){Er(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ve=vu;var ot=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var ab=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},yu=a=>{let e=ab(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},sb=a=>{let e=ab(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Be,map as It,merge as ob,filterChanged as mw,isNonNullable as ub,Subject as bw,filter as lb,mapTo as cb,combine as gw,once as Sw,ErrorCategory as vw,ValueSubject as db,clientChecker as yw}from"@vkontakte/videoplayer-shared";var fw=3,nb=(a,e,t=fw)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var be=a=>{let e=T=>Be(a,T).pipe(cb(void 0)),i=ob(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Be(a,T))).pipe(It(T=>T.type==="ended"?a.readyState<2:a.readyState<3),mw()),r=ob(Be(a,"progress"),Be(a,"timeupdate")).pipe(It(()=>nb(a.buffered,a.currentTime))),s=yw.isSafari?gw({play:e("play").pipe(Sw()),playing:e("playing")}).pipe(cb(void 0)):e("playing"),n=Be(a,"volumechange").pipe(It(()=>({muted:a.muted,volume:a.volume}))),o=Be(a,"ratechange").pipe(It(()=>a.playbackRate)),u=Be(a,"error").pipe(lb(()=>!!(a.error||a.played.length)),It(()=>{var E;let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:vw.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=Be(a,"timeupdate").pipe(It(()=>a.currentTime)),d=new bw,c=.3,h;l.subscribe(T=>{a.loop&&ub(h)&&ub(T)&&h>=a.duration-c&&T<=c&&d.next(h),h=T});let p=e("pause").pipe(lb(()=>!a.error&&h!==a.duration)),f=Be(a,"enterpictureinpicture"),m=Be(a,"leavepictureinpicture"),g=new db(sb(a));f.subscribe(()=>g.next(!0)),m.subscribe(()=>g.next(!1));let v=new db(yu(a));return Be(a,"fullscreenchange").pipe(It(()=>yu(a))).subscribe(v),{playing$:s,pause$:p,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Be(a,"durationchange").pipe(It(()=>a.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as Et}from"@vkontakte/videoplayer-shared";var xt=a=>{switch(a){case"mobile":return Et.Q_144P;case"lowest":return Et.Q_240P;case"low":return Et.Q_360P;case"sd":case"medium":return Et.Q_480P;case"hd":case"high":return Et.Q_720P;case"fullhd":case"full":return Et.Q_1080P;case"quadhd":case"quad":return Et.Q_1440P;case"ultrahd":case"ultra":return Et.Q_2160P}};var Pt=Ue(Ci(),1);import{isNonNullable as ee,isNullable as Iu,now as xb,isHigher as Eu,isHigherOrEqual as xu,isInvariantQuality as Tb,isLower as Ib,isLowerOrEqual as Pu,videoSizeToQuality as Rw,assertNotEmptyArray as Pb,assertNonNullable as $w}from"@vkontakte/videoplayer-shared";var Tu=!1,ut={},Sb=a=>{Tu=a},vb=()=>{ut={}},yb=a=>{a(ut)},Pr=(a,e)=>{var t;Tu&&(ut.meta=(t=ut.meta)!=null?t:{},ut.meta[a]=e)},le=class{constructor(e){this.name=e}next(e){var i,r;if(!Tu)return;ut.series=(i=ut.series)!=null?i:{};let t=(r=ut.series[this.name])!=null?r:[];t.push([Date.now(),e]),ut.series[this.name]=t}};var Lw=new le("best_bitrate"),Ab=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Au=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ar=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=xb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},wb='Assertion "ABR Tracks is empty array" failed',ks=(a,e,t,i)=>{var u;let r=[...e].sort(Au(1)),s=[...t].sort(Au(1)),n=s.filter(l=>ee(l.bitrate)&&ee(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Pt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Pt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,Pt.default)(n,-1):(0,Pt.default)(s,0)},Eb=a=>"quality"in a,kb=(a,e,t,i)=>{var n;let r=ee((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&ee(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&xb()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Eb(o)?"video":"audio",l=Eb(o)?o.quality:o.bitrate;return e({message:`
6
+ var LT=Object.create;var Oc=Object.defineProperty;var MT=Object.getOwnPropertyDescriptor;var CT=Object.getOwnPropertyNames;var DT=Object.getPrototypeOf,OT=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var BT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of CT(e))!OT.call(a,i)&&i!==t&&Oc(a,i,{get:()=>e[i],enumerable:!(r=MT(e,i))||r.enumerable});return a};var L=(a,e,t)=>(t=a!=null?LT(DT(a)):{},BT(e||!a||!a.__esModule?Oc(t,"default",{value:a,enumerable:!0}):t,a));var z=m((qn,Vc)=>{"use strict";var li=function(a){return a&&a.Math===Math&&a};Vc.exports=li(typeof globalThis=="object"&&globalThis)||li(typeof window=="object"&&window)||li(typeof self=="object"&&self)||li(typeof global=="object"&&global)||li(typeof qn=="object"&&qn)||function(){return this}()||Function("return this")()});var ue=m((tD,_c)=>{"use strict";_c.exports=function(a){try{return!!a()}catch(e){return!0}}});var ci=m((rD,Nc)=>{"use strict";var VT=ue();Nc.exports=!VT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Un=m((iD,Hc)=>{"use strict";var _T=ci(),Uc=Function.prototype,Fc=Uc.apply,qc=Uc.call;Hc.exports=typeof Reflect=="object"&&Reflect.apply||(_T?qc.bind(Fc):function(){return qc.apply(Fc,arguments)})});var te=m((aD,Qc)=>{"use strict";var jc=ci(),Gc=Function.prototype,Hn=Gc.call,NT=jc&&Gc.bind.bind(Hn,Hn);Qc.exports=jc?NT:function(a){return function(){return Hn.apply(a,arguments)}}});var zt=m((sD,Yc)=>{"use strict";var Wc=te(),FT=Wc({}.toString),qT=Wc("".slice);Yc.exports=function(a){return qT(FT(a),8,-1)}});var jn=m((nD,zc)=>{"use strict";var UT=zt(),HT=te();zc.exports=function(a){if(UT(a)==="Function")return HT(a)}});var Y=m((oD,Kc)=>{"use strict";var Gn=typeof document=="object"&&document.all;Kc.exports=typeof Gn=="undefined"&&Gn!==void 0?function(a){return typeof a=="function"||a===Gn}:function(a){return typeof a=="function"}});var xe=m((uD,Jc)=>{"use strict";var jT=ue();Jc.exports=!jT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Pe=m((lD,Xc)=>{"use strict";var GT=ci(),is=Function.prototype.call;Xc.exports=GT?is.bind(is):function(){return is.apply(is,arguments)}});var Qn=m(td=>{"use strict";var Zc={}.propertyIsEnumerable,ed=Object.getOwnPropertyDescriptor,QT=ed&&!Zc.call({1:2},1);td.f=QT?function(e){var t=ed(this,e);return!!t&&t.enumerable}:Zc});var di=m((dD,rd)=>{"use strict";rd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var ad=m((pD,id)=>{"use strict";var WT=te(),YT=ue(),zT=zt(),Wn=Object,KT=WT("".split);id.exports=YT(function(){return!Wn("z").propertyIsEnumerable(0)})?function(a){return zT(a)==="String"?KT(a,""):Wn(a)}:Wn});var Pr=m((hD,sd)=>{"use strict";sd.exports=function(a){return a==null}});var At=m((fD,nd)=>{"use strict";var JT=Pr(),XT=TypeError;nd.exports=function(a){if(JT(a))throw new XT("Can't call method on "+a);return a}});var Kt=m((mD,od)=>{"use strict";var ZT=ad(),eI=At();od.exports=function(a){return ZT(eI(a))}});var Ae=m((bD,ud)=>{"use strict";var tI=Y();ud.exports=function(a){return typeof a=="object"?a!==null:tI(a)}});var Ar=m((gD,ld)=>{"use strict";ld.exports={}});var st=m((vD,dd)=>{"use strict";var Yn=Ar(),zn=z(),rI=Y(),cd=function(a){return rI(a)?a:void 0};dd.exports=function(a,e){return arguments.length<2?cd(Yn[a])||cd(zn[a]):Yn[a]&&Yn[a][e]||zn[a]&&zn[a][e]}});var pi=m((SD,pd)=>{"use strict";var iI=te();pd.exports=iI({}.isPrototypeOf)});var Jt=m((yD,md)=>{"use strict";var aI=z(),hd=aI.navigator,fd=hd&&hd.userAgent;md.exports=fd?String(fd):""});var Jn=m((TD,Td)=>{"use strict";var yd=z(),Kn=Jt(),bd=yd.process,gd=yd.Deno,vd=bd&&bd.versions||gd&&gd.version,Sd=vd&&vd.v8,Ue,as;Sd&&(Ue=Sd.split("."),as=Ue[0]>0&&Ue[0]<4?1:+(Ue[0]+Ue[1]));!as&&Kn&&(Ue=Kn.match(/Edge\/(\d+)/),(!Ue||Ue[1]>=74)&&(Ue=Kn.match(/Chrome\/(\d+)/),Ue&&(as=+Ue[1])));Td.exports=as});var Xn=m((ID,Ed)=>{"use strict";var Id=Jn(),sI=ue(),nI=z(),oI=nI.String;Ed.exports=!!Object.getOwnPropertySymbols&&!sI(function(){var a=Symbol("symbol detection");return!oI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Id&&Id<41})});var Zn=m((ED,xd)=>{"use strict";var uI=Xn();xd.exports=uI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var eo=m((xD,Pd)=>{"use strict";var lI=st(),cI=Y(),dI=pi(),pI=Zn(),hI=Object;Pd.exports=pI?function(a){return typeof a=="symbol"}:function(a){var e=lI("Symbol");return cI(e)&&dI(e.prototype,hI(a))}});var hi=m((PD,Ad)=>{"use strict";var fI=String;Ad.exports=function(a){try{return fI(a)}catch(e){return"Object"}}});var Ke=m((AD,wd)=>{"use strict";var mI=Y(),bI=hi(),gI=TypeError;wd.exports=function(a){if(mI(a))return a;throw new gI(bI(a)+" is not a function")}});var fi=m((wD,kd)=>{"use strict";var vI=Ke(),SI=Pr();kd.exports=function(a,e){var t=a[e];return SI(t)?void 0:vI(t)}});var $d=m((kD,Rd)=>{"use strict";var to=Pe(),ro=Y(),io=Ae(),yI=TypeError;Rd.exports=function(a,e){var t,r;if(e==="string"&&ro(t=a.toString)&&!io(r=to(t,a))||ro(t=a.valueOf)&&!io(r=to(t,a))||e!=="string"&&ro(t=a.toString)&&!io(r=to(t,a)))return r;throw new yI("Can't convert object to primitive value")}});var He=m((RD,Ld)=>{"use strict";Ld.exports=!0});var Dd=m(($D,Cd)=>{"use strict";var Md=z(),TI=Object.defineProperty;Cd.exports=function(a,e){try{TI(Md,a,{value:e,configurable:!0,writable:!0})}catch(t){Md[a]=e}return e}});var mi=m((LD,Vd)=>{"use strict";var II=He(),EI=z(),xI=Dd(),Od="__core-js_shared__",Bd=Vd.exports=EI[Od]||xI(Od,{});(Bd.versions||(Bd.versions=[])).push({version:"3.38.0",mode:II?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var ao=m((MD,Nd)=>{"use strict";var _d=mi();Nd.exports=function(a,e){return _d[a]||(_d[a]=e||{})}});var wr=m((CD,Fd)=>{"use strict";var PI=At(),AI=Object;Fd.exports=function(a){return AI(PI(a))}});var je=m((DD,qd)=>{"use strict";var wI=te(),kI=wr(),RI=wI({}.hasOwnProperty);qd.exports=Object.hasOwn||function(e,t){return RI(kI(e),t)}});var so=m((OD,Ud)=>{"use strict";var $I=te(),LI=0,MI=Math.random(),CI=$I(1 .toString);Ud.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+CI(++LI+MI,36)}});var le=m((BD,jd)=>{"use strict";var DI=z(),OI=ao(),Hd=je(),BI=so(),VI=Xn(),_I=Zn(),kr=DI.Symbol,no=OI("wks"),NI=_I?kr.for||kr:kr&&kr.withoutSetter||BI;jd.exports=function(a){return Hd(no,a)||(no[a]=VI&&Hd(kr,a)?kr[a]:NI("Symbol."+a)),no[a]}});var Yd=m((VD,Wd)=>{"use strict";var FI=Pe(),Gd=Ae(),Qd=eo(),qI=fi(),UI=$d(),HI=le(),jI=TypeError,GI=HI("toPrimitive");Wd.exports=function(a,e){if(!Gd(a)||Qd(a))return a;var t=qI(a,GI),r;if(t){if(e===void 0&&(e="default"),r=FI(t,a,e),!Gd(r)||Qd(r))return r;throw new jI("Can't convert object to primitive value")}return e===void 0&&(e="number"),UI(a,e)}});var oo=m((_D,zd)=>{"use strict";var QI=Yd(),WI=eo();zd.exports=function(a){var e=QI(a,"string");return WI(e)?e:e+""}});var ss=m((ND,Jd)=>{"use strict";var YI=z(),Kd=Ae(),uo=YI.document,zI=Kd(uo)&&Kd(uo.createElement);Jd.exports=function(a){return zI?uo.createElement(a):{}}});var lo=m((FD,Xd)=>{"use strict";var KI=xe(),JI=ue(),XI=ss();Xd.exports=!KI&&!JI(function(){return Object.defineProperty(XI("div"),"a",{get:function(){return 7}}).a!==7})});var tp=m(ep=>{"use strict";var ZI=xe(),eE=Pe(),tE=Qn(),rE=di(),iE=Kt(),aE=oo(),sE=je(),nE=lo(),Zd=Object.getOwnPropertyDescriptor;ep.f=ZI?Zd:function(e,t){if(e=iE(e),t=aE(t),nE)try{return Zd(e,t)}catch(r){}if(sE(e,t))return rE(!eE(tE.f,e,t),e[t])}});var co=m((UD,rp)=>{"use strict";var oE=ue(),uE=Y(),lE=/#|\.prototype\./,bi=function(a,e){var t=dE[cE(a)];return t===hE?!0:t===pE?!1:uE(e)?oE(e):!!e},cE=bi.normalize=function(a){return String(a).replace(lE,".").toLowerCase()},dE=bi.data={},pE=bi.NATIVE="N",hE=bi.POLYFILL="P";rp.exports=bi});var Rr=m((HD,ap)=>{"use strict";var ip=jn(),fE=Ke(),mE=ci(),bE=ip(ip.bind);ap.exports=function(a,e){return fE(a),e===void 0?a:mE?bE(a,e):function(){return a.apply(e,arguments)}}});var po=m((jD,sp)=>{"use strict";var gE=xe(),vE=ue();sp.exports=gE&&vE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Je=m((GD,np)=>{"use strict";var SE=Ae(),yE=String,TE=TypeError;np.exports=function(a){if(SE(a))return a;throw new TE(yE(a)+" is not an object")}});var Xt=m(up=>{"use strict";var IE=xe(),EE=lo(),xE=po(),ns=Je(),op=oo(),PE=TypeError,ho=Object.defineProperty,AE=Object.getOwnPropertyDescriptor,fo="enumerable",mo="configurable",bo="writable";up.f=IE?xE?function(e,t,r){if(ns(e),t=op(t),ns(r),typeof e=="function"&&t==="prototype"&&"value"in r&&bo in r&&!r[bo]){var i=AE(e,t);i&&i[bo]&&(e[t]=r.value,r={configurable:mo in r?r[mo]:i[mo],enumerable:fo in r?r[fo]:i[fo],writable:!1})}return ho(e,t,r)}:ho:function(e,t,r){if(ns(e),t=op(t),ns(r),EE)try{return ho(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new PE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var $r=m((WD,lp)=>{"use strict";var wE=xe(),kE=Xt(),RE=di();lp.exports=wE?function(a,e,t){return kE.f(a,e,RE(1,t))}:function(a,e,t){return a[e]=t,a}});var X=m((YD,dp)=>{"use strict";var gi=z(),$E=Un(),LE=jn(),ME=Y(),CE=tp().f,DE=co(),Lr=Ar(),OE=Rr(),Mr=$r(),cp=je();mi();var BE=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 $E(a,this,arguments)};return e.prototype=a.prototype,e};dp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?gi:i?gi[t]:gi[t]&&gi[t].prototype,o=r?Lr:Lr[t]||Mr(Lr,t,{})[t],u=o.prototype,l,d,c,p,h,f,b,g,v;for(p in e)l=DE(r?p:t+(i?".":"#")+p,a.forced),d=!l&&n&&cp(n,p),f=o[p],d&&(a.dontCallGetSet?(v=CE(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&d?g=OE(h,gi):a.wrap&&d?g=BE(h):s&&ME(h)?g=LE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Mr(g,"sham",!0),Mr(o,p,g),s&&(c=t+"Prototype",cp(Lr,c)||Mr(Lr,c,{}),Mr(Lr[c],p,h),a.real&&u&&(l||!u[p])&&Mr(u,p,h)))}});var hp=m((zD,pp)=>{"use strict";var VE=Math.ceil,_E=Math.floor;pp.exports=Math.trunc||function(e){var t=+e;return(t>0?_E:VE)(t)}});var vi=m((KD,fp)=>{"use strict";var NE=hp();fp.exports=function(a){var e=+a;return e!==e||e===0?0:NE(e)}});var bp=m((JD,mp)=>{"use strict";var FE=vi(),qE=Math.max,UE=Math.min;mp.exports=function(a,e){var t=FE(a);return t<0?qE(t+e,0):UE(t,e)}});var go=m((XD,gp)=>{"use strict";var HE=vi(),jE=Math.min;gp.exports=function(a){var e=HE(a);return e>0?jE(e,9007199254740991):0}});var Cr=m((ZD,vp)=>{"use strict";var GE=go();vp.exports=function(a){return GE(a.length)}});var vo=m((eO,yp)=>{"use strict";var QE=Kt(),WE=bp(),YE=Cr(),Sp=function(a){return function(e,t,r){var i=QE(e),s=YE(i);if(s===0)return!a&&-1;var n=WE(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}};yp.exports={includes:Sp(!0),indexOf:Sp(!1)}});var Si=m((tO,Tp)=>{"use strict";Tp.exports=function(){}});var Ip=m(()=>{"use strict";var zE=X(),KE=vo().includes,JE=ue(),XE=Si(),ZE=JE(function(){return!Array(1).includes()});zE({target:"Array",proto:!0,forced:ZE},{includes:function(e){return KE(this,e,arguments.length>1?arguments[1]:void 0)}});XE("includes")});var wt=m((aO,Ep)=>{"use strict";var ex=st();Ep.exports=ex});var Pp=m((sO,xp)=>{"use strict";Ip();var tx=wt();xp.exports=tx("Array","includes")});var wp=m((nO,Ap)=>{"use strict";var rx=Pp();Ap.exports=rx});var Xe=m((oO,kp)=>{"use strict";var ix=wp();kp.exports=ix});var ls=m((SO,Bp)=>{"use strict";var dx=ao(),px=so(),Op=dx("keys");Bp.exports=function(a){return Op[a]||(Op[a]=px(a))}});var _p=m((yO,Vp)=>{"use strict";var hx=ue();Vp.exports=!hx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var cs=m((TO,Fp)=>{"use strict";var fx=je(),mx=Y(),bx=wr(),gx=ls(),vx=_p(),Np=gx("IE_PROTO"),To=Object,Sx=To.prototype;Fp.exports=vx?To.getPrototypeOf:function(a){var e=bx(a);if(fx(e,Np))return e[Np];var t=e.constructor;return mx(t)&&e instanceof t?t.prototype:e instanceof To?Sx:null}});var ds=m((IO,qp)=>{"use strict";qp.exports={}});var jp=m((EO,Hp)=>{"use strict";var yx=te(),Io=je(),Tx=Kt(),Ix=vo().indexOf,Ex=ds(),Up=yx([].push);Hp.exports=function(a,e){var t=Tx(a),r=0,i=[],s;for(s in t)!Io(Ex,s)&&Io(t,s)&&Up(i,s);for(;e.length>r;)Io(t,s=e[r++])&&(~Ix(i,s)||Up(i,s));return i}});var Eo=m((xO,Gp)=>{"use strict";Gp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var xo=m((PO,Qp)=>{"use strict";var xx=jp(),Px=Eo();Qp.exports=Object.keys||function(e){return xx(e,Px)}});var Po=m((AO,Jp)=>{"use strict";var Yp=xe(),Ax=ue(),zp=te(),wx=cs(),kx=xo(),Rx=Kt(),$x=Qn().f,Kp=zp($x),Lx=zp([].push),Mx=Yp&&Ax(function(){var a=Object.create(null);return a[2]=2,!Kp(a,2)}),Wp=function(a){return function(e){for(var t=Rx(e),r=kx(t),i=Mx&&wx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Yp||(i?u in t:Kp(t,u)))&&Lx(o,a?[u,t[u]]:t[u]);return o}};Jp.exports={entries:Wp(!0),values:Wp(!1)}});var Xp=m(()=>{"use strict";var Cx=X(),Dx=Po().entries;Cx({target:"Object",stat:!0},{entries:function(e){return Dx(e)}})});var eh=m((RO,Zp)=>{"use strict";Xp();var Ox=Ar();Zp.exports=Ox.Object.entries});var rh=m(($O,th)=>{"use strict";var Bx=eh();th.exports=Bx});var kt=m((LO,ih)=>{"use strict";var Vx=rh();ih.exports=Vx});var Zt=m((MO,ah)=>{"use strict";ah.exports={}});var oh=m((CO,nh)=>{"use strict";var _x=z(),Nx=Y(),sh=_x.WeakMap;nh.exports=Nx(sh)&&/native code/.test(String(sh))});var Ro=m((DO,ch)=>{"use strict";var Fx=oh(),lh=z(),qx=Ae(),Ux=$r(),Ao=je(),wo=mi(),Hx=ls(),jx=ds(),uh="Object already initialized",ko=lh.TypeError,Gx=lh.WeakMap,ps,yi,hs,Qx=function(a){return hs(a)?yi(a):ps(a,{})},Wx=function(a){return function(e){var t;if(!qx(e)||(t=yi(e)).type!==a)throw new ko("Incompatible receiver, "+a+" required");return t}};Fx||wo.state?(Ge=wo.state||(wo.state=new Gx),Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,ps=function(a,e){if(Ge.has(a))throw new ko(uh);return e.facade=a,Ge.set(a,e),e},yi=function(a){return Ge.get(a)||{}},hs=function(a){return Ge.has(a)}):(er=Hx("state"),jx[er]=!0,ps=function(a,e){if(Ao(a,er))throw new ko(uh);return e.facade=a,Ux(a,er,e),e},yi=function(a){return Ao(a,er)?a[er]:{}},hs=function(a){return Ao(a,er)});var Ge,er;ch.exports={set:ps,get:yi,has:hs,enforce:Qx,getterFor:Wx}});var Mo=m((OO,ph)=>{"use strict";var $o=xe(),Yx=je(),dh=Function.prototype,zx=$o&&Object.getOwnPropertyDescriptor,Lo=Yx(dh,"name"),Kx=Lo&&function(){}.name==="something",Jx=Lo&&(!$o||$o&&zx(dh,"name").configurable);ph.exports={EXISTS:Lo,PROPER:Kx,CONFIGURABLE:Jx}});var fh=m(hh=>{"use strict";var Xx=xe(),Zx=po(),eP=Xt(),tP=Je(),rP=Kt(),iP=xo();hh.f=Xx&&!Zx?Object.defineProperties:function(e,t){tP(e);for(var r=rP(t),i=iP(t),s=i.length,n=0,o;s>n;)eP.f(e,o=i[n++],r[o]);return e}});var Co=m((VO,mh)=>{"use strict";var aP=st();mh.exports=aP("document","documentElement")});var Vo=m((_O,Ih)=>{"use strict";var sP=Je(),nP=fh(),bh=Eo(),oP=ds(),uP=Co(),lP=ss(),cP=ls(),gh=">",vh="<",Oo="prototype",Bo="script",yh=cP("IE_PROTO"),Do=function(){},Th=function(a){return vh+Bo+gh+a+vh+"/"+Bo+gh},Sh=function(a){a.write(Th("")),a.close();var e=a.parentWindow.Object;return a=null,e},dP=function(){var a=lP("iframe"),e="java"+Bo+":",t;return a.style.display="none",uP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Th("document.F=Object")),t.close(),t.F},fs,ms=function(){try{fs=new ActiveXObject("htmlfile")}catch(e){}ms=typeof document!="undefined"?document.domain&&fs?Sh(fs):dP():Sh(fs);for(var a=bh.length;a--;)delete ms[Oo][bh[a]];return ms()};oP[yh]=!0;Ih.exports=Object.create||function(e,t){var r;return e!==null?(Do[Oo]=sP(e),r=new Do,Do[Oo]=null,r[yh]=e):r=ms(),t===void 0?r:nP.f(r,t)}});var Dr=m((NO,Eh)=>{"use strict";var pP=$r();Eh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:pP(a,e,t),a}});var qo=m((FO,Ah)=>{"use strict";var hP=ue(),fP=Y(),mP=Ae(),bP=Vo(),xh=cs(),gP=Dr(),vP=le(),SP=He(),Fo=vP("iterator"),Ph=!1,nt,_o,No;[].keys&&(No=[].keys(),"next"in No?(_o=xh(xh(No)),_o!==Object.prototype&&(nt=_o)):Ph=!0);var yP=!mP(nt)||hP(function(){var a={};return nt[Fo].call(a)!==a});yP?nt={}:SP&&(nt=bP(nt));fP(nt[Fo])||gP(nt,Fo,function(){return this});Ah.exports={IteratorPrototype:nt,BUGGY_SAFARI_ITERATORS:Ph}});var bs=m((qO,kh)=>{"use strict";var TP=le(),IP=TP("toStringTag"),wh={};wh[IP]="z";kh.exports=String(wh)==="[object z]"});var Ti=m((UO,Rh)=>{"use strict";var EP=bs(),xP=Y(),gs=zt(),PP=le(),AP=PP("toStringTag"),wP=Object,kP=gs(function(){return arguments}())==="Arguments",RP=function(a,e){try{return a[e]}catch(t){}};Rh.exports=EP?gs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=RP(e=wP(a),AP))=="string"?t:kP?gs(e):(r=gs(e))==="Object"&&xP(e.callee)?"Arguments":r}});var Lh=m((HO,$h)=>{"use strict";var $P=bs(),LP=Ti();$h.exports=$P?{}.toString:function(){return"[object "+LP(this)+"]"}});var Ii=m((jO,Ch)=>{"use strict";var MP=bs(),CP=Xt().f,DP=$r(),OP=je(),BP=Lh(),VP=le(),Mh=VP("toStringTag");Ch.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(OP(i,Mh)||CP(i,Mh,{configurable:!0,value:e}),r&&!MP&&DP(i,"toString",BP))}});var Oh=m((GO,Dh)=>{"use strict";var _P=qo().IteratorPrototype,NP=Vo(),FP=di(),qP=Ii(),UP=Zt(),HP=function(){return this};Dh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=NP(_P,{next:FP(+!r,t)}),qP(a,i,!1,!0),UP[i]=HP,a}});var Vh=m((QO,Bh)=>{"use strict";var jP=te(),GP=Ke();Bh.exports=function(a,e,t){try{return jP(GP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Nh=m((WO,_h)=>{"use strict";var QP=Ae();_h.exports=function(a){return QP(a)||a===null}});var qh=m((YO,Fh)=>{"use strict";var WP=Nh(),YP=String,zP=TypeError;Fh.exports=function(a){if(WP(a))return a;throw new zP("Can't set "+YP(a)+" as a prototype")}});var Uo=m((zO,Uh)=>{"use strict";var KP=Vh(),JP=Ae(),XP=At(),ZP=qh();Uh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=KP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return XP(i),ZP(s),JP(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Zh=m((KO,Xh)=>{"use strict";var eA=X(),tA=Pe(),vs=He(),Kh=Mo(),rA=Y(),iA=Oh(),Hh=cs(),jh=Uo(),aA=Ii(),sA=$r(),Ho=Dr(),nA=le(),Gh=Zt(),Jh=qo(),oA=Kh.PROPER,uA=Kh.CONFIGURABLE,Qh=Jh.IteratorPrototype,Ss=Jh.BUGGY_SAFARI_ITERATORS,Ei=nA("iterator"),Wh="keys",xi="values",Yh="entries",zh=function(){return this};Xh.exports=function(a,e,t,r,i,s,n){iA(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ss&&v&&v in d)return d[v];switch(v){case Wh:return function(){return new t(this,v)};case xi:return function(){return new t(this,v)};case Yh:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[Ei]||d["@@iterator"]||i&&d[i],p=!Ss&&c||o(i),h=e==="Array"&&d.entries||c,f,b,g;if(h&&(f=Hh(h.call(new a)),f!==Object.prototype&&f.next&&(!vs&&Hh(f)!==Qh&&(jh?jh(f,Qh):rA(f[Ei])||Ho(f,Ei,zh)),aA(f,u,!0,!0),vs&&(Gh[u]=zh))),oA&&i===xi&&c&&c.name!==xi&&(!vs&&uA?sA(d,"name",xi):(l=!0,p=function(){return tA(c,this)})),i)if(b={values:o(xi),keys:s?p:o(Wh),entries:o(Yh)},n)for(g in b)(Ss||l||!(g in d))&&Ho(d,g,b[g]);else eA({target:e,proto:!0,forced:Ss||l},b);return(!vs||n)&&d[Ei]!==p&&Ho(d,Ei,p,{name:i}),Gh[e]=p,b}});var tf=m((JO,ef)=>{"use strict";ef.exports=function(a,e){return{value:a,done:e}}});var Go=m((XO,of)=>{"use strict";var lA=Kt(),jo=Si(),rf=Zt(),sf=Ro(),cA=Xt().f,dA=Zh(),ys=tf(),pA=He(),hA=xe(),nf="Array Iterator",fA=sf.set,mA=sf.getterFor(nf);of.exports=dA(Array,"Array",function(a,e){fA(this,{type:nf,target:lA(a),index:0,kind:e})},function(){var a=mA(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ys(void 0,!0);switch(a.kind){case"keys":return ys(t,!1);case"values":return ys(e[t],!1)}return ys([t,e[t]],!1)},"values");var af=rf.Arguments=rf.Array;jo("keys");jo("values");jo("entries");if(!pA&&hA&&af.name!=="values")try{cA(af,"name",{value:"values"})}catch(a){}});var lf=m((ZO,uf)=>{"use strict";var bA=le(),gA=Zt(),vA=bA("iterator"),SA=Array.prototype;uf.exports=function(a){return a!==void 0&&(gA.Array===a||SA[vA]===a)}});var Qo=m((eB,df)=>{"use strict";var yA=Ti(),cf=fi(),TA=Pr(),IA=Zt(),EA=le(),xA=EA("iterator");df.exports=function(a){if(!TA(a))return cf(a,xA)||cf(a,"@@iterator")||IA[yA(a)]}});var hf=m((tB,pf)=>{"use strict";var PA=Pe(),AA=Ke(),wA=Je(),kA=hi(),RA=Qo(),$A=TypeError;pf.exports=function(a,e){var t=arguments.length<2?RA(a):e;if(AA(t))return wA(PA(t,a));throw new $A(kA(a)+" is not iterable")}});var bf=m((rB,mf)=>{"use strict";var LA=Pe(),ff=Je(),MA=fi();mf.exports=function(a,e,t){var r,i;ff(a);try{if(r=MA(a,"return"),!r){if(e==="throw")throw t;return t}r=LA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return ff(r),t}});var Is=m((iB,yf)=>{"use strict";var CA=Rr(),DA=Pe(),OA=Je(),BA=hi(),VA=lf(),_A=Cr(),gf=pi(),NA=hf(),FA=Qo(),vf=bf(),qA=TypeError,Ts=function(a,e){this.stopped=a,this.result=e},Sf=Ts.prototype;yf.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=CA(e,r),l,d,c,p,h,f,b,g=function(S){return l&&vf(l,"normal",S),new Ts(!0,S)},v=function(S){return i?(OA(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(d=FA(a),!d)throw new qA(BA(a)+" is not iterable");if(VA(d)){for(c=0,p=_A(a);p>c;c++)if(h=v(a[c]),h&&gf(Sf,h))return h;return new Ts(!1)}l=NA(a,d)}for(f=s?a.next:l.next;!(b=DA(f,l)).done;){try{h=v(b.value)}catch(S){vf(l,"throw",S)}if(typeof h=="object"&&h&&gf(Sf,h))return h}return new Ts(!1)}});var If=m((aB,Tf)=>{"use strict";var UA=xe(),HA=Xt(),jA=di();Tf.exports=function(a,e,t){UA?HA.f(a,e,jA(0,t)):a[e]=t}});var Ef=m(()=>{"use strict";var GA=X(),QA=Is(),WA=If();GA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return QA(e,function(r,i){WA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Pf=m((oB,xf)=>{"use strict";Go();Ef();var YA=Ar();xf.exports=YA.Object.fromEntries});var wf=m((uB,Af)=>{"use strict";Af.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 Rf=m(()=>{"use strict";Go();var zA=wf(),KA=z(),JA=Ii(),kf=Zt();for(Es in zA)JA(KA[Es],Es),kf[Es]=kf.Array;var Es});var Lf=m((dB,$f)=>{"use strict";var XA=Pf();Rf();$f.exports=XA});var Wo=m((pB,Mf)=>{"use strict";var ZA=Lf();Mf.exports=ZA});var Cf=m(()=>{"use strict"});var Yo=m((mB,Df)=>{"use strict";var Pi=z(),ew=Jt(),tw=zt(),xs=function(a){return ew.slice(0,a.length)===a};Df.exports=function(){return xs("Bun/")?"BUN":xs("Cloudflare-Workers")?"CLOUDFLARE":xs("Deno/")?"DENO":xs("Node.js/")?"NODE":Pi.Bun&&typeof Bun.version=="string"?"BUN":Pi.Deno&&typeof Deno.version=="object"?"DENO":tw(Pi.process)==="process"?"NODE":Pi.window&&Pi.document?"BROWSER":"REST"}()});var Ps=m((bB,Of)=>{"use strict";var rw=Yo();Of.exports=rw==="NODE"});var Vf=m((gB,Bf)=>{"use strict";var iw=Xt();Bf.exports=function(a,e,t){return iw.f(a,e,t)}});var Ff=m((vB,Nf)=>{"use strict";var aw=st(),sw=Vf(),nw=le(),ow=xe(),_f=nw("species");Nf.exports=function(a){var e=aw(a);ow&&e&&!e[_f]&&sw(e,_f,{configurable:!0,get:function(){return this}})}});var Uf=m((SB,qf)=>{"use strict";var uw=pi(),lw=TypeError;qf.exports=function(a,e){if(uw(e,a))return a;throw new lw("Incorrect invocation")}});var Ko=m((yB,Hf)=>{"use strict";var cw=te(),dw=Y(),zo=mi(),pw=cw(Function.toString);dw(zo.inspectSource)||(zo.inspectSource=function(a){return pw(a)});Hf.exports=zo.inspectSource});var Xo=m((TB,Yf)=>{"use strict";var hw=te(),fw=ue(),jf=Y(),mw=Ti(),bw=st(),gw=Ko(),Gf=function(){},Qf=bw("Reflect","construct"),Jo=/^\s*(?:class|function)\b/,vw=hw(Jo.exec),Sw=!Jo.test(Gf),Ai=function(e){if(!jf(e))return!1;try{return Qf(Gf,[],e),!0}catch(t){return!1}},Wf=function(e){if(!jf(e))return!1;switch(mw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Sw||!!vw(Jo,gw(e))}catch(t){return!0}};Wf.sham=!0;Yf.exports=!Qf||fw(function(){var a;return Ai(Ai.call)||!Ai(Object)||!Ai(function(){a=!0})||a})?Wf:Ai});var Kf=m((IB,zf)=>{"use strict";var yw=Xo(),Tw=hi(),Iw=TypeError;zf.exports=function(a){if(yw(a))return a;throw new Iw(Tw(a)+" is not a constructor")}});var Zo=m((EB,Xf)=>{"use strict";var Jf=Je(),Ew=Kf(),xw=Pr(),Pw=le(),Aw=Pw("species");Xf.exports=function(a,e){var t=Jf(a).constructor,r;return t===void 0||xw(r=Jf(t)[Aw])?e:Ew(r)}});var em=m((xB,Zf)=>{"use strict";var ww=te();Zf.exports=ww([].slice)});var rm=m((PB,tm)=>{"use strict";var kw=TypeError;tm.exports=function(a,e){if(a<e)throw new kw("Not enough arguments");return a}});var eu=m((AB,im)=>{"use strict";var Rw=Jt();im.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Rw)});var lu=m((wB,pm)=>{"use strict";var we=z(),$w=Un(),Lw=Rr(),am=Y(),Mw=je(),dm=ue(),sm=Co(),Cw=em(),nm=ss(),Dw=rm(),Ow=eu(),Bw=Ps(),nu=we.setImmediate,ou=we.clearImmediate,Vw=we.process,tu=we.Dispatch,_w=we.Function,om=we.MessageChannel,Nw=we.String,ru=0,wi={},um="onreadystatechange",ki,tr,iu,au;dm(function(){ki=we.location});var uu=function(a){if(Mw(wi,a)){var e=wi[a];delete wi[a],e()}},su=function(a){return function(){uu(a)}},lm=function(a){uu(a.data)},cm=function(a){we.postMessage(Nw(a),ki.protocol+"//"+ki.host)};(!nu||!ou)&&(nu=function(e){Dw(arguments.length,1);var t=am(e)?e:_w(e),r=Cw(arguments,1);return wi[++ru]=function(){$w(t,void 0,r)},tr(ru),ru},ou=function(e){delete wi[e]},Bw?tr=function(a){Vw.nextTick(su(a))}:tu&&tu.now?tr=function(a){tu.now(su(a))}:om&&!Ow?(iu=new om,au=iu.port2,iu.port1.onmessage=lm,tr=Lw(au.postMessage,au)):we.addEventListener&&am(we.postMessage)&&!we.importScripts&&ki&&ki.protocol!=="file:"&&!dm(cm)?(tr=cm,we.addEventListener("message",lm,!1)):um in nm("script")?tr=function(a){sm.appendChild(nm("script"))[um]=function(){sm.removeChild(this),uu(a)}}:tr=function(a){setTimeout(su(a),0)});pm.exports={set:nu,clear:ou}});var mm=m((kB,fm)=>{"use strict";var hm=z(),Fw=xe(),qw=Object.getOwnPropertyDescriptor;fm.exports=function(a){if(!Fw)return hm[a];var e=qw(hm,a);return e&&e.value}});var cu=m((RB,gm)=>{"use strict";var bm=function(){this.head=null,this.tail=null};bm.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}}};gm.exports=bm});var Sm=m(($B,vm)=>{"use strict";var Uw=Jt();vm.exports=/ipad|iphone|ipod/i.test(Uw)&&typeof Pebble!="undefined"});var Tm=m((LB,ym)=>{"use strict";var Hw=Jt();ym.exports=/web0s(?!.*chrome)/i.test(Hw)});var km=m((MB,wm)=>{"use strict";var Br=z(),jw=mm(),Im=Rr(),du=lu().set,Gw=cu(),Qw=eu(),Ww=Sm(),Yw=Tm(),pu=Ps(),Em=Br.MutationObserver||Br.WebKitMutationObserver,xm=Br.document,Pm=Br.process,As=Br.Promise,mu=jw("queueMicrotask"),Or,hu,fu,ws,Am;mu||(Ri=new Gw,$i=function(){var a,e;for(pu&&(a=Pm.domain)&&a.exit();e=Ri.get();)try{e()}catch(t){throw Ri.head&&Or(),t}a&&a.enter()},!Qw&&!pu&&!Yw&&Em&&xm?(hu=!0,fu=xm.createTextNode(""),new Em($i).observe(fu,{characterData:!0}),Or=function(){fu.data=hu=!hu}):!Ww&&As&&As.resolve?(ws=As.resolve(void 0),ws.constructor=As,Am=Im(ws.then,ws),Or=function(){Am($i)}):pu?Or=function(){Pm.nextTick($i)}:(du=Im(du,Br),Or=function(){du($i)}),mu=function(a){Ri.head||Or(),Ri.add(a)});var Ri,$i;wm.exports=mu});var $m=m((CB,Rm)=>{"use strict";Rm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ks=m((DB,Lm)=>{"use strict";Lm.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var rr=m((OB,Mm)=>{"use strict";var zw=z();Mm.exports=zw.Promise});var Vr=m((BB,Bm)=>{"use strict";var Kw=z(),Li=rr(),Jw=Y(),Xw=co(),Zw=Ko(),ek=le(),Cm=Yo(),tk=He(),bu=Jn(),Dm=Li&&Li.prototype,rk=ek("species"),gu=!1,Om=Jw(Kw.PromiseRejectionEvent),ik=Xw("Promise",function(){var a=Zw(Li),e=a!==String(Li);if(!e&&bu===66||tk&&!(Dm.catch&&Dm.finally))return!0;if(!bu||bu<51||!/native code/.test(a)){var t=new Li(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[rk]=r,gu=t.then(function(){})instanceof r,!gu)return!0}return!e&&(Cm==="BROWSER"||Cm==="DENO")&&!Om});Bm.exports={CONSTRUCTOR:ik,REJECTION_EVENT:Om,SUBCLASSING:gu}});var _r=m((VB,_m)=>{"use strict";var Vm=Ke(),ak=TypeError,sk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new ak("Bad Promise constructor");e=r,t=i}),this.resolve=Vm(e),this.reject=Vm(t)};_m.exports.f=function(a){return new sk(a)}});var ib=m(()=>{"use strict";var nk=X(),ok=He(),Ms=Ps(),Rt=z(),Ur=Pe(),Nm=Dr(),Fm=Uo(),uk=Ii(),lk=Ff(),ck=Ke(),Ls=Y(),dk=Ae(),pk=Uf(),hk=Zo(),Gm=lu().set,Iu=km(),fk=$m(),mk=ks(),bk=cu(),Qm=Ro(),Cs=rr(),Eu=Vr(),Wm=_r(),Ds="Promise",Ym=Eu.CONSTRUCTOR,gk=Eu.REJECTION_EVENT,vk=Eu.SUBCLASSING,vu=Qm.getterFor(Ds),Sk=Qm.set,Nr=Cs&&Cs.prototype,ir=Cs,Rs=Nr,zm=Rt.TypeError,Su=Rt.document,xu=Rt.process,yu=Wm.f,yk=yu,Tk=!!(Su&&Su.createEvent&&Rt.dispatchEvent),Km="unhandledrejection",Ik="rejectionhandled",qm=0,Jm=1,Ek=2,Pu=1,Xm=2,$s,Um,xk,Hm,Zm=function(a){var e;return dk(a)&&Ls(e=a.then)?e:!1},eb=function(a,e){var t=e.value,r=e.state===Jm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{i?(r||(e.rejection===Xm&&Ak(e),e.rejection=Pu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),d=!0)),u===a.promise?n(new zm("Promise-chain cycle")):(l=Zm(u))?Ur(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},tb=function(a,e){a.notified||(a.notified=!0,Iu(function(){for(var t=a.reactions,r;r=t.get();)eb(r,a);a.notified=!1,e&&!a.rejection&&Pk(a)}))},rb=function(a,e,t){var r,i;Tk?(r=Su.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Rt.dispatchEvent(r)):r={promise:e,reason:t},!gk&&(i=Rt["on"+a])?i(r):a===Km&&fk("Unhandled promise rejection",t)},Pk=function(a){Ur(Gm,Rt,function(){var e=a.facade,t=a.value,r=jm(a),i;if(r&&(i=mk(function(){Ms?xu.emit("unhandledRejection",t,e):rb(Km,e,t)}),a.rejection=Ms||jm(a)?Xm:Pu,i.error))throw i.value})},jm=function(a){return a.rejection!==Pu&&!a.parent},Ak=function(a){Ur(Gm,Rt,function(){var e=a.facade;Ms?xu.emit("rejectionHandled",e):rb(Ik,e,a.value)})},Fr=function(a,e,t){return function(r){a(e,r,t)}},qr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Ek,tb(a,!0))},Tu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new zm("Promise can't be resolved itself");var r=Zm(e);r?Iu(function(){var i={done:!1};try{Ur(r,e,Fr(Tu,i,a),Fr(qr,i,a))}catch(s){qr(i,s,a)}}):(a.value=e,a.state=Jm,tb(a,!1))}catch(i){qr({done:!1},i,a)}}};if(Ym&&(ir=function(e){pk(this,Rs),ck(e),Ur($s,this);var t=vu(this);try{e(Fr(Tu,t),Fr(qr,t))}catch(r){qr(t,r)}},Rs=ir.prototype,$s=function(e){Sk(this,{type:Ds,done:!1,notified:!1,parent:!1,reactions:new bk,rejection:!1,state:qm,value:void 0})},$s.prototype=Nm(Rs,"then",function(e,t){var r=vu(this),i=yu(hk(this,ir));return r.parent=!0,i.ok=Ls(e)?e:!0,i.fail=Ls(t)&&t,i.domain=Ms?xu.domain:void 0,r.state===qm?r.reactions.add(i):Iu(function(){eb(i,r)}),i.promise}),Um=function(){var a=new $s,e=vu(a);this.promise=a,this.resolve=Fr(Tu,e),this.reject=Fr(qr,e)},Wm.f=yu=function(a){return a===ir||a===xk?new Um(a):yk(a)},!ok&&Ls(Cs)&&Nr!==Object.prototype)){Hm=Nr.then,vk||Nm(Nr,"then",function(e,t){var r=this;return new ir(function(i,s){Ur(Hm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Nr.constructor}catch(a){}Fm&&Fm(Nr,Rs)}nk({global:!0,constructor:!0,wrap:!0,forced:Ym},{Promise:ir});uk(ir,Ds,!1,!0);lk(Ds)});var ub=m((FB,ob)=>{"use strict";var wk=le(),sb=wk("iterator"),nb=!1;try{ab=0,Au={next:function(){return{done:!!ab++}},return:function(){nb=!0}},Au[sb]=function(){return this},Array.from(Au,function(){throw 2})}catch(a){}var ab,Au;ob.exports=function(a,e){try{if(!e&&!nb)return!1}catch(i){return!1}var t=!1;try{var r={};r[sb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var wu=m((qB,lb)=>{"use strict";var kk=rr(),Rk=ub(),$k=Vr().CONSTRUCTOR;lb.exports=$k||!Rk(function(a){kk.all(a).then(void 0,function(){})})});var cb=m(()=>{"use strict";var Lk=X(),Mk=Pe(),Ck=Ke(),Dk=_r(),Ok=ks(),Bk=Is(),Vk=wu();Lk({target:"Promise",stat:!0,forced:Vk},{all:function(e){var t=this,r=Dk.f(t),i=r.resolve,s=r.reject,n=Ok(function(){var o=Ck(t.resolve),u=[],l=0,d=1;Bk(e,function(c){var p=l++,h=!1;d++,Mk(o,t,c).then(function(f){h||(h=!0,u[p]=f,--d||i(u))},s)}),--d||i(u)});return n.error&&s(n.value),r.promise}})});var pb=m(()=>{"use strict";var _k=X(),Nk=He(),Fk=Vr().CONSTRUCTOR,Ru=rr(),qk=st(),Uk=Y(),Hk=Dr(),db=Ru&&Ru.prototype;_k({target:"Promise",proto:!0,forced:Fk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Nk&&Uk(Ru)&&(ku=qk("Promise").prototype.catch,db.catch!==ku&&Hk(db,"catch",ku,{unsafe:!0}));var ku});var hb=m(()=>{"use strict";var jk=X(),Gk=Pe(),Qk=Ke(),Wk=_r(),Yk=ks(),zk=Is(),Kk=wu();jk({target:"Promise",stat:!0,forced:Kk},{race:function(e){var t=this,r=Wk.f(t),i=r.reject,s=Yk(function(){var n=Qk(t.resolve);zk(e,function(o){Gk(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var fb=m(()=>{"use strict";var Jk=X(),Xk=_r(),Zk=Vr().CONSTRUCTOR;Jk({target:"Promise",stat:!0,forced:Zk},{reject:function(e){var t=Xk.f(this),r=t.reject;return r(e),t.promise}})});var $u=m((KB,mb)=>{"use strict";var eR=Je(),tR=Ae(),rR=_r();mb.exports=function(a,e){if(eR(a),tR(e)&&e.constructor===a)return e;var t=rR.f(a),r=t.resolve;return r(e),t.promise}});var vb=m(()=>{"use strict";var iR=X(),aR=st(),bb=He(),sR=rr(),gb=Vr().CONSTRUCTOR,nR=$u(),oR=aR("Promise"),uR=bb&&!gb;iR({target:"Promise",stat:!0,forced:bb||gb},{resolve:function(e){return nR(uR&&this===oR?sR:this,e)}})});var Sb=m(()=>{"use strict";ib();cb();pb();hb();fb();vb()});var Eb=m(()=>{"use strict";var lR=X(),cR=He(),Os=rr(),dR=ue(),Tb=st(),Ib=Y(),pR=Zo(),yb=$u(),hR=Dr(),Mu=Os&&Os.prototype,fR=!!Os&&dR(function(){Mu.finally.call({then:function(){}},function(){})});lR({target:"Promise",proto:!0,real:!0,forced:fR},{finally:function(a){var e=pR(this,Tb("Promise")),t=Ib(a);return this.then(t?function(r){return yb(e,a()).then(function(){return r})}:a,t?function(r){return yb(e,a()).then(function(){throw r})}:a)}});!cR&&Ib(Os)&&(Lu=Tb("Promise").prototype.finally,Mu.finally!==Lu&&hR(Mu,"finally",Lu,{unsafe:!0}));var Lu});var Pb=m((iV,xb)=>{"use strict";Cf();Sb();Eb();var mR=wt();xb.exports=mR("Promise","finally")});var wb=m((aV,Ab)=>{"use strict";var bR=Pb();Ab.exports=bR});var Bs=m((sV,kb)=>{"use strict";var gR=wb();kb.exports=gR});var qb=m(()=>{"use strict";var LR=X(),MR=Po().values;LR({target:"Object",stat:!0},{values:function(e){return MR(e)}})});var Hb=m((HV,Ub)=>{"use strict";qb();var CR=Ar();Ub.exports=CR.Object.values});var Gb=m((jV,jb)=>{"use strict";var DR=Hb();jb.exports=DR});var ut=m((GV,Qb)=>{"use strict";var OR=Gb();Qb.exports=OR});var sg=m(()=>{"use strict";var JR=X(),XR=wr(),ZR=Cr(),e$=vi(),t$=Si();JR({target:"Array",proto:!0},{at:function(e){var t=XR(this),r=ZR(t),i=e$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});t$("at")});var og=m((S_,ng)=>{"use strict";sg();var r$=wt();ng.exports=r$("Array","at")});var lg=m((y_,ug)=>{"use strict";var i$=og();ug.exports=i$});var Gr=m((T_,cg)=>{"use strict";var a$=lg();cg.exports=a$});var tl=m((WN,Fg)=>{"use strict";var N$=zt();Fg.exports=Array.isArray||function(e){return N$(e)==="Array"}});var Ug=m((YN,qg)=>{"use strict";var F$=TypeError,q$=9007199254740991;qg.exports=function(a){if(a>q$)throw F$("Maximum allowed index exceeded");return a}});var Gg=m((zN,jg)=>{"use strict";var U$=tl(),H$=Cr(),j$=Ug(),G$=Rr(),Hg=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,d=n?G$(n,o):!1,c,p;l<r;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&U$(c)?(p=H$(c),u=Hg(a,e,c,p,u,s-1)-1):(j$(u+1),a[u]=c),u++),l++;return u};jg.exports=Hg});var zg=m((KN,Yg)=>{"use strict";var Qg=tl(),Q$=Xo(),W$=Ae(),Y$=le(),z$=Y$("species"),Wg=Array;Yg.exports=function(a){var e;return Qg(a)&&(e=a.constructor,Q$(e)&&(e===Wg||Qg(e.prototype))?e=void 0:W$(e)&&(e=e[z$],e===null&&(e=void 0))),e===void 0?Wg:e}});var Jg=m((JN,Kg)=>{"use strict";var K$=zg();Kg.exports=function(a,e){return new(K$(a))(e===0?0:e)}});var Xg=m(()=>{"use strict";var J$=X(),X$=Gg(),Z$=Ke(),eL=wr(),tL=Cr(),rL=Jg();J$({target:"Array",proto:!0},{flatMap:function(e){var t=eL(this),r=tL(t),i;return Z$(e),i=rL(t,0),i.length=X$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Zg=m(()=>{"use strict";var iL=Si();iL("flatMap")});var tv=m((rF,ev)=>{"use strict";Xg();Zg();var aL=wt();ev.exports=aL("Array","flatMap")});var iv=m((iF,rv)=>{"use strict";var sL=tv();rv.exports=sL});var rl=m((aF,av)=>{"use strict";var nL=iv();av.exports=nL});var Qi=m((fF,xv)=>{"use strict";var fL=Ti(),mL=String;xv.exports=function(a){if(fL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return mL(a)}});var sl=m((mF,Pv)=>{"use strict";Pv.exports=`
7
+ \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var kv=m((bF,wv)=>{"use strict";var bL=te(),gL=At(),vL=Qi(),ol=sl(),Av=bL("".replace),SL=RegExp("^["+ol+"]+"),yL=RegExp("(^|[^"+ol+"])["+ol+"]+$"),nl=function(a){return function(e){var t=vL(gL(e));return a&1&&(t=Av(t,SL,"")),a&2&&(t=Av(t,yL,"$1")),t}};wv.exports={start:nl(1),end:nl(2),trim:nl(3)}});var Mv=m((gF,Lv)=>{"use strict";var TL=Mo().PROPER,IL=ue(),Rv=sl(),$v="\u200B\x85\u180E";Lv.exports=function(a){return IL(function(){return!!Rv[a]()||$v[a]()!==$v||TL&&Rv[a].name!==a})}});var ul=m((vF,Cv)=>{"use strict";var EL=kv().start,xL=Mv();Cv.exports=xL("trimStart")?function(){return EL(this)}:"".trimStart});var Ov=m(()=>{"use strict";var PL=X(),Dv=ul();PL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Dv},{trimLeft:Dv})});var Vv=m(()=>{"use strict";Ov();var AL=X(),Bv=ul();AL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Bv},{trimStart:Bv})});var Nv=m((EF,_v)=>{"use strict";Vv();var wL=wt();_v.exports=wL("String","trimLeft")});var qv=m((xF,Fv)=>{"use strict";var kL=Nv();Fv.exports=kL});var Hv=m((PF,Uv)=>{"use strict";var RL=qv();Uv.exports=RL});var sS=m(()=>{"use strict"});var nS=m(()=>{"use strict"});var uS=m((zU,oS)=>{"use strict";var XL=Ae(),ZL=zt(),eM=le(),tM=eM("match");oS.exports=function(a){var e;return XL(a)&&((e=a[tM])!==void 0?!!e:ZL(a)==="RegExp")}});var cS=m((KU,lS)=>{"use strict";var rM=Je();lS.exports=function(){var a=rM(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 hS=m((JU,pS)=>{"use strict";var iM=Pe(),aM=je(),sM=pi(),nM=cS(),dS=RegExp.prototype;pS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in dS)&&!aM(a,"flags")&&sM(dS,a)?iM(nM,a):e}});var mS=m((XU,fS)=>{"use strict";var gl=te(),oM=wr(),uM=Math.floor,ml=gl("".charAt),lM=gl("".replace),bl=gl("".slice),cM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,dM=/\$([$&'`]|\d{1,2})/g;fS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=dM;return i!==void 0&&(i=oM(i),u=cM),lM(s,u,function(l,d){var c;switch(ml(d,0)){case"$":return"$";case"&":return a;case"`":return bl(e,0,t);case"'":return bl(e,n);case"<":c=i[bl(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=uM(p/10);return h===0?l:h<=o?r[h-1]===void 0?ml(d,1):r[h-1]+ml(d,1):l}c=r[p-1]}return c===void 0?"":c})}});var vS=m(()=>{"use strict";var pM=X(),hM=Pe(),Sl=te(),bS=At(),fM=Y(),mM=Pr(),bM=uS(),Jr=Qi(),gM=fi(),vM=hS(),SM=mS(),yM=le(),TM=He(),IM=yM("replace"),EM=TypeError,vl=Sl("".indexOf),xM=Sl("".replace),gS=Sl("".slice),PM=Math.max;pM({target:"String",proto:!0},{replaceAll:function(e,t){var r=bS(this),i,s,n,o,u,l,d,c,p,h,f=0,b="";if(!mM(e)){if(i=bM(e),i&&(s=Jr(bS(vM(e))),!~vl(s,"g")))throw new EM("`.replaceAll` does not allow non-global regexes");if(n=gM(e,IM),n)return hM(n,e,r,t);if(TM&&i)return xM(Jr(r),e,t)}for(o=Jr(r),u=Jr(e),l=fM(t),l||(t=Jr(t)),d=u.length,c=PM(1,d),p=vl(o,u);p!==-1;)h=l?Jr(t(u,p,o)):SM(u,o,p,[],void 0,t),b+=gS(o,f,p)+h,f=p+d,p=p+c>o.length?-1:vl(o,u,p+c);return f<o.length&&(b+=gS(o,f)),b}})});var yS=m((t1,SS)=>{"use strict";sS();nS();vS();var AM=wt();SS.exports=AM("String","replaceAll")});var IS=m((r1,TS)=>{"use strict";var wM=yS();TS.exports=wM});var xS=m((i1,ES)=>{"use strict";var kM=IS();ES.exports=kM});var AS=m((a1,PS)=>{"use strict";var RM=vi(),$M=Qi(),LM=At(),MM=RangeError;PS.exports=function(e){var t=$M(LM(this)),r="",i=RM(e);if(i<0||i===1/0)throw new MM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var LS=m((s1,$S)=>{"use strict";var RS=te(),CM=go(),wS=Qi(),DM=AS(),OM=At(),BM=RS(DM),VM=RS("".slice),_M=Math.ceil,kS=function(a){return function(e,t,r){var i=wS(OM(e)),s=CM(t),n=i.length,o=r===void 0?" ":wS(r),u,l;return s<=n||o===""?i:(u=s-n,l=BM(o,_M(u/o.length)),l.length>u&&(l=VM(l,0,u)),a?i+l:l+i)}};$S.exports={start:kS(!1),end:kS(!0)}});var CS=m((n1,MS)=>{"use strict";var NM=Jt();MS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(NM)});var DS=m(()=>{"use strict";var FM=X(),qM=LS().start,UM=CS();FM({target:"String",proto:!0,forced:UM},{padStart:function(e){return qM(this,e,arguments.length>1?arguments[1]:void 0)}})});var BS=m((l1,OS)=>{"use strict";DS();var HM=wt();OS.exports=HM("String","padStart")});var _S=m((c1,VS)=>{"use strict";var jM=BS();VS.exports=jM});var FS=m((d1,NS)=>{"use strict";var GM=_S();NS.exports=GM});var Bc="2.0.118-beta.0";var me=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(me||{}),Pt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Pt||{});var rs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(rs||{}),Nn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Nn||{});var Fn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Fn||{});var ST=L(Xe(),1);import{assertNever as Dp,assertNonNullable as ax,isNonNullable as os,ValueSubject as So,Subject as sx,Subscription as nx,merge as ox,observableFrom as ux,fromEvent as $p,map as Lp,tap as Mp,filterChanged as lx,isNullable as yo,ErrorCategory as Cp}from"@vkontakte/videoplayer-shared";var Rp=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var us=class{constructor(e){this.connection$=new So(void 0);this.castState$=new So("NOT_AVAILABLE");this.errorEvent$=new sx;this.realCastState$=new So("NOT_AVAILABLE");this.subscription=new nx;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=os((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Rp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Cp.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){os(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();yo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();yo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add($p(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 Dp(i.sessionState)}})).add(ox($p(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Mp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Lp(i=>i.castState)),ux([r.getCastState()])).pipe(lx(),Lp(cx),Mp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=os(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();ax(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(yo(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?os(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Cp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},cx=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 Dp(a)}};var zl=L(Xe(),1),Zy=L(kt(),1),eT=L(Wo(),1);var _b=L(Bs(),1);import{assertNever as Rb}from"@vkontakte/videoplayer-shared";var ce=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Rb(t)}return a},Vs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Rb(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as vR,Subject as _s,merge as $b}from"@vkontakte/videoplayer-shared";var M=class{constructor(e){this.transitionStarted$=new _s;this.transitionEnded$=new _s;this.transitionUpdated$=new _s;this.forceChanged$=new _s;this.stateChangeStarted$=$b(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=$b(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||vR(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 SR}from"@vkontakte/videoplayer-shared";var Lb=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 SR(a)}};import{assertNever as Hr,assertNonNullable as ar,debounce as Mb,ErrorCategory as Cb,fromEvent as sr,isNonNullable as Db,map as Ob,merge as Bb,observableFrom as yR,Subject as TR,Subscription as Cu,timeout as IR,getHighestQuality as ER}from"@vkontakte/videoplayer-shared";var xR=5,PR=5,AR=500,Vb=7e3,Mi=class{constructor(e){this.subscription=new Cu;this.loadMediaTimeoutSubscription=new Cu;this.videoState=new M("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:Hr(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:Hr(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:Hr(e)}break}default:Hr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Lb(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Cu;this.subscription.add(e),this.subscription.add(Bb(this.videoState.stateChangeStarted$.pipe(Ob(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Ob(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 TR;e.add(i.pipe(Mb(AR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(sr(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)>xR)&&i.next(o),s=o})),e.add(sr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(sr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(sr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(sr(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<PR&&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:Hr(n)}}),t(sr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(sr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Bb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,yR(["init"])).pipe(Mb(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 d=t[e];ar(d);let c=ER(Object.keys(d));ar(c);let p=d[c];ar(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];ar(d),r=d.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 d=t[e];ar(d),r=d.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];ar(d),r=d.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];ar(d),r=ce(d.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Cb.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Hr(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 Db(o)&&(n.metadata.title=o),Db(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(IR(Vb).subscribe(()=>s(`timeout(${Vb})`)))});(0,_b.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:Cb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Zu=L(Xe(),1);import{clearVideoElement as Fb}from"@vkontakte/videoplayer-shared";import{clearVideoElement as wR}from"@vkontakte/videoplayer-shared";var Nb=a=>{try{a.pause(),a.playbackRate=0,wR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as kR,Subscription as RR}from"@vkontakte/videoplayer-shared";var Du=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Ou=window.WeakMap?new WeakMap:new Du,Bu=window.WeakMap?new WeakMap:new Map,$R=(a,e=20)=>{let t=0;return kR(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?Fb(t):(t=document.createElement("video"),a.appendChild(t)),Ou.set(t,r);let i=new RR;return i.add($R(t,e)),Bu.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=Bu.get(a);e==null||e.unsubscribe(),Bu.delete(a);let t=Ou.get(a);Ou.delete(a),t?Fb(a):Nb(a)};var _u=L(ut(),1);import{assertNonNullable as Ci,isNonNullable as et,isNullable as _R,fromEvent as jr,merge as Wb,observableFrom as Yb,filterChanged as zb,map as Di,Subject as Kb,Subscription as NR,ValueSubject as FR,ErrorCategory as qR}from"@vkontakte/videoplayer-shared";import{isNonNullable as Vu,isNullable as BR,Subscription as VR}from"@vkontakte/videoplayer-shared";var Ns=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=BR(i),l=new VR;return i&&l.add(i.subscribe(d=>{let c=a.getState();r(d,c)&&a.setState(d)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},Ze=(a,e,t)=>Ns(e,()=>a.loop,r=>{Vu(r)&&(a.loop=r)},{onError:t}),ve=(a,e,t,r)=>Ns(e,()=>({muted:a.muted,volume:a.volume}),i=>{Vu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),De=(a,e,t,r)=>Ns(e,()=>a.playbackRate,i=>{Vu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),$t=Ns;var UR=a=>["__",a.language,a.label].join("|"),HR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Nu=class a{constructor(){this.available$=new Kb;this.current$=new FR(void 0);this.error$=new Kb;this.subscription=new NR;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:qR.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add($t(t.internalTextTracks,()=>(0,_u.default)(Object,this.internalTracks),s=>{et(s)&&this.setInternal(s)},{equal:(s,n)=>et(s)&&et(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Di(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add($t(t.externalTextTracks,()=>(0,_u.default)(Object,this.externalTracks),s=>{et(s)&&this.setExternal(s)},{equal:(s,n)=>et(s)&&et(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Di(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add($t(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add($t(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ci(this.video);let{textTracks:e}=this.video;this.subscription.add(jr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Wb(jr(e,"addtrack"),jr(e,"removetrack"),Yb(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),zb((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Wb(jr(e,"change"),Yb(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Di(r=>r&&this.htmlTextTrackToITextTrack(r).id),zb()).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(jr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,d,c,p,h;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(jr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;et(t.align)&&(i.align=t.align),et(t.position)&&(i.position=t.position),et(t.size)&&(i.size=t.size),et(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Ci(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:r}=e,i=e.id?e.id:UR(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(d=this.externalTracks.get(i))==null?void 0:d.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){Ci(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(_R(e)||!HR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Ci(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Ci(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Oe=Nu;var lt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Jb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Fu=a=>{let e=Jb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Xb=a=>{let e=Jb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Be,map as Lt,merge as eg,filterChanged as GR,isNonNullable as tg,Subject as QR,filter as rg,mapTo as ig,combine as WR,once as YR,ErrorCategory as zR,ValueSubject as ag,clientChecker as KR}from"@vkontakte/videoplayer-shared";var jR=3,Zb=(a,e,t=jR)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Se=a=>{let e=y=>Be(a,y).pipe(ig(void 0)),r=eg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Be(a,y))).pipe(Lt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),GR()),i=eg(Be(a,"progress"),Be(a,"timeupdate")).pipe(Lt(()=>Zb(a.buffered,a.currentTime))),s=KR.isSafari?WR({play:e("play").pipe(YR()),playing:e("playing")}).pipe(ig(void 0)):e("playing"),n=Be(a,"volumechange").pipe(Lt(()=>({muted:a.muted,volume:a.volume}))),o=Be(a,"ratechange").pipe(Lt(()=>a.playbackRate)),u=Be(a,"error").pipe(rg(()=>!!(a.error||a.played.length)),Lt(()=>{var E;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:zR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=Be(a,"timeupdate").pipe(Lt(()=>a.currentTime)),d=new QR,c=.3,p;l.subscribe(y=>{a.loop&&tg(p)&&tg(y)&&p>=a.duration-c&&y<=c&&d.next(p),p=y});let h=e("pause").pipe(rg(()=>!a.error&&p!==a.duration)),f=Be(a,"enterpictureinpicture"),b=Be(a,"leavepictureinpicture"),g=new ag(Xb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new ag(Fu(a));return Be(a,"fullscreenchange").pipe(Lt(()=>Fu(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Be(a,"durationchange").pipe(Lt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as Mt}from"@vkontakte/videoplayer-shared";var Ct=a=>{switch(a){case"mobile":return Mt.Q_144P;case"lowest":return Mt.Q_240P;case"low":return Mt.Q_360P;case"sd":case"medium":return Mt.Q_480P;case"hd":case"high":return Mt.Q_720P;case"fullhd":case"full":return Mt.Q_1080P;case"quadhd":case"quad":return Mt.Q_1440P;case"ultrahd":case"ultra":return Mt.Q_2160P}};var Dt=L(Gr(),1),gg=L(Xe(),1),Fs=L(kt(),1);import{isNonNullable as re,isNullable as Uu,now as vg,isHigher as Hu,isHigherOrEqual as ju,isInvariantQuality as fg,isLower as mg,isLowerOrEqual as Gu,videoSizeToQuality as s$,assertNotEmptyArray as Sg,assertNonNullable as n$}from"@vkontakte/videoplayer-shared";var qu=!1,ct={},dg=a=>{qu=a},pg=()=>{ct={}},hg=a=>{a(ct)},Oi=(a,e)=>{var t;qu&&(ct.meta=(t=ct.meta)!=null?t:{},ct.meta[a]=e)},he=class{constructor(e){this.name=e}next(e){var r,i;if(!qu)return;ct.series=(r=ct.series)!=null?r:{};let t=(i=ct.series[this.name])!=null?i:[];t.push([Date.now(),e]),ct.series[this.name]=t}};var o$=new he("best_bitrate"),yg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Qu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Bi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=vg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Tg='Assertion "ABR Tracks is empty array" failed',qs=(a,e,t,r)=>{var u;let i=[...e].sort(Qu(1)),s=[...t].sort(Qu(1)),n=s.filter(l=>re(l.bitrate)&&re(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Dt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Dt.default)(s,-1);return o&&(0,gg.default)(n,o)?o:n.length?(0,Dt.default)(n,-1):(0,Dt.default)(s,0)},bg=a=>"quality"in a,Ig=(a,e,t,r)=>{var n;let i=re((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&re(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&vg()-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=bg(o)?"video":"audio",l=bg(o)?o.quality:o.bitrate;return e({message:`
7
8
  [last ${u} selected] ${l}
8
- `}),o}return i==null||i.recordSwitch(t),t},Mw=(a,e)=>Math.log(e)/Math.log(a),At=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:f})=>{var B,k,A,q,z;Pb(a,wb);let m=i.containerSizeFactor;if(i.usePixelRatio&&window.devicePixelRatio){let y=window.devicePixelRatio;if(i.pixelRatioMultiplier)m*=i.pixelRatioMultiplier*(y-1)+1;else{let R=i.pixelRatioLogBase,[F=0,C=0,X=0]=i.pixelRatioLogCoefficients,Te=Mw(R,F*y+C)+X;Number.isFinite(Te)&&(m*=Te)}}let g=i.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*m,height:e.height*m}:void 0,v=i.considerPlaybackRate&&ee(o)?o:1,S=a.filter(y=>!Tb(y.quality)).sort((y,R)=>Eu(y.quality,R.quality)?-1:1),T=(B=(0,Pt.default)(S,-1))==null?void 0:B.quality,E=(k=(0,Pt.default)(S,0))==null?void 0:k.quality,I=Iu(r)||ee(r.min)&&ee(r.max)&&Ib(r.max,r.min)||ee(r.min)&&E&&Eu(r.min,E)||ee(r.max)&&T&&Ib(r.max,T),$=v*Ab(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),D={},w=S.filter(y=>{let R=!0;if(g)if(y.size)R=y.size.width<=g.width&&y.size.height<=g.height;else{let J=g&&Rw(g);R=J?Pu(y.quality,J):!0}if(!R)return D[y.quality]="FitsContainer",!1;let F=p||t;if(!(ee(F)&&isFinite(F)&&ee(y.bitrate)?F-s>=y.bitrate*$:!0))return D[y.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&ee(i.minBufferToSwitchUp)&&u&&!Tb(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Eu(y.quality,u.quality))return D[y.quality]="Buffer",!1;if(!!c&&xu(y.quality,c))return D[y.quality]="DroppedFramesLimit",!1;if(!!h&&xu(y.quality,h))return D[y.quality]="StallsLimit",!1;let Bt=I||(Iu(r.max)||Pu(y.quality,r.max))&&(Iu(r.min)||xu(y.quality,r.min)),_=ee(d)&&!d?Pu(y.quality,i.backgroundVideoQualityLimit):!0;return!Bt||!_?(D[y.quality]="FitsQualityLimits",!1):!0})[0];w&&w.bitrate&&Lw.next(w.bitrate);let V=w!=null?w:(0,Pt.default)(S,-1);return V.quality!==((A=l==null?void 0:l.last)==null?void 0:A.quality)&&f({message:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},u$=(a,e)=>Math.log(e)/Math.log(a),Ot=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{var _,k,w,H,J,A;Sg(a,Tg);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let B=r.pixelRatioLogBase,[C=0,Z=0,Le=0]=r.pixelRatioLogCoefficients,gt=u$(B,C*T+Z)+Le;Number.isFinite(gt)&&(b*=gt)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,v=r.considerPlaybackRate&&re(o)?o:1,S=a.filter(T=>!fg(T.quality)).sort((T,B)=>Hu(T.quality,B.quality)?-1:1),y=(_=(0,Dt.default)(S,-1))==null?void 0:_.quality,E=(k=(0,Dt.default)(S,0))==null?void 0:k.quality,I=Uu(i)||re(i.min)&&re(i.max)&&mg(i.max,i.min)||re(i.min)&&E&&Hu(i.min,E)||re(i.max)&&y&&mg(i.max,y),R=v*yg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),D={},$=S.filter(T=>{let B=!0;if(g)if(T.size)B=T.size.width<=g.width&&T.size.height<=g.height;else{let ne=g&&s$(g);B=ne?Gu(T.quality,ne):!0}if(!B)return D[T.quality]="FitsContainer",!1;let C=h||t;if(!(re(C)&&isFinite(C)&&re(T.bitrate)?C-s>=T.bitrate*R:!0))return D[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&re(r.minBufferToSwitchUp)&&u&&!fg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Hu(T.quality,u.quality))return D[T.quality]="Buffer",!1;if(!!c&&ju(T.quality,c))return D[T.quality]="DroppedFramesLimit",!1;if(!!p&&ju(T.quality,p))return D[T.quality]="StallsLimit",!1;let F=I||(Uu(i.max)||Gu(T.quality,i.max))&&(Uu(i.min)||ju(T.quality,i.min)),se=re(d)&&!d?Gu(T.quality,r.backgroundVideoQualityLimit):!0;return!F||!se?(D[T.quality]="FitsQualityLimits",!1):!0})[0];$&&$.bitrate&&o$.next($.bitrate);let V=(w=$!=null?$:(0,Dt.default)(S,-1))!=null?w:a[0];return V.quality!==((H=l==null?void 0:l.last)==null?void 0:H.quality)&&f({message:`
9
10
  [VIDEO TRACKS ABR]
10
11
  [available video tracks]
11
- ${a.map(y=>`{ id: ${y.id}, quality: ${y.quality}, bitrate: ${y.bitrate} }`).join(`
12
+ ${a.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate} }`).join(`
12
13
  `)}
13
14
 
14
15
  [tuning]
15
- ${Object.entries(i!=null?i:{}).map(([y,R])=>`${y}: ${R}`).join(`
16
+ ${(0,Fs.default)(Object,r!=null?r:{}).map(([T,B])=>`${T}: ${B}`).join(`
16
17
  `)}
17
18
 
18
19
  [limit params]
19
- containerSizeLimit: ${(q=g==null?void 0:g.width)!=null?q:0} x ${(z=g==null?void 0:g.width)!=null?z:0},
20
+ containerSizeLimit: ${(J=g==null?void 0:g.width)!=null?J:0} x ${(A=g==null?void 0:g.width)!=null?A:0},
20
21
  estimatedThroughput: ${t},
21
- stallsPredictedThroughput: ${p},
22
+ stallsPredictedThroughput: ${h},
22
23
  reserve: ${s},
23
24
  playbackRate: ${o},
24
25
  playbackRateFactor: ${v},
25
26
  forwardBufferHealth: ${n},
26
- bitrateFactor: ${$},
27
- minBufferToSwitchUp: ${i.minBufferToSwitchUp},
27
+ bitrateFactor: ${R},
28
+ minBufferToSwitchUp: ${r.minBufferToSwitchUp},
28
29
  droppedVideoMaxQualityLimit: ${c},
29
- stallsVideoMaxQualityLimit: ${h},
30
+ stallsVideoMaxQualityLimit: ${p},
30
31
  limitsAreInvalid: ${I},
31
- maxQualityLimit: ${r==null?void 0:r.max},
32
- minQualityLimit: ${r==null?void 0:r.min},
32
+ maxQualityLimit: ${i==null?void 0:i.max},
33
+ minQualityLimit: ${i==null?void 0:i.min},
33
34
 
34
35
  [limited video tracks]
35
- ${Object.entries(D).map(([y,R])=>`${y}: ${R}`).join(`
36
+ ${(0,Fs.default)(Object,D).map(([T,B])=>`${T}: ${B}`).join(`
36
37
  `)||"All tracks are available"}
37
38
 
38
- [best video track] ${w==null?void 0:w.quality}
39
+ [best video track] ${$==null?void 0:$.quality}
39
40
  [selected video track] ${V==null?void 0:V.quality}
40
- `}),kb(i,f,V,l)},Rb=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Pb(t,wb);let d=r.considerPlaybackRate&&ee(s)?s:1,c=[...t].sort(Au(-1)),h=a.bitrate;$w(h);let p=d*Ab(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=ks(a,e,t,r.minVideoAudioRatio),g=l||i;return ee(g)&&isFinite(g)&&(f=c.find(S=>ee(S.bitrate)&&ee(m==null?void 0:m.bitrate)?g-h>=S.bitrate*p&&S.bitrate>=m.bitrate:!1)),f||(f=m),(f==null?void 0:f.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
41
+ `}),Ig(r,f,V,l)},Eg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Sg(t,Tg);let d=i.considerPlaybackRate&&re(s)?s:1,c=[...t].sort(Qu(-1)),p=a.bitrate;n$(p);let h=d*yg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=qs(a,e,t,i.minVideoAudioRatio),g=l||r;return re(g)&&isFinite(g)&&(f=c.find(S=>re(S.bitrate)&&re(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),f||(f=b),(f==null?void 0:f.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
41
42
  [AUDIO TRACKS ABR]
42
43
  [available audio tracks]
43
44
  ${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
44
45
  `)}
45
46
 
46
47
  [tuning]
47
- ${Object.entries(r!=null?r:{}).map(([S,T])=>`${S}: ${T}`).join(`
48
+ ${(0,Fs.default)(Object,i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
48
49
  `)}
49
50
 
50
51
  [limit params]
51
- estimatedThroughput: ${i},
52
+ estimatedThroughput: ${r},
52
53
  stallsPredictedThroughput: ${l},
53
- reserve: ${h},
54
+ reserve: ${p},
54
55
  playbackRate: ${s},
55
56
  playbackRateFactor: ${d},
56
57
  forwardBufferHealth: ${n},
57
- bitrateFactor: ${p},
58
- minBufferToSwitchUp: ${r.minBufferToSwitchUp},
58
+ bitrateFactor: ${h},
59
+ minBufferToSwitchUp: ${i.minBufferToSwitchUp},
59
60
 
60
61
  [selected audio track] ${f==null?void 0:f.id}
61
- `}),f&&kb(r,u,f,o)};var te=a=>new URL(a).hostname;import{assertNever as Vb,assertNonNullable as Bb,combine as Zw,debounce as ek,ErrorCategory as Ob,filter as _b,filterChanged as tk,isNonNullable as Lu,map as Ds,merge as Nb,observableFrom as ik,once as rk,Subscription as ak,ValueSubject as Mu,videoQualityToHeight as sk,videoSizeToQuality as nk}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"))},ge=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!$b(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return $b(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as $s,isNullable as Vw,assertNonNullable as Rr}from"@vkontakte/videoplayer-shared";import{isNonNullable as Lb,assertNonNullable as Rs,now as Dw}from"@vkontakte/videoplayer-shared";function ie(){return Dw()}function wu(a){return ie()-a}function ku(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(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 Mb(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Vi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,h=!1,p="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;Rs(d);let k=wu(d),A;if(k<m){A=m-k,setTimeout(g,A);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,$()},v=k=>(s=k,B),S=k=>(c=k,B),T=()=>(p="json",B),E=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},I=k=>(h=k,B),$=()=>{d=ie(),n=new r,n.open("get",a);let k=0,A,q=0,z=()=>(Rs(d),Math.max(d,Math.max(A||0,q||0)));if(s&&n.addEventListener("progress",y=>{let R=ie();s.updateChunk&&y.loaded>k&&(s.updateChunk(z(),y.loaded-k),k=y.loaded,A=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;Rs(n);let y=n.status;if(y>=200&&y<300){if(n.response.byteLength&&s){let R=n.response.byteLength-k;R&&s.updateChunk&&s.updateChunk(z(),R)}n.responseType==="json"&&!Object.values(n.response).length?E():(c&&c(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),h){let y=()=>{Rs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=ie(),n.removeEventListener("readystatechange",y))};n.addEventListener("readystatechange",y)}return n.responseType=p,n.send(),B},B={withBitrateReporting:v,withParallel:I,withJSONResponse:T,withRetryCount:k=>(l=k,B),withRetryInterval:(k,A)=>(Lb(k)&&(m=k),Lb(A)&&(f=A),B),withTimeout:k=>(o=k,B),withFinally:S,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return B}var wr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var kr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ie(),r=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()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Vi(t,s,()=>r("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 i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,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 Bw}from"@vkontakte/videoplayer-shared";var Ls=1e4,Ru=3;var Ow=6e4,_w=10,Nw=1,Fw=500,$r=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 Bw,this.chunkRateEstimator=new wr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ku(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ku(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,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)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||$s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Mb(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 kr(Ru,Ls,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let E=s&&(!d||d===this.rep);return E||t("Not running!"),E},h=(E,I,$)=>{u&&u.abort(),u=Vi(this.urlResolver.resolve(E,!1),I,$,()=>this._retryCallback()).withTimeout(Ls).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ru).withFinally(()=>{u=null}).send()},p=(E,I,$)=>{Rr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=E=>{let I=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),i.playbackRate=E)},m=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=ie()-1e4,D=0;for(let w=0;w<this.bufferStates.length;w++){let V=this.bufferStates[w];E=Math.min(E,V.buf),V.ts<$&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${E} drop=${D} jitter=${this.sourceJitter}`);let H=E-Nw;this.sourceJitter>=0?H-=this.sourceJitter/2:this.sourceJitter-=1,H>3?f(1.15):H>1?f(1.1):H>.3?f(1.05):f(1)}},v=E=>{let I,$=()=>I&&I.start?I.start.length:0,D=y=>I.start[y]/1e3,H=y=>I.dur[y]/1e3,w=y=>I.fragIndex+y,V=(y,R)=>({chunkIdx:w(y),startTS:D(y),dur:H(y),discontinuity:R}),B=()=>{let y=0;if(I&&I.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,F=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,C=R;this.sourceJitter>1&&(C+=this.sourceJitter-1);let X=I.dur.length-1;for(;X>=0&&(C-=I.dur[X],!(C<=0));--X);y=Math.min(X,I.dur.length-1-F),y=Math.max(y,0)}return V(y,!0)},k=y=>{let R=$();if(!(R<=0)){if($s(y)){for(let F=0;F<R;F++)if(D(F)>y)return V(F)}return B()}},A=y=>{let R=$(),F=y?y.chunkIdx+1:0,C=F-I.fragIndex;if(!(R<=0)){if(!y||C<0||C-R>_w)return t(`Resync: offset=${C} bChunks=${R} chunk=`+JSON.stringify(y)),B();if(!(C>=R))return V(F-I.fragIndex,!1)}},q=(y,R,F)=>{l&&l.abort(),l=Vi(this.urlResolver.resolve(y,!0,this.lowLatency),R,F,()=>this._retryCallback()).withTimeout(Ls).withRetryCount(Ru).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(y,R)=>{q(E,F=>{if(!c())return;I=F;let C=!!I.lowLatency;C!==this.lowLatency&&m(C);let X=0;for(let Te=0;Te<I.dur.length;++Te)X+=I.dur[Te];X>0&&(Rr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(X/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,y(k(R))},()=>this._handleNetworkError())},nextChunk:A}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Rr(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:E=>{let{videoElement:I,logger:$}=this.params,D=v(e.jidxUrl),H,w,V,B,k=0,A,q,z,y=()=>{A&&(clearTimeout(A),A=void 0);let _=Math.max(Fw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),J=k+_,Ie=ie(),Re=Math.min(1e4,J-Ie);k=Ie;let pt=()=>{l||c()&&D.seek(()=>{c()&&(k=ie(),R(),y())})};Re>0?A=window.setTimeout(()=>{this.paused?y():pt()},Re):pt()},R=()=>{let _;for(;_=D.nextChunk(B);)B=_,Gi(_);let J=D.nextChunk(V);if(J){if(V&&J.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?y():(S(),this._initPlayerWith(e));return}Te(J)}else y()},F=(_,J)=>{if(!c()||!this.sourceBuffer)return;let Ie,Re,pt,oi=ht=>{window.setTimeout(()=>{c()&&F(_,J)},ht)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),oi(100);else{let ht=ie(),Ot=I.currentTime;!this.paused&&I.buffered.length>1&&q===Ot&&ht-z>500&&($("Stall suspected; trying to fix"),this._fixupStall()),q!==Ot&&(q=Ot,z=ht);let ui=this._getBufferSizeSec();if(ui>30)$(`Buffered ${ui} seconds; delaying appendBuffer`),oi(2e3);else try{this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(this.bufferStates.push({ts:ht,buf:ui}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),J&&J()}catch(Qi){if(Qi.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),pt=this.sourceBuffer.buffered.length,pt!==0&&(Ie=this.sourceBuffer.buffered.start(0),Re=Ot,Re-Ie>4&&this.sourceBuffer.remove(Ie,Re-3)),oi(1e3);else throw Qi}}},C=()=>{w&&H&&($([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(V)]),F(w,function(){w=null,R()}))},X=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),Te=_=>{c()&&p(X(_),(J,Ie)=>{if(c()){if(Ie/=1e3,w=J,V=_,n=_.startTS,Ie){let Re=Math.min(10,_.dur/Ie);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Re:Re}C()}},()=>this._handleNetworkError())},Gi=_=>{c()&&(Rr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(X(_),!1)))},Bt=_=>{c()&&(e.cachedHeader=_,F(_,()=>{H=!0,C()}))};s=!0,D.seek(_=>{if(c()){if(k=ie(),!_){y();return}B=_,!Vw(E)||_.startTS>E?Te(_):(V=_,R())}},E),e.cachedHeader?Bt(e.cachedHeader):h(e.headerUrl,Bt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),$s(r)&&(r+=.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,Rr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return $s(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),f=c/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(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},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 c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&wu(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=s.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=ie();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Vi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ls).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;ge(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Ow))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Uw,filter as Db,fromEvent as qw,interval as Hw,isHigher as jw,isInvariantQuality as Gw,isLower as Qw,merge as Ww,Subject as Cb,Subscription as Yw}from"@vkontakte/videoplayer-shared";var $u=class{constructor(){this.onDroopedVideoFramesLimit$=new Cb;this.subscription=new Yw;this.playing=!1;this.tracks=[];this.forceChecker$=new Cb;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&&!Gw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&jw(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(qw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Hw(this.droppedFramesChecker.checkTime).pipe(Db(()=>this.playing),Db(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Uw(this.droppedFramesChecker.checkTime)),i=Ww(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>Qw(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[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}},Ms=$u;import{map as zw,Observable as Kw}from"@vkontakte/videoplayer-shared";import{fromEvent as Xw}from"@vkontakte/videoplayer-shared";var Lr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Jw=(a,e)=>new Kw(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Lr()))},{...i,...e});r.observe(a);let s=Xw(document,"visibilitychange").pipe(zw(n=>!document.hidden||Lr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe}}),Oe=Jw;var ok=["paused","playing","ready"],uk=["paused","playing","ready"],Mr=class{constructor(e){this.subscription=new ak;this.videoState=new L("stopped");this.representations$=new Mu([]);this.textTracksManager=new Ve;this.droppedFramesManager=new Ms;this.maxSeekBackTime$=new Mu(1/0);this.zeroTime$=new Mu(void 0);this.liveOffset=new ot;this._dashCb=e=>{var t,i,r,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:Ob.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),d=(i=xt(u.name))!=null?i:nk(u.video),c=u.bitrate/1e3,h={...u.video};if(!d)continue;let p={id:l,quality:d,bitrate:c,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.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),Lu(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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(uk.includes(e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&ok.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(se(this.params.source.url,u))}return;default:return Vb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Ob.WTF,message:"DashLiveProvider internal logic error",thrown:r})};Nb(this.videoState.stateChangeStarted$.pipe(Ds(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ds(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})}),this.video=he(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(te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=be(this.video);this.subscription.add(this.representations$.pipe(Ds(r=>r.map(({track:s})=>s)),_b(r=>!!r.length),rk()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(tk(),Ds(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Zw({zeroTime:this.zeroTime$.pipe(_b(Lu)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(Je(this.video,this.params.desiredState.isLooped,t)).add(me(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ce(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Oe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let s=r&&sk(r);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.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 Vb(r.to)}},t)).add(Nb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,ik(["init"])).pipe(ek(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),fe(this.video)}createLiveDashPlayer(){let e=new $r({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,d,c,h,p,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Lu(t)?t:At(e.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.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(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let m=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Bb(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Bb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Fb=Mr;var et=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as HR,assertNonNullable as jR,debounce as GR,ErrorCategory as cl,filter as vS,filterChanged as ba,fromEvent as QR,isNonNullable as yS,map as dl,merge as an,observableFrom as WR,observeElementSize as YR,once as TS,Subscription as zR,ValueSubject as KR}from"@vkontakte/videoplayer-shared";var Cs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];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}},Bi=class extends Cs{constructor(){super(),this.listeners||Cs.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)}},Dr=class{constructor(){Object.defineProperty(this,"signal",{value:new Bi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Dr.prototype[Symbol.toStringTag]="AbortController",Bi.prototype[Symbol.toStringTag]="AbortSignal");function Vs(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 Du(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!Vs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let h=new Promise((p,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Cr=Vs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ub=Cr?Du({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Qe=Cr?Ub.fetch:window.fetch,aB=Cr?Ub.Request:window.Request,ne=Cr?Dr:window.AbortController,sB=Cr?Bi:window.AbortSignal;var js=Ue(Ci(),1);var lt=()=>window.ManagedMediaSource||window.MediaSource,Bs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},qb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Hb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Qs,clientChecker as Gs}from"@vkontakte/videoplayer-shared";var _e=document.createElement("video"),dk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',pk='video/mp4; codecs="hev1.1.6.L93.B0"',eg='video/webm; codecs="vp09.00.10.08"',tg='video/webm; codecs="av01.0.00M.08"',hk='audio/mp4; codecs="mp4a.40.2"',fk='audio/webm; codecs="opus"',jb,Gb,Vr={mms:Bs(),mse:qb(),hls:!!((jb=_e.canPlayType)!=null&&jb.call(_e,"application/x-mpegurl")||(Gb=_e.canPlayType)!=null&&Gb.call(_e,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Qb,Wb,Se={mp4:!!((Qb=_e.canPlayType)!=null&&Qb.call(_e,"video/mp4")),webm:!!((Wb=_e.canPlayType)!=null&&Wb.call(_e,"video/webm")),cmaf:!0},_s,Yb,Ns,zb,Fs,Kb,Us,Xb,qs,Jb,Hs,Zb,ve={h264:!!((Yb=(_s=lt())==null?void 0:_s.isTypeSupported)!=null&&Yb.call(_s,dk)),h265:!!((zb=(Ns=lt())==null?void 0:Ns.isTypeSupported)!=null&&zb.call(Ns,pk)),vp9:!!((Kb=(Fs=lt())==null?void 0:Fs.isTypeSupported)!=null&&Kb.call(Fs,eg)),av1:!!((Xb=(Us=lt())==null?void 0:Us.isTypeSupported)!=null&&Xb.call(Us,tg)),aac:!!((Jb=(qs=lt())==null?void 0:qs.isTypeSupported)!=null&&Jb.call(qs,hk)),opus:!!((Zb=(Hs=lt())==null?void 0:Hs.isTypeSupported)!=null&&Zb.call(Hs,fk))},Oi=(ve.h264||ve.h265)&&ve.aac,Kt,mk=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:tg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:eg}})]);Kt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{mk()}catch(a){console.error(a)}var _i=Vr.hls&&Se.mp4,ig=()=>Object.keys(ve).filter(a=>ve[a]),rg=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let r=Vr.mse&&(!i||!!window.MediaStreamTrack)||Vr.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return r&&Se.mp4&&Oi;case"DASH_WEBM":return r&&Se.webm&&ve.vp9&&ve.opus;case"DASH_WEBM_AV1":return r&&Se.webm&&ve.av1&&ve.opus;case"DASH_STREAMS":return r&&(Se.mp4&&Oi||Se.webm&&(ve.vp9||ve.av1)&&(ve.opus||ve.aac));case"DASH_LIVE":return r&&Se.mp4&&Oi;case"DASH_LIVE_CMAF":return r&&Se.mp4&&Oi&&Se.cmaf;case"DASH_ONDEMAND":return r&&Se.mp4&&Oi;case"HLS":case"HLS_ONDEMAND":return _i||e&&r&&Se.mp4&&Oi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return _i;case"MPEG":return Se.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Vr.webrtc&&Vr.ws&&ve.h264&&(Se.mp4||Se.webm);default:return Qs(s)}})},Os=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 Kt?Kt[t].smooth?[t,e]:Kt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Kt?Kt[t].powerEfficient?[t,e]:Kt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Qs(a)}return[e,t]},ag=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Os(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Gs.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Os(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Os(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Os(a),...r,"HLS","HLS_ONDEMAND"];default:Qs(e)}return _i?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},sg=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=Gs.isMac&&Gs.isSafari;if(Gs.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:Qs(a)}else _i&&!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"]},Cu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ng=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,js.default)(t.value.split("."),0)}for(let t of a){let i=(0,js.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,js.default)(e.value.split("."),0)};import{ErrorCategory as Br}from"@vkontakte/videoplayer-shared";var og=a=>{if(!a)return{id:"EmptyResponse",category:Br.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Br.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:Br.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:Br.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Br.PARSER,message:"Response is valid XML, but parser failed"}};var wt=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as sl,assertNonNullable as ri,clientChecker as kR,combine as Js,ErrorCategory as Lt,filter as nl,filterChanged as lS,flattenObject as fa,fromEvent as ai,getTraceSubscriptionMethod as RR,interval as ol,isNonNullable as cS,map as ul,merge as si,now as $R,Subject as dS,Subscription as pS,tap as LR,throttle as MR,ValueSubject as K}from"@vkontakte/videoplayer-shared";var Ui=Ue(Ci(),1);var bk=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},gk=a=>window.clearTimeout(a),ug=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),lg=!ug(window.requestIdleCallback)||!ug(window.cancelIdleCallback),Vu=lg?bk:window.requestIdleCallback,vB=lg?gk:window.cancelIdleCallback;var tS=Ue(Ps(),1);import{assertNever as Sk,ErrorCategory as cg,clientChecker as Bu,Subject as dg}from"@vkontakte/videoplayer-shared";var vk=18,pg=!1;try{pg=Bu.isSafari&&!!Bu.macVersion&&Bu.macVersion<=vk}catch(a){console.error(a)}var Ou=class{constructor(e){this.bufferFull$=new dg;this.error$=new dg;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:cg.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i;pg&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.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:cg.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:Sk(t)}}},hg=Ou;var _u=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 ei,assertNonNullable as re,ErrorCategory as Rt,fromEvent as el,getExponentialDelay as tl,isNonNullable as na,isNullable as we,now as Ws,once as SR,Subject as vR,Subscription as yR,ValueSubject as oa}from"@vkontakte/videoplayer-shared";var U=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=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,r),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 r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Ni=class extends U{};var Or=class extends U{};var _r=class extends U{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Nr=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Q=class extends U{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Fr=class extends Q{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Ur=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var qr=class extends U{constructor(e,t){super(e,t),this.data=this.content}};var Xt=class extends Q{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Hr=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var jr=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gr=class extends Q{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Qr=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Wr=class extends Q{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Yr=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zr=class extends Q{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Kr=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xr=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Jr=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zr=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends Q{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ta=class extends Q{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ia=class extends Q{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)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 Tk={ftyp:_r,moov:Nr,mvhd:Fr,moof:Ur,mdat:qr,sidx:Xt,trak:Hr,mdia:Yr,mfhd:Jr,tkhd:zr,traf:Zr,tfhd:ea,tfdt:ta,trun:ia,minf:Kr,sv3d:jr,st3d:Gr,prhd:Qr,proj:Xr,equi:Wr,uuid:Or,unknown:Ni},kt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=Tk[e];return i?new i(t,new a):new Ni(t,new a)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 Ek=new TextDecoder("ascii"),xk=a=>Ek.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Pk=a=>{let e=new Xt(a,new kt),t=e.earliestPresentationTime/e.timescale*1e3,i=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:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},Ak=(a,e)=>{let i=new kt().parse(a),r=new Jt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},wk=a=>{var r;let t=new kt().parse(a);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},kk=(a,e)=>{let i=new kt().parse(a),s=new Jt(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Rk=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}}},i=new kt().parse(a),r=new Jt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.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},fg={validateData:xk,parseInit:Rk,getIndexRange:()=>{},parseSegments:Pk,parseFeedableSegmentChunk:Ak,getChunkEndTime:kk,getTimescaleFromIndex:wk};import{assertNonNullable as Fu,isNonNullable as Sg,isNullable as Lk}from"@vkontakte/videoplayer-shared";import{assertNever as $k}from"@vkontakte/videoplayer-shared";var mg={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"}},bg=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 i=ra(a,t),r=i in mg,s=r?mg[i].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,d=ra(u),c=l*2**((o-1)*8)+d,h=t+o,p;return h+c>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},ra=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},We=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ra(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:$k(e)}},Zt=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=bg(i);if(!e(r))return;r.type==="master"&&Zt(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},gg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=bg(a);return Zt(r.value,({tag:s,type:n,value:o})=>(s===17143?e=We(o,n):s===17026?t=We(o,n):s===17029&&(i=We(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var vg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Mk=[231,22612,22743,167,171,163,160,175],Dk=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return Zt(a,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=We(f,p);l=ra(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=We(f,p):h===17545?r=We(f,p):h===21420&&l===475249515?u=We(f,p):h===374648427?Zt(f,({tag:g,type:v,value:S})=>g===30321?(d=We(S,v)===1,!1):!0):s&&n&&vg.includes(h)&&(o=!0),!o}),Fu(e,"Failed to parse webm Segment start"),Fu(t,"Failed to parse webm Segment end"),Fu(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ck=a=>{if(Lk(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Vk=(a,e)=>{let t=!1,i=!1,r=o=>Sg(o.time)&&Sg(o.position),s=[],n;return Zt(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=We(l,u));break;case 183:break;case 241:n&&(n.position=We(l,u));break;default:t&&vg.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Bk=a=>{let e=0,t=!1;try{Zt(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Mk.includes(i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},yg={validateData:gg,parseInit:Dk,getIndexRange:Ck,parseSegments:Vk,parseFeedableSegmentChunk:Bk};var aa=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return yg;case"mp4":return fg}}throw new ReferenceError(`Unsupported mime type ${a}`)},Tg=a=>"getChunkEndTime"in a;var Wu=Ue(Hg(),1),zg=Ue(Ci(),1);var Qu=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as Qg,isNullable as Wg}from"@vkontakte/videoplayer-shared";var jg=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Gg=a=>{var e;try{let t=bR(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.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=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.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 bR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
62
+ `}),f&&Ig(i,u,f,o)};var ie=a=>new URL(a).hostname;import{assertNever as Cg,assertNonNullable as Dg,combine as R$,debounce as $$,ErrorCategory as Og,filter as Bg,filterChanged as L$,isNonNullable as Ju,map as Qs,merge as Vg,observableFrom as M$,once as C$,Subscription as D$,ValueSubject as Xu,videoQualityToHeight as O$,videoSizeToQuality as B$}from"@vkontakte/videoplayer-shared";var Pg=L(Xe(),1),xg=a=>{if(a instanceof DOMException&&(0,Pg.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},ye=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!xg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return xg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Hs,isNullable as d$,assertNonNullable as Ni}from"@vkontakte/videoplayer-shared";var wg=L(ut(),1);import{isNonNullable as Ag,assertNonNullable as Us,now as l$}from"@vkontakte/videoplayer-shared";function ae(){return l$()}function Wu(a){return ae()-a}function Yu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function kg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Qr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Us(d);let k=Wu(d),w;if(k<b){w=b-k,setTimeout(g,w);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,R()},v=k=>(s=k,_),S=k=>(c=k,_),y=()=>(h="json",_),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,c&&c(),t&&t()}},I=k=>(p=k,_),R=()=>{d=ae(),n=new i,n.open("get",a);let k=0,w,H=0,J=()=>(Us(d),Math.max(d,Math.max(w||0,H||0)));if(s&&n.addEventListener("progress",A=>{let T=ae();s.updateChunk&&A.loaded>k&&(s.updateChunk(J(),A.loaded-k),k=A.loaded,w=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;Us(n);let A=n.status;if(A>=200&&A<300){if(n.response.byteLength&&s){let T=n.response.byteLength-k;T&&s.updateChunk&&s.updateChunk(J(),T)}n.responseType==="json"&&!(0,wg.default)(Object,n.response).length?E():(c&&c(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){let A=()=>{Us(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(H=ae(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=h,n.send(),_},_={withBitrateReporting:v,withParallel:I,withJSONResponse:y,withRetryCount:k=>(l=k,_),withRetryInterval:(k,w)=>(Ag(k)&&(b=k),Ag(w)&&(f=w),_),withTimeout:k=>(o=k,_),withFinally:S,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return _}var Vi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Rg=L(ut(),1);var _i=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ae(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ae()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Qr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ae()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ae();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Rg.default)(Object,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 p$}from"@vkontakte/videoplayer-shared";var js=1e4,zu=3;var h$=6e4,f$=10,m$=1,b$=500,Fi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new p$,this.chunkRateEstimator=new Vi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Yu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Yu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Hs(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=()=>{kg(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new _i(zu,js,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,d=!1,c=()=>{let E=s&&(!d||d===this.rep);return E||t("Not running!"),E},p=(E,I,R)=>{u&&u.abort(),u=Qr(this.urlResolver.resolve(E,!1),I,R,()=>this._retryCallback()).withTimeout(js).withBitrateReporting(this.bitrateSwitcher).withRetryCount(zu).withFinally(()=>{u=null}).send()},h=(E,I,R)=>{Ni(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=E=>{let I=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),r.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=ae()-1e4,D=0;for(let $=0;$<this.bufferStates.length;$++){let V=this.bufferStates[$];E=Math.min(E,V.buf),V.ts<R&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${E} drop=${D} jitter=${this.sourceJitter}`);let G=E-m$;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?f(1.15):G>1?f(1.1):G>.3?f(1.05):f(1)}},v=E=>{let I,R=()=>I&&I.start?I.start.length:0,D=A=>I.start[A]/1e3,G=A=>I.dur[A]/1e3,$=A=>I.fragIndex+A,V=(A,T)=>({chunkIdx:$(A),startTS:D(A),dur:G(A),discontinuity:T}),_=()=>{let A=0;if(I&&I.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,B=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,C=T;this.sourceJitter>1&&(C+=this.sourceJitter-1);let Z=I.dur.length-1;for(;Z>=0&&(C-=I.dur[Z],!(C<=0));--Z);A=Math.min(Z,I.dur.length-1-B),A=Math.max(A,0)}return V(A,!0)},k=A=>{let T=R();if(!(T<=0)){if(Hs(A)){for(let B=0;B<T;B++)if(D(B)>A)return V(B)}return _()}},w=A=>{let T=R(),B=A?A.chunkIdx+1:0,C=B-I.fragIndex;if(!(T<=0)){if(!A||C<0||C-T>f$)return t(`Resync: offset=${C} bChunks=${T} chunk=`+JSON.stringify(A)),_();if(!(C>=T))return V(B-I.fragIndex,!1)}},H=(A,T,B)=>{l&&l.abort(),l=Qr(this.urlResolver.resolve(A,!0,this.lowLatency),T,B,()=>this._retryCallback()).withTimeout(js).withRetryCount(zu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,T)=>{H(E,B=>{if(!c())return;I=B;let C=!!I.lowLatency;C!==this.lowLatency&&b(C);let Z=0;for(let Le=0;Le<I.dur.length;++Le)Z+=I.dur[Le];Z>0&&(Ni(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,A(k(T))},()=>this._handleNetworkError())},nextChunk:w}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ni(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:E=>{let{videoElement:I,logger:R}=this.params,D=v(e.jidxUrl),G,$,V,_,k=0,w,H,J,A=()=>{w&&(clearTimeout(w),w=void 0);let F=Math.max(b$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),se=k+F,ne=ae(),Me=Math.min(1e4,se-ne);k=ne;let vt=()=>{l||c()&&D.seek(()=>{c()&&(k=ae(),T(),A())})};Me>0?w=window.setTimeout(()=>{this.paused?A():vt()},Me):vt()},T=()=>{let F;for(;F=D.nextChunk(_);)_=F,gt(F);let se=D.nextChunk(V);if(se){if(V&&se.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?A():(S(),this._initPlayerWith(e));return}Le(se)}else A()},B=(F,se)=>{if(!c()||!this.sourceBuffer)return;let ne,Me,vt,gr=St=>{window.setTimeout(()=>{c()&&B(F,se)},St)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),gr(100);else{let St=ae(),jt=I.currentTime;!this.paused&&I.buffered.length>1&&H===jt&&St-J>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),H!==jt&&(H=jt,J=St);let vr=this._getBufferSizeSec();if(vr>30)R(`Buffered ${vr} seconds; delaying appendBuffer`),gr(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:vr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),se&&se()}catch(ii){if(ii.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),vt=this.sourceBuffer.buffered.length,vt!==0&&(ne=this.sourceBuffer.buffered.start(0),Me=jt,Me-ne>4&&this.sourceBuffer.remove(ne,Me-3)),gr(1e3);else throw ii}}},C=()=>{$&&G&&(R([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(V)]),B($,function(){$=null,T()}))},Z=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),Le=F=>{c()&&h(Z(F),(se,ne)=>{if(c()){if(ne/=1e3,$=se,V=F,n=F.startTS,ne){let Me=Math.min(10,F.dur/ne);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Me:Me}C()}},()=>this._handleNetworkError())},gt=F=>{c()&&(Ni(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(F),!1)))},br=F=>{c()&&(e.cachedHeader=F,B(F,()=>{G=!0,C()}))};s=!0,D.seek(F=>{if(c()){if(k=ae(),!F){A();return}_=F,!d$(E)||F.startTS>E?Le(F):(V=F,T())}},E),e.cachedHeader?br(e.cachedHeader):p(e.headerUrl,br,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Hs(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ni(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Hs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=c=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),f=c/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let f=ae();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Wu(n)<3e4)return;r(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=ae();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=Qr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(js).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))},h$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Mg=L(kt(),1);import{debounce as g$,filter as $g,fromEvent as v$,interval as S$,isHigher as y$,isInvariantQuality as T$,isLower as I$,merge as E$,Subject as Lg,Subscription as x$}from"@vkontakte/videoplayer-shared";var Ku=class{constructor(){this.onDroopedVideoFramesLimit$=new Lg;this.subscription=new x$;this.playing=!1;this.tracks=[];this.forceChecker$=new Lg;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&&!T$(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&&y$(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(v$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=S$(this.droppedFramesChecker.checkTime).pipe($g(()=>this.playing),$g(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(g$(this.droppedFramesChecker.checkTime)),r=E$(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,Mg.default)(Object,this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>I$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Gs=Ku;import{map as P$,Observable as A$}from"@vkontakte/videoplayer-shared";import{fromEvent as w$}from"@vkontakte/videoplayer-shared";var qi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var k$=(a,e)=>new A$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||qi()))},{...r,...e});i.observe(a);let s=w$(document,"visibilitychange").pipe(P$(n=>!document.hidden||qi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ve=k$;var V$=["paused","playing","ready"],_$=["paused","playing","ready"],Ui=class{constructor(e){this.subscription=new D$;this.videoState=new M("stopped");this.representations$=new Xu([]);this.textTracksManager=new Oe;this.droppedFramesManager=new Gs;this.maxSeekBackTime$=new Xu(1/0);this.zeroTime$=new Xu(void 0);this.liveOffset=new lt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Og.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),d=(r=Ct(u.name))!=null?r:B$(u.video),c=u.bitrate/1e3,p={...u.video};if(!d)continue;let h={id:l,quality:d,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Ju(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Zu.default)(_$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Zu.default)(V$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ce(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ce(this.params.source.url,u))}return;default:return Cg(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Og.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Vg(this.videoState.stateChangeStarted$.pipe(Qs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Qs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Se(this.video);this.subscription.add(this.representations$.pipe(Qs(i=>i.map(({track:s})=>s)),Bg(i=>!!i.length),C$()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(L$(),Qs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(R$({zeroTime:this.zeroTime$.pipe(Bg(Ju)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ze(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(De(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&O$(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 Cg(i.to)}},t)).add(Vg(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,M$(["init"])).pipe($$(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 Fi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,p,h,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),r=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&Ju(t)?t:Ot(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Dg(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;Dg(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ce(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var _g=Ui;var Ey=L(Xe(),1),Fl=L(kt(),1);var tt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as SC,assertNonNullable as yC,debounce as TC,ErrorCategory as _l,filter as yy,filterChanged as Ra,fromEvent as IC,isNonNullable as Ty,map as Nl,merge as yn,observableFrom as EC,observeElementSize as xC,once as Iy,Subscription as PC,ValueSubject as AC}from"@vkontakte/videoplayer-shared";var Ws=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}},Wr=class extends Ws{constructor(){super(),this.listeners||Ws.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Hi=class{constructor(){Object.defineProperty(this,"signal",{value:new Wr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Hi.prototype[Symbol.toStringTag]="AbortController",Wr.prototype[Symbol.toStringTag]="AbortSignal");function Ys(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function el(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Ys({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,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ji=Ys({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ng=ji?el({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,dt=ji?Ng.fetch:window.fetch,jN=ji?Ng.Request:window.Request,ke=ji?Hi:window.AbortController,GN=ji?Wr:window.AbortSignal;var Bl=L(rl(),1);var il=L(ut(),1),an=L(Gr(),1);var pt=()=>window.ManagedMediaSource||window.MediaSource,zs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},sv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},nv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as nn,clientChecker as sn}from"@vkontakte/videoplayer-shared";var _e=document.createElement("video"),lL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',cL='video/mp4; codecs="hev1.1.6.L93.B0"',gv='video/webm; codecs="vp09.00.10.08"',vv='video/webm; codecs="av01.0.00M.08"',dL='audio/mp4; codecs="mp4a.40.2"',pL='audio/webm; codecs="opus"',ov,uv,Gi={mms:zs(),mse:sv(),hls:!!((ov=_e.canPlayType)!=null&&ov.call(_e,"application/x-mpegurl")||(uv=_e.canPlayType)!=null&&uv.call(_e,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},lv,cv,Te={mp4:!!((lv=_e.canPlayType)!=null&&lv.call(_e,"video/mp4")),webm:!!((cv=_e.canPlayType)!=null&&cv.call(_e,"video/webm")),cmaf:!0},Js,dv,Xs,pv,Zs,hv,en,fv,tn,mv,rn,bv,Ie={h264:!!((dv=(Js=pt())==null?void 0:Js.isTypeSupported)!=null&&dv.call(Js,lL)),h265:!!((pv=(Xs=pt())==null?void 0:Xs.isTypeSupported)!=null&&pv.call(Xs,cL)),vp9:!!((hv=(Zs=pt())==null?void 0:Zs.isTypeSupported)!=null&&hv.call(Zs,gv)),av1:!!((fv=(en=pt())==null?void 0:en.isTypeSupported)!=null&&fv.call(en,vv)),aac:!!((mv=(tn=pt())==null?void 0:tn.isTypeSupported)!=null&&mv.call(tn,dL)),opus:!!((bv=(rn=pt())==null?void 0:rn.isTypeSupported)!=null&&bv.call(rn,pL))},Yr=(Ie.h264||Ie.h265)&&Ie.aac,nr,hL=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:vv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:gv}})]);nr={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{hL()}catch(a){console.error(a)}var zr=Gi.hls&&Te.mp4,Sv=()=>Object.keys(Ie).filter(a=>Ie[a]),yv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Gi.mse&&(!r||!!window.MediaStreamTrack)||Gi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Te.mp4&&Yr;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&&Yr||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return i&&Te.mp4&&Yr;case"DASH_LIVE_CMAF":return i&&Te.mp4&&Yr&&Te.cmaf;case"DASH_ONDEMAND":return i&&Te.mp4&&Yr;case"HLS":case"HLS_ONDEMAND":return zr||e&&i&&Te.mp4&&Yr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return zr;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Gi.webrtc&&Gi.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return nn(s)}})},Ks=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 nr?nr[t].smooth?[t,e]:nr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return nr?nr[t].powerEfficient?[t,e]:nr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:nn(a)}return[e,t]},Tv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ks(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(sn.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",...Ks(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ks(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ks(a),...i,"HLS","HLS_ONDEMAND"];default:nn(e)}return zr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Iv=({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=sn.isMac&&sn.isSafari;if(sn.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:nn(a)}else zr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},al=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ev=a=>{if(a.size===0)return;if(a.size===1){let t=(0,il.default)(a).next();return(0,an.default)(t.value.split("."),0)}for(let t of a){let r=(0,an.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=(0,il.default)(a).next();return(0,an.default)(e.value.split("."),0)};var jv=L(Hv(),1);import{ErrorCategory as Wi}from"@vkontakte/videoplayer-shared";var Gv=a=>{if(!a)return{id:"EmptyResponse",category:Wi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Wi.NETWORK,message:`UV Error ${a}`};let e=(0,jv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Wi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Wi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Wi.PARSER,message:"Response is valid XML, but parser failed"}};var Bt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as Cl,assertNonNullable as pr,clientChecker as aC,combine as Pa,ErrorCategory as Ft,filter as mn,filterChanged as Dl,flattenObject as Aa,fromEvent as hr,getTraceSubscriptionMethod as sC,interval as Ol,isNonNullable as dy,map as wa,merge as fr,now as nC,Subject as py,Subscription as hy,tap as oC,throttle as uC,ValueSubject as K}from"@vkontakte/videoplayer-shared";var ln=L(Xe(),1),Zr=L(Gr(),1),cn=L(rl(),1),rt=L(ut(),1);var $L=(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)},LL=a=>window.clearTimeout(a),Qv=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Wv=!Qv(window.requestIdleCallback)||!Qv(window.cancelIdleCallback),ll=Wv?$L:window.requestIdleCallback,Yi=Wv?LL:window.cancelIdleCallback;var ry=L(kt(),1);var iy=L(Bs(),1);import{assertNever as ML,ErrorCategory as Yv,clientChecker as cl,Subject as zv}from"@vkontakte/videoplayer-shared";var CL=18,Kv=!1;try{Kv=cl.isSafari&&!!cl.macVersion&&cl.macVersion<=CL}catch(a){console.error(a)}var dl=class{constructor(e){this.bufferFull$=new zv;this.error$=new zv;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:Yv.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Kv&&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:Yv.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:ML(t)}}},Jv=dl;var pl=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 lr,assertNonNullable as fe,ErrorCategory as _t,fromEvent as kl,getExponentialDelay as Rl,isNonNullable as on,isNullable as Ne,now as un,once as YM,Subject as zM,Subscription as KM,ValueSubject as Xr}from"@vkontakte/videoplayer-shared";var U=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Kr=class extends U{};var zi=class extends U{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Ki=class extends U{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var Ji=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var W=class extends U{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Xi=class extends W{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Zi=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends U{constructor(e,t){super(e,t),this.data=this.content}};var or=class extends W{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ta=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=class extends W{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var aa=class extends W{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var sa=class extends W{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var na=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends W{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ua=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var la=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ca=class extends W{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var da=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pa=class extends W{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ha=class extends W{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var fa=class extends W{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var OL={ftyp:Ki,moov:Ji,mvhd:Xi,moof:Zi,mdat:ea,sidx:or,trak:ta,mdia:na,mfhd:ca,tkhd:oa,traf:da,tfhd:pa,tfdt:ha,trun:fa,minf:ua,sv3d:ra,st3d:ia,prhd:aa,proj:la,equi:sa,uuid:zi,unknown:Kr},ht=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=OL[e];return r?new r(t,new a):new Kr(t,new a)}};var Vt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var VL=new TextDecoder("ascii"),_L=a=>VL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",NL=a=>{let e=new or(a,new ht),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},FL=(a,e)=>{let r=new ht().parse(a),i=new Vt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},qL=a=>{let t=new ht().parse(a),r=new Vt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},UL=a=>{var i;let t=new ht().parse(a);return(i=new Vt(t).find("sidx"))==null?void 0:i.timescale},HL=(a,e)=>{let r=new ht().parse(a),s=new Vt(r).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},jL=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new ht().parse(a),i=new Vt(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Xv={validateData:_L,parseInit:jL,getIndexRange:()=>{},parseSegments:NL,parseFeedableSegmentChunk:FL,getChunkEndTime:HL,getServerLatencyTimestamps:qL,getTimescaleFromIndex:UL};var ba=L(Xe(),1);import{assertNonNullable as fl,isNonNullable as rS,isNullable as QL}from"@vkontakte/videoplayer-shared";import{assertNever as GL}from"@vkontakte/videoplayer-shared";var Zv={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"}},eS=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=ma(a,t),i=r in Zv,s=i?Zv[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,d=ma(u),c=l*2**((o-1)*8)+d,p=t+o,h;return p+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,c),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},ma=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Qe=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ma(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:GL(e)}},ur=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=eS(r);if(!e(i))return;i.type==="master"&&ur(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},tS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=eS(a);return ur(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Qe(o,n):s===17026?t=Qe(o,n):s===17029&&(r=Qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var iS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],WL=[231,22612,22743,167,171,163,160,175],YL=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return ur(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Qe(f,h);l=ma(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Qe(f,h):p===17545?i=Qe(f,h):p===21420&&l===475249515?u=Qe(f,h):p===374648427?ur(f,({tag:g,type:v,value:S})=>g===30321?(d=Qe(S,v)===1,!1):!0):s&&n&&(0,ba.default)(iS,p)&&(o=!0),!o}),fl(e,"Failed to parse webm Segment start"),fl(t,"Failed to parse webm Segment end"),fl(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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},zL=a=>{if(QL(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},KL=(a,e)=>{let t=!1,r=!1,i=o=>rS(o.time)&&rS(o.position),s=[],n;return ur(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Qe(l,u));break;case 183:break;case 241:n&&(n.position=Qe(l,u));break;default:t&&(0,ba.default)(iS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},JL=a=>{let e=0,t=!1;try{ur(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ba.default)(WL,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ba.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},aS={validateData:tS,parseInit:YL,getIndexRange:zL,parseSegments:KL,parseFeedableSegmentChunk:JL};var ga=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return aS;case"mp4":return Xv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Tl=L(xS(),1),WS=L(kt(),1),YS=L(FS(),1),zS=L(ut(),1),KS=L(Gr(),1);var qS=L(Xe(),1),yl=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,qS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as jS,isNullable as GS}from"@vkontakte/videoplayer-shared";var US=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var HS=a=>{var e;try{let t=QM(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function QM(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
62
63
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
63
64
  (-(?<script>[a-z]{4}))?
64
65
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
65
66
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
66
67
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
67
68
  (?:-(?<privateuse>(?:${e})))?
68
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Yg=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ct=(a,e)=>{let t=a;t=(0,Wu.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of Object.entries(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Wu.default)(t,n,(o,u)=>Wg(s)?o:Wg(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Kg=(a,e)=>{var I,$,D,H,w,V,B,k,A,q,z,y,R,F,C,X,Te,Gi,Bt,_,J,Ie,Re,pt,oi,ht,Ot,ui,Qi,Al,wl,kl,Rl,$l,Ll,Ml,Dl,Cl,Vl,Bl,Ol,_l,Nl,Fl,Ul,ql,Hl,jl,Gl,Ql,Wl,Yl,zl,Kl,Xl,Jl,Zl,ec,tc,ic;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(ae=>{var Ra,ft;return(ft=(Ra=ae.textContent)==null?void 0:Ra.trim())!=null?ft:""}),u=(I=(0,zg.default)(o,0))!=null?I:"",l=n.children,d=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),h=c?new Date(c).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],v=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=Yg(f);else if(m){let ae=Yg(m);Qg(ae)&&(p=ae)}else v&&(p=parseInt(v,10));let S=0,T=(D=($=s.getAttribute("profiles"))==null?void 0:$.split(","))!=null?D:[];for(let ae of l){let Ra=(H=ae.getAttribute("id"))!=null?H:"id"+(S++).toString(10),ft=(w=ae.getAttribute("mimeType"))!=null?w:"",vn=(V=ae.getAttribute("codecs"))!=null?V:"",yn=(B=ae.getAttribute("contentType"))!=null?B:ft==null?void 0:ft.split("/")[0],mv=(A=(k=ae.getAttribute("profiles"))==null?void 0:k.split(","))!=null?A:[],rc=(z=Gg((q=ae.getAttribute("lang"))!=null?q:""))!=null?z:{},bv=(F=(R=(y=ae.querySelector("Label"))==null?void 0:y.textContent)==null?void 0:R.trim())!=null?F:void 0,gv=ae.querySelectorAll("Representation"),Sv=ae.querySelector("SegmentTemplate"),vv=(X=(C=ae.querySelector("Role"))==null?void 0:C.getAttribute("value"))!=null?X:void 0,Wi=yn,Z={id:Ra,language:rc.language,isDefault:vv==="main",label:bv,codecs:vn,hdr:Wi==="video"&&Qu(vn),mime:ft,representations:[]};for(let G of gv){let yv=(Te=G.getAttribute("lang"))!=null?Te:void 0,Tv=(Gi=G.getAttribute("label"))!=null?Gi:void 0,Iv=(J=(_=(Bt=G.querySelector("BaseURL"))==null?void 0:Bt.textContent)==null?void 0:_.trim())!=null?J:"",$a=new URL(Iv||u,e).toString(),li=(Ie=G.getAttribute("mimeType"))!=null?Ie:ft,La=(pt=(Re=G.getAttribute("codecs"))!=null?Re:vn)!=null?pt:"",Ma;if(yn==="text"){let mt=G.getAttribute("id")||"",Da=((oi=rc.privateuse)==null?void 0:oi.includes("x-auto"))||mt.includes("_auto"),_t=G.querySelector("SegmentTemplate");if(_t){let Yi={representationId:(ht=G.getAttribute("id"))!=null?ht:void 0,bandwidth:(Ot=G.getAttribute("bandwidth"))!=null?Ot:void 0},Ca=parseInt((ui=G.getAttribute("bandwidth"))!=null?ui:"",10)/1e3,Va=(Al=parseInt((Qi=_t.getAttribute("startNumber"))!=null?Qi:"",10))!=null?Al:1,ci=parseInt((wl=_t.getAttribute("timescale"))!=null?wl:"",10),Tn=(kl=_t.querySelectorAll("SegmentTimeline S"))!=null?kl:[],di=_t.getAttribute("media");if(!di)continue;let Ba=[],Oa=0,_a="",pi=0,zi=Va,oe=0;for(let Ne of Tn){let Nt=parseInt((Rl=Ne.getAttribute("d"))!=null?Rl:"",10),$e=parseInt(($l=Ne.getAttribute("r"))!=null?$l:"",10)||0,bt=parseInt((Ll=Ne.getAttribute("t"))!=null?Ll:"",10);oe=Number.isFinite(bt)?bt:oe;let Ft=Nt/ci*1e3,gt=oe/ci*1e3;for(let ze=0;ze<$e+1;ze++){let St=ct(di,{...Yi,segmentNumber:zi.toString(10),segmentTime:(oe+ze*Nt).toString(10)}),hi=(gt!=null?gt:0)+ze*Ft,Xi=hi+Ft;zi++,Ba.push({time:{from:hi,to:Xi},url:St})}oe+=($e+1)*Nt,Oa+=($e+1)*Ft}pi=oe/ci*1e3,_a=ct(di,{...Yi,segmentNumber:zi.toString(10),segmentTime:oe.toString(10)});let Ki={time:{from:pi,to:1/0},url:_a},it={type:"template",baseUrl:$a,segmentTemplateUrl:di,initUrl:"",totalSegmentsDurationMs:Oa,segments:Ba,nextSegmentBeyondManifest:Ki,timescale:ci};Ma={id:mt,kind:"text",segmentReference:it,profiles:[],duration:p,bitrate:Ca,mime:"",codecs:"",width:0,height:0,isAuto:Da}}else Ma={id:mt,isAuto:Da,kind:"text",url:$a}}else{let mt=(Dl=(Ml=G.getAttribute("contentType"))!=null?Ml:li==null?void 0:li.split("/")[0])!=null?Dl:yn,Da=(Vl=(Cl=ae.getAttribute("profiles"))==null?void 0:Cl.split(","))!=null?Vl:[],_t=parseInt((Bl=G.getAttribute("width"))!=null?Bl:"",10),Yi=parseInt((Ol=G.getAttribute("height"))!=null?Ol:"",10),Ca=parseInt((_l=G.getAttribute("bandwidth"))!=null?_l:"",10)/1e3,Va=(Nl=G.getAttribute("frameRate"))!=null?Nl:"",ci=(Fl=G.getAttribute("quality"))!=null?Fl:void 0,Tn=Va?jg(Va):void 0,di=(Ul=G.getAttribute("id"))!=null?Ul:"id"+(S++).toString(10),Ba=mt==="video"?`${Yi}p`:mt==="audio"?`${Ca}Kbps`:La,Oa=`${di}@${Ba}`,_a=[...T,...mv,...Da],pi,zi=G.querySelector("SegmentBase"),oe=(ql=G.querySelector("SegmentTemplate"))!=null?ql:Sv;if(zi){let it=(jl=(Hl=G.querySelector("SegmentBase Initialization"))==null?void 0:Hl.getAttribute("range"))!=null?jl:"",[Ne,Nt]=it.split("-").map(St=>parseInt(St,10)),$e={from:Ne,to:Nt},bt=(Gl=G.querySelector("SegmentBase"))==null?void 0:Gl.getAttribute("indexRange"),[Ft,gt]=bt?bt.split("-").map(St=>parseInt(St,10)):[],ze=bt?{from:Ft,to:gt}:void 0;pi={type:"byteRange",url:$a,initRange:$e,indexRange:ze}}else if(oe){let it={representationId:(Ql=G.getAttribute("id"))!=null?Ql:void 0,bandwidth:(Wl=G.getAttribute("bandwidth"))!=null?Wl:void 0},Ne=parseInt((Yl=oe.getAttribute("timescale"))!=null?Yl:"",10),Nt=(zl=oe.getAttribute("initialization"))!=null?zl:"",$e=oe.getAttribute("media"),bt=(Xl=parseInt((Kl=oe.getAttribute("startNumber"))!=null?Kl:"",10))!=null?Xl:1,Ft=ct(Nt,it);if(!$e)throw new ReferenceError("No media attribute in SegmentTemplate");let gt=(Jl=oe.querySelectorAll("SegmentTimeline S"))!=null?Jl:[],ze=[],St=0,hi="",Xi=0;if(gt.length){let Na=bt,Fe=0;for(let fi of gt){let Ke=parseInt((Zl=fi.getAttribute("d"))!=null?Zl:"",10),Ut=parseInt((ec=fi.getAttribute("r"))!=null?ec:"",10)||0,Fa=parseInt((tc=fi.getAttribute("t"))!=null?tc:"",10);Fe=Number.isFinite(Fa)?Fa:Fe;let In=Ke/Ne*1e3,En=Fe/Ne*1e3;for(let Ua=0;Ua<Ut+1;Ua++){let xv=ct($e,{...it,segmentNumber:Na.toString(10),segmentTime:(Fe+Ua*Ke).toString(10)}),ac=(En!=null?En:0)+Ua*In,Pv=ac+In;Na++,ze.push({time:{from:ac,to:Pv},url:xv})}Fe+=(Ut+1)*Ke,St+=(Ut+1)*In}Xi=Fe/Ne*1e3,hi=ct($e,{...it,segmentNumber:Na.toString(10),segmentTime:Fe.toString(10)})}else if(Qg(p)){let Fe=parseInt((ic=oe.getAttribute("duration"))!=null?ic:"",10)/Ne*1e3,fi=Math.ceil(p/Fe),Ke=0;for(let Ut=1;Ut<fi;Ut++){let Fa=ct($e,{...it,segmentNumber:Ut.toString(10),segmentTime:Ke.toString(10)});ze.push({time:{from:Ke,to:Ke+Fe},url:Fa}),Ke+=Fe}Xi=Ke,hi=ct($e,{...it,segmentNumber:fi.toString(10),segmentTime:Ke.toString(10)})}let Ev={time:{from:Xi,to:1/0},url:hi};pi={type:"template",baseUrl:$a,segmentTemplateUrl:$e,initUrl:Ft,totalSegmentsDurationMs:St,segments:ze,nextSegmentBeyondManifest:Ev,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!mt||!li)continue;let Ki={video:"video",audio:"audio",text:"text"}[mt];if(!Ki)continue;Wi||(Wi=Ki),Ma={id:Oa,kind:Ki,segmentReference:pi,profiles:_a,duration:p,bitrate:Ca,mime:li,codecs:La,width:_t,height:Yi,fps:Tn,quality:ci}}Z.language||(Z.language=yv),Z.label||(Z.label=Tv),Z.mime||(Z.mime=li),Z.codecs||(Z.codecs=La),Z.hdr||(Z.hdr=Wi==="video"&&Qu(La)),Z.representations.push(Ma)}Wi&&r[Wi].push(Z)}return{dynamic:d,liveAvailabilityStartTime:h,duration:p,streams:r,baseUrls:o}};var Ku=Ue(Ci(),1);import{videoSizeToQuality as gR}from"@vkontakte/videoplayer-shared";var Xg=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s})=>{var o;let n=(o=s?xt(s):void 0)!=null?o:gR({width:e,height:t});return n&&{id:a,quality:n,bitrate:i,size:{width:e,height:t},fps:r}},Jg=({id:a,bitrate:e})=>({id:a,bitrate:e}),Zg=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),eS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Xu=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Ku.default)(i.split("."),0),isDefault:r}),Ju=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Ku.default)(r.split("."),0)}),Zu=a=>"url"in a,Ae=a=>a.type==="template",sa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ua=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new oa(0);this.onLastSegment$=new oa(!1);this.fullyBuffered$=new oa(!1);this.playingRepresentation$=new oa(void 0);this.playingRepresentationInit$=new oa(void 0);this.error$=new vR;this.gaps=[];this.subscription=new yR;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ne;this.switchAbortController=new ne;this.destroyAbortController=new ne;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=ei(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);re(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 hg(this.sourceBuffer),this.subscription.add(el(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(el(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Rt.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,_u(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=et(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);re(i,"No init buffer for starting representation"),re(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=ei(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(we(s)||we(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),re(r,"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();na(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ei(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=e==null?void 0:e.flatMap(d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!Ae(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);re(r);let s=this.segments.get(i);re(s,"No segments for starting representation");let n=this.initData.get(i);if(re(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,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,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=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),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 ne,ei(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);re(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(we(o)||we(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),re(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();na(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ne,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,d;if(we(e)||we(this.downloadingRepresentationId)||we(this.playingRepresentationId)||we(this.sourceBuffer)||na(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(re(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((l=r==null?void 0:r.time.to)!=null?l:0)-((d=r==null?void 0:r.time.from)!=null?d:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=et(this.sourceBuffer.buffered,e),p=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=r.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&_u(this.sourceBuffer.buffered)>=this.bufferLimit){let c=et(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))c="high";else{let h=(0,Ui.default)(o,0);h&&h.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&et(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Ui.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;na(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.streams[this.kind].flatMap(r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?i:[];for(let o of t){if(!o||!Ae(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,Ui.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,c=u==null?void 0:u.findIndex(h=>Math.floor(d)>=Math.floor(h.time.from)&&Math.floor(d)<=Math.floor(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(c+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;re(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){var s;re(this.playingRepresentationId);let e=(s=this.representations.get(this.playingRepresentationId))==null?void 0:s.duration;re(e);let{shortVideoDuration:t,shortVideoBufferStallSize:i,longVideoBufferStallSize:r}=this.tuning.dash.accumulationBufferStallSize;this.bufferAccumulation={enabled:!1,targetBufferSizeMs:e<=t?i:r,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ae(r))return;let s=(t=this.segments.get(i.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*r.timescale/1e3).toString(10),l=ct(r.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 i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.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,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+v||p<=i+v;return(c==="none"||c==="partially_ejected"&&g&&S&&this.sourceBuffer&&!(wt(this.sourceBuffer.buffered,h)&&wt(this.sourceBuffer.buffered,p)))&&g&&S});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<s.length&&(n<=l||o<=d);c++){let h=s[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){Ae(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ei(o,async function*(){let d=tl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Ws(),!d)return;let c=new DataView(d);if(!isFinite(r.segment.time.to)){let h=t.segmentReference.timescale,p=aa(t.mime);r.segment.time.to=p.getChunkEndTime(c,h)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),sa(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ae(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ei(n,async function*(){let u=tl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),el(window,"online").pipe(SR()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Ws(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),sa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ae(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ui.default)(e,0).byte.from,to:(0,Ui.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ws(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ae(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Ws();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=aa(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,f=c<=r;if(!p)continue;let m=aa(o.mime),g=this.tuning.dash.enableSubSegmentBufferFeeding&&(Tg(m)||this.bufferAccumulation.targetBufferSizeMs===0);if(l.status==="downloading"&&f){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h),S=this.getCurrentPosition();na(S)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-S,this.bufferAccumulation.accumulated.push({dataView:v,segmentProgress:u}),this.activeSegments.delete(u));let T=async({dataView:E,segmentProgress:I})=>{await this.sourceBufferTaskQueue.append(E,s)&&!s.aborted?this.onSegmentFullyAppended(I,t):n()};this.bufferAccumulation.enabled&&this.bufferAccumulation.accumulatedBufferSizeMs>this.bufferAccumulation.targetBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(T),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||we(S))&&(T({dataView:v,segmentProgress:u}),this.resetAccumulateBufferAfterStall())}else if(g&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===h?v:m.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){var i;this.tuning.useSafariEndlessRequestBugfix&&(re(this.sourceBuffer),wt(this.sourceBuffer.buffered,e.segment.time.from,100)&&wt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Rt.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",Zu(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])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");re(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[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Vu(()=>(0,tS.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ei(this.destroyAbortController.signal,async function*(){let o=tl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,aa(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&Ae(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),i&&this.error$.next({id:"LoadInits",category:Rt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||we(e)||this.sourceBuffer.updating)return!1;let r=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Zu(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let 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(d)&&c++;if(c===this.segments.size){let h={time:{from:l,to:d},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!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||we(e)?0:et(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){re(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Vu(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Rt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(we(this.sourceBuffer)||we(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var la=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var iS=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as ca,assertNever as aS,fromEvent as sS,merge as TR,now as da,Subscription as IR,ValueSubject as il,flattenObject as qi}from"@vkontakte/videoplayer-shared";var rS=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Ys=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new il(void 0);this.lastConnectionReused$=new il(void 0);this.lastRequestFirstBytes$=new il(void 0);this.abortAllController=new ne;this.subscription=new IR;this.fetchManifest=ca(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=la(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=rS(i));let r=yield Qe(i,{signal:this.abortAllController.signal}).catch(pa);return r?(t.log("success",qi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",qi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ca(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var B,k;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let A=new URL(l,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),l=A.toString();break}default:aS(t)}this.requestQuic&&(l=la(l));let h=this.abortAllController.signal,p;if(n){let A=new ne;if(p=TR(sS(this.abortAllController.signal,"abort"),sS(n,"abort")).subscribe(()=>{try{A.abort()}catch(q){pa(q)}}),this.abortAllController.signal.aborted||n.aborted)try{A.abort()}catch(q){pa(q)}h=A.signal}let f=da();c.log("startRequest",qi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let m=yield Qe(l,{priority:s,headers:d,signal:h}).catch(pa),g=da();if(!m)return c.error("error",{message:"No response in request"}),c.end(),p==null||p.unsubscribe(),null;if((B=this.throughputEstimator)==null||B.addRawRtt(g-f),!m.ok||!m.body){p==null||p.unsubscribe();let A=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:A}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){p==null||p.unsubscribe();let A=da(),q={requestStartedAt:f,requestEndedAt:A,duration:A-f};return c.log("endRequest",qi(q)),c.end(),m.arrayBuffer()}let[v,S]=m.body.tee(),T=v.getReader();o&&((k=this.throughputEstimator)==null||k.trackStream(S,u));let E=0,I=new Uint8Array(0),$=!1,D=A=>{p==null||p.unsubscribe(),$=!0,pa(A)},H=ca(h,async function*({done:A,value:q}){if(E===0&&this.lastRequestFirstBytes$.next(da()-f),h.aborted){p==null||p.unsubscribe();return}if(!A&&q){let z=new Uint8Array(I.length+q.length);z.set(I),z.set(q,I.length),I=z,E+=q.byteLength,r==null||r(new DataView(I.buffer),E),yield T==null?void 0:T.read().then(H,D)}}.bind(this));yield T==null?void 0:T.read().then(H,D),p==null||p.unsubscribe();let w=da(),V={failed:$,requestStartedAt:f,requestEndedAt:w,duration:w-f};return $?(c.error("endRequest",qi(V)),c.end(),null):(c.log("endRequest",qi(V)),c.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=ca(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-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 m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!S)return null;m=new DataView(S)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=ca(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=iS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:aS(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},pa=a=>{if(!sa(a))throw a};var ti=(a,e,t)=>t*e+(1-t)*a,rl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,nS=(a,e,t,i)=>{let r=0,s=t,n=rl(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as ER,ValueSubject as oS}from"@vkontakte/videoplayer-shared";var $t=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new oS(e.initial),this.debounced$=new oS(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new le(`raw_${t}`),this.smoothedSeries$=new le(`smoothed_${t}`),this.reportedSeries$=new le(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;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)&&(ER(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 zs=class extends $t{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ti(this.slow,e,this.params.emaAlphaSlow),this.fast=ti(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ks=class extends $t{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=rl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ti(this.emaSmoothed,e,this.params.emaAlpha);let i=nS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Xs=class extends $t{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?ti(this.smoothed,t,this.params.emaAlpha):t}};var ii=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new zs({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ks({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Xs({initial:e,label:"liveEdgeDelay",...t})}};var al=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as xR,ValueSubject as PR}from"@vkontakte/videoplayer-shared";var ha=class a{constructor(e,t){this.currentRepresentation$=new PR(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(!xR(e))for(let i of this.representations)for(let r of i){let s=r.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(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,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 i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,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&&Ae(t.segmentReference))}};var DR=["timeupdate","progress","play","seeked","stalled","waiting"],CR=["timeupdate","progress","loadeddata","playing","seeked"];var Zs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new pS;this.representationSubscription=new pS;this.state$=new L("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new dS;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.liveDuration$=new K(0);this.liveAvailabilityStartTime$=new K(void 0);this.bufferLength$=new K(0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.isLowLatency$=new K(!1);this.isActiveLowLatency$=new K(!1);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new dS;this.gapWatchdogActive=!1;this.destroyController=new ne;this.initManifest=sl(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Lt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=sl(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Lt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Kg(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=og(e))!=null?n:{id:"ManifestParsing",category:Lt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=lt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||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 r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=ng(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);kR.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",fa(s)),s}.bind(this));this.initRepresentations=sl(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",fa({initialVideo:e,initialAudio:t,sourceHls:i})),ri(this.manifest),ri(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(ai(p,"error").pipe(nl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Hb():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Bs())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new ua("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],cS(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new ua("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ha.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ha(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(ol(1e3).subscribe(p=>{var f;if((f=this.element)!=null&&f.paused){let m=hu(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(si(...CR.map(p=>ai(this.element,p))).pipe(ul(p=>this.element?et(this.element.buffered,this.element.currentTime*1e3):0),lS(),LR(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(si(ai(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(lS()).subscribe(f=>al(this.element,1))),this.representationSubscription.add(Js({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(nl(({bufferLength:f,isActiveLowLatency:m})=>m&&!!f)).subscribe(({bufferLength:f})=>this.liveEstimatedDelay.next(f))),this.representationSubscription.add(Js({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:f,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=f-g,E=1;Math.abs(T)>v&&(E=1+Math.sign(T)*S),al(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,v;let m=0;if(f){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;m=Math.min(...this.bufferManagers.map(E=>{var I,$;return($=(I=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?$:S}))-S}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(Js({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(MR(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(ri(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=hu(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(f)?f:m,D=this.isActiveLowLatency$.getValue(),H=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(D&&H);let w="none";if(D?w="active_low_latency":this.isLowLatency$.getValue()&&H?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(V=>V.proceedLowLatencyLive()),w="active_low_latency"):v!==0&&$<T?w="live_forward_buffering":$<T+I&&(w="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let V=p-(T+E),B=this.normolizeLiveOffset(Math.trunc(v+V/g)),k=Math.abs(B-v),A;!f||k<=this.tuning.dashCmafLive.offsetCalculationError?A=v:B>0&&k>this.tuning.dashCmafLive.offsetCalculationError?A=B:A=0,this.manifestUrlString=se(this.manifestUrlString,A,2)}w!=="none"&&w!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=si(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ul(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=si(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ul(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(si(this.forceEnded$,Js({allBuffersFull:l,someBufferEnded:d}).pipe(nl(({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:Lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(si(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",p)}));let c=[(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),Ae(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&cS(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,i,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(i=this.liveTextManager)==null||i.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ol(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Lt.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 Ys({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveEstimatedDelay=ii.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){var i,r,s;ri(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=se(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video)),await((r=this.audioBufferManager)==null?void 0:r.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){ri(this.element),this.state$.setState("running"),this.subscription.add(si(...DR.map(e=>ai(this.element,e)),ai(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Lt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ai(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ai(this.element,"waiting").subscribe(()=>{var t,i,r;this.element&&this.element.readyState===2&&!this.element.seeking&&wt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var m,g,v,S,T,E,I,$,D,H;if(!this.element)return;let s=this.currentStallDuration$.getValue();s+=50,this.currentStallDuration$.next(s);let n={timeInWaiting:s},o=$R(),u=100,l=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(l);let d=(S=(v=this.audioBufferManager)==null?void 0:v.lastDataObtainedTimestamp)!=null?S:0,c=(E=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?E:0,h=($=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?$:0,p=c<u&&o-l>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&h<u&&o-d>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||f)&&s>this.tuning.dash.crashOnStallTWithoutDataTimeout||s>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${s} ms`);if(this.isLive$.getValue()&&s%5e3===0)this.seekLive(this.liveLastSeekOffset),n.liveLastSeekOffset=this.liveLastSeekOffset;else{let w=this.element.currentTime*1e3;(D=this.videoBufferManager)==null||D.maintain(w),(H=this.audioBufferManager)==null||H.maintain(w),n.position=w}this.tracer.log("stallIntervalCallback",fa(n))};(t=this.videoBufferManager)==null||t.startAccumulateBuffer(),(i=this.audioBufferManager)==null||i.startAccumulateBuffer(),(r=this.stallWatchdogSubscription)==null||r.unsubscribe(),this.stallWatchdogSubscription=ol(50).subscribe(e,s=>{this.error$.next({id:"StallWatchdogCallback",category:Lt.NETWORK,message:"Can't restore DASH after stall.",thrown:s})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t,i)}seek(e,t){var r,s,n,o,u,l;ri(this.element),ri(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),wt(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.startAccumulateBuffer(),(l=this.audioBufferManager)==null||l.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",fa({requestedPosition:e,forcePrecise:t,position:i}))}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.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=RR(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.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 i=this.element.currentTime*1e3,r=[],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<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let n=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:r,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",fa(t)))}}};var en=class{constructor(e,t){this.fov=e,this.orientation=t}};var tn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var hS=`attribute vec2 a_vertex;
69
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var QS=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},ft=(a,e)=>{let t=a;t=(0,Tl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,WS.default)(Object,r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Tl.default)(t,n,(o,u)=>GS(s)?o:GS(u)?s:(0,YS.default)(s,parseInt(u,10),"0"))}return t},JS=(a,e)=>{var I,R,D,G,$,V,_,k,w,H,J,A,T,B,C,Z,Le,gt,br,F,se,ne,Me,vt,gr,St,jt,vr,ii,rc,ic,ac,sc,nc,oc,uc,lc,cc,dc,pc,hc,fc,mc,bc,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from((0,zS.default)(s.querySelectorAll("MPD > BaseURL"))).map(oe=>{var Ha,yt;return(yt=(Ha=oe.textContent)==null?void 0:Ha.trim())!=null?yt:""}),u=(I=(0,KS.default)(o,0))!=null?I:"",l=n.children,d=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,h,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)h=QS(f);else if(b){let oe=QS(b);jS(oe)&&(h=oe)}else v&&(h=parseInt(v,10));let S=0,y=(D=(R=s.getAttribute("profiles"))==null?void 0:R.split(","))!=null?D:[];for(let oe of l){let Ha=(G=oe.getAttribute("id"))!=null?G:"id"+(S++).toString(10),yt=($=oe.getAttribute("mimeType"))!=null?$:"",Dn=(V=oe.getAttribute("codecs"))!=null?V:"",On=(_=oe.getAttribute("contentType"))!=null?_:yt==null?void 0:yt.split("/")[0],yT=(w=(k=oe.getAttribute("profiles"))==null?void 0:k.split(","))!=null?w:[],Cc=(J=HS((H=oe.getAttribute("lang"))!=null?H:""))!=null?J:{},TT=(B=(T=(A=oe.querySelector("Label"))==null?void 0:A.textContent)==null?void 0:T.trim())!=null?B:void 0,IT=oe.querySelectorAll("Representation"),ET=oe.querySelector("SegmentTemplate"),xT=(Z=(C=oe.querySelector("Role"))==null?void 0:C.getAttribute("value"))!=null?Z:void 0,ai=On,ee={id:Ha,language:Cc.language,isDefault:xT==="main",label:TT,codecs:Dn,hdr:ai==="video"&&yl(Dn),mime:yt,representations:[]};for(let Q of IT){let PT=(Le=Q.getAttribute("lang"))!=null?Le:void 0,AT=(gt=Q.getAttribute("label"))!=null?gt:void 0,wT=(se=(F=(br=Q.querySelector("BaseURL"))==null?void 0:br.textContent)==null?void 0:F.trim())!=null?se:"",ja=new URL(wT||u,e).toString(),Sr=(ne=Q.getAttribute("mimeType"))!=null?ne:yt,Ga=(vt=(Me=Q.getAttribute("codecs"))!=null?Me:Dn)!=null?vt:"",Qa;if(On==="text"){let Tt=Q.getAttribute("id")||"",Wa=((gr=Cc.privateuse)==null?void 0:gr.includes("x-auto"))||Tt.includes("_auto"),Gt=Q.querySelector("SegmentTemplate");if(Gt){let si={representationId:(St=Q.getAttribute("id"))!=null?St:void 0,bandwidth:(jt=Q.getAttribute("bandwidth"))!=null?jt:void 0},Ya=parseInt((vr=Q.getAttribute("bandwidth"))!=null?vr:"",10)/1e3,za=(rc=parseInt((ii=Gt.getAttribute("startNumber"))!=null?ii:"",10))!=null?rc:1,yr=parseInt((ic=Gt.getAttribute("timescale"))!=null?ic:"",10),Bn=(ac=Gt.querySelectorAll("SegmentTimeline S"))!=null?ac:[],Tr=Gt.getAttribute("media");if(!Tr)continue;let Ka=[],Ja=0,Xa="",Ir=0,ni=za,pe=0;for(let Fe of Bn){let Qt=parseInt((sc=Fe.getAttribute("d"))!=null?sc:"",10),Ce=parseInt((nc=Fe.getAttribute("r"))!=null?nc:"",10)||0,It=parseInt((oc=Fe.getAttribute("t"))!=null?oc:"",10);pe=Number.isFinite(It)?It:pe;let Wt=Qt/yr*1e3,Et=pe/yr*1e3;for(let Ye=0;Ye<Ce+1;Ye++){let xt=ft(Tr,{...si,segmentNumber:ni.toString(10),segmentTime:(pe+Ye*Qt).toString(10)}),Er=(Et!=null?Et:0)+Ye*Wt,ui=Er+Wt;ni++,Ka.push({time:{from:Er,to:ui},url:xt})}pe+=(Ce+1)*Qt,Ja+=(Ce+1)*Wt}Ir=pe/yr*1e3,Xa=ft(Tr,{...si,segmentNumber:ni.toString(10),segmentTime:pe.toString(10)});let oi={time:{from:Ir,to:1/0},url:Xa},at={type:"template",baseUrl:ja,segmentTemplateUrl:Tr,initUrl:"",totalSegmentsDurationMs:Ja,segments:Ka,nextSegmentBeyondManifest:oi,timescale:yr};Qa={id:Tt,kind:"text",segmentReference:at,profiles:[],duration:h,bitrate:Ya,mime:"",codecs:"",width:0,height:0,isAuto:Wa}}else Qa={id:Tt,isAuto:Wa,kind:"text",url:ja}}else{let Tt=(lc=(uc=Q.getAttribute("contentType"))!=null?uc:Sr==null?void 0:Sr.split("/")[0])!=null?lc:On,Wa=(dc=(cc=oe.getAttribute("profiles"))==null?void 0:cc.split(","))!=null?dc:[],Gt=parseInt((pc=Q.getAttribute("width"))!=null?pc:"",10),si=parseInt((hc=Q.getAttribute("height"))!=null?hc:"",10),Ya=parseInt((fc=Q.getAttribute("bandwidth"))!=null?fc:"",10)/1e3,za=(mc=Q.getAttribute("frameRate"))!=null?mc:"",yr=(bc=Q.getAttribute("quality"))!=null?bc:void 0,Bn=za?US(za):void 0,Tr=(gc=Q.getAttribute("id"))!=null?gc:"id"+(S++).toString(10),Ka=Tt==="video"?`${si}p`:Tt==="audio"?`${Ya}Kbps`:Ga,Ja=`${Tr}@${Ka}`,Xa=[...y,...yT,...Wa],Ir,ni=Q.querySelector("SegmentBase"),pe=(vc=Q.querySelector("SegmentTemplate"))!=null?vc:ET;if(ni){let at=(yc=(Sc=Q.querySelector("SegmentBase Initialization"))==null?void 0:Sc.getAttribute("range"))!=null?yc:"",[Fe,Qt]=at.split("-").map(xt=>parseInt(xt,10)),Ce={from:Fe,to:Qt},It=(Tc=Q.querySelector("SegmentBase"))==null?void 0:Tc.getAttribute("indexRange"),[Wt,Et]=It?It.split("-").map(xt=>parseInt(xt,10)):[],Ye=It?{from:Wt,to:Et}:void 0;Ir={type:"byteRange",url:ja,initRange:Ce,indexRange:Ye}}else if(pe){let at={representationId:(Ic=Q.getAttribute("id"))!=null?Ic:void 0,bandwidth:(Ec=Q.getAttribute("bandwidth"))!=null?Ec:void 0},Fe=parseInt((xc=pe.getAttribute("timescale"))!=null?xc:"",10),Qt=(Pc=pe.getAttribute("initialization"))!=null?Pc:"",Ce=pe.getAttribute("media"),It=(wc=parseInt((Ac=pe.getAttribute("startNumber"))!=null?Ac:"",10))!=null?wc:1,Wt=ft(Qt,at);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");let Et=(kc=pe.querySelectorAll("SegmentTimeline S"))!=null?kc:[],Ye=[],xt=0,Er="",ui=0;if(Et.length){let Za=It,qe=0;for(let xr of Et){let ze=parseInt((Rc=xr.getAttribute("d"))!=null?Rc:"",10),Yt=parseInt(($c=xr.getAttribute("r"))!=null?$c:"",10)||0,es=parseInt((Lc=xr.getAttribute("t"))!=null?Lc:"",10);qe=Number.isFinite(es)?es:qe;let Vn=ze/Fe*1e3,_n=qe/Fe*1e3;for(let ts=0;ts<Yt+1;ts++){let RT=ft(Ce,{...at,segmentNumber:Za.toString(10),segmentTime:(qe+ts*ze).toString(10)}),Dc=(_n!=null?_n:0)+ts*Vn,$T=Dc+Vn;Za++,Ye.push({time:{from:Dc,to:$T},url:RT})}qe+=(Yt+1)*ze,xt+=(Yt+1)*Vn}ui=qe/Fe*1e3,Er=ft(Ce,{...at,segmentNumber:Za.toString(10),segmentTime:qe.toString(10)})}else if(jS(h)){let qe=parseInt((Mc=pe.getAttribute("duration"))!=null?Mc:"",10)/Fe*1e3,xr=Math.ceil(h/qe),ze=0;for(let Yt=1;Yt<xr;Yt++){let es=ft(Ce,{...at,segmentNumber:Yt.toString(10),segmentTime:ze.toString(10)});Ye.push({time:{from:ze,to:ze+qe},url:es}),ze+=qe}ui=ze,Er=ft(Ce,{...at,segmentNumber:xr.toString(10),segmentTime:ze.toString(10)})}let kT={time:{from:ui,to:1/0},url:Er};Ir={type:"template",baseUrl:ja,segmentTemplateUrl:Ce,initUrl:Wt,totalSegmentsDurationMs:xt,segments:Ye,nextSegmentBeyondManifest:kT,timescale:Fe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Tt||!Sr)continue;let oi={video:"video",audio:"audio",text:"text"}[Tt];if(!oi)continue;ai||(ai=oi),Qa={id:Ja,kind:oi,segmentReference:Ir,profiles:Xa,duration:h,bitrate:Ya,mime:Sr,codecs:Ga,width:Gt,height:si,fps:Bn,quality:yr}}ee.language||(ee.language=PT),ee.label||(ee.label=AT),ee.mime||(ee.mime=Sr),ee.codecs||(ee.codecs=Ga),ee.hdr||(ee.hdr=ai==="video"&&yl(Ga)),ee.representations.push(Qa)}ai&&i[ai].push(ee)}return{dynamic:d,liveAvailabilityStartTime:p,duration:h,streams:i,baseUrls:o}};var xl=L(Gr(),1);import{videoSizeToQuality as WM}from"@vkontakte/videoplayer-shared";var XS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ct(s):void 0)!=null?u:WM({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},ZS=({id:a,bitrate:e})=>({id:a,bitrate:e}),ey=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ty=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Pl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,xl.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,xl.default)(i.split("."),0)}),wl=a=>"url"in a,Re=a=>a.type==="template",va=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Sa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Xr(0);this.currentSegmentLength$=new Xr(0);this.onLastSegment$=new Xr(!1);this.fullyBuffered$=new Xr(!1);this.playingRepresentation$=new Xr(void 0);this.playingRepresentationInit$=new Xr(void 0);this.error$=new zM;this.gaps=[];this.subscription=new KM;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=lr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);fe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Jv(this.sourceBuffer),this.subscription.add(kl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:_t.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:_t.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(kl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:_t.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,pl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=tt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);fe(r,"No init buffer for starting representation"),fe(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=lr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);fe(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ne(s)||Ne(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),fe(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))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();on(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=lr(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,cn.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let p=this.representations.get(d);if(!p||!Re(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);fe(i);let s=this.segments.get(r);fe(s,"No segments for starting representation");let n=this.initData.get(r);if(fe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,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 d;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=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),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,lr(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);fe(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Ne(o)||Ne(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),fe(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){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();on(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,d;if(Ne(e)||Ne(this.downloadingRepresentationId)||Ne(this.playingRepresentationId)||Ne(this.sourceBuffer)||on(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(fe(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((d=i==null?void 0:i.time.from)!=null?d:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=tt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&pl(this.sourceBuffer.buffered)>=this.bufferLimit){let c=tt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,ln.default)(o,i))c="high";else{let p=(0,Zr.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&tt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Zr.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;on(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,cn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,cn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Re(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,Zr.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,c=u==null?void 0:u.findIndex(p=>Math.floor(d)>=Math.floor(p.time.from)&&Math.floor(d)<=Math.floor(p.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(c+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;fe(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of(0,rt.default)(this.representations)){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=ft(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Yi&&Yi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yi&&Yi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:c,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(c==="none"||c==="partially_ejected"&&g&&S&&this.sourceBuffer&&!(Bt(this.sourceBuffer.buffered,p)&&Bt(this.sourceBuffer.buffered,h)))&&g&&S});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=i;c<s.length&&(n<=l||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){Re(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await lr(o,async function*(){let d=Rl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=un(),!d)return;let c=new DataView(d),p=ga(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(c,b)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),va(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of(0,rt.default)(this.representations))Re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await lr(n,async function*(){let u=Rl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),kl(window,"online").pipe(YM()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=un(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),va(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Re(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Zr.default)(e,0).byte.from,to:(0,Zr.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=un(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:_t.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!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,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=un();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:_t.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,ln.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=ga(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-r,c=l.byte.to-r,p=c-d+1,h=d<i,f=c<=i;if(!h)continue;let b=ga(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(fe(this.sourceBuffer),Bt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Bt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:_t.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",wl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of(0,rt.default)(this.representations))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");fe(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of(0,rt.default)(this.activeSegments))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(0,ry.default)(this.initData)){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=ll(()=>(0,iy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?lr(this.destroyAbortController.signal,async function*(){let o=Rl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ga(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&Re(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:_t.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of(0,rt.default)(this.segments))for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ne(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=wl(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of(0,rt.default)(this.segments))for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of(0,rt.default)(this.segments))for(let h of p)(0,ln.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of(0,rt.default)(this.segments))for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||Ne(e)?0:tt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){fe(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=ll(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:_t.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ne(this.sourceBuffer)||Ne(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of(0,rt.default)(this.segments))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(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(d=>d.from===i.time.from||d.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ya=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ay=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ta,assertNever as ny,fromEvent as oy,merge as JM,now as Ia,Subscription as XM,ValueSubject as $l,flattenObject as ei}from"@vkontakte/videoplayer-shared";var sy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var dn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new $l(void 0);this.lastConnectionReused$=new $l(void 0);this.lastRequestFirstBytes$=new $l(void 0);this.abortAllController=new ke;this.subscription=new XM;this.fetchManifest=Ta(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ya(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=sy(r));let i=yield dt(r,{signal:this.abortAllController.signal}).catch(Ea);return i?(t.log("success",ei({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ei({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ta(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var _,k;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let w=new URL(l,location.href);w.searchParams.append("bytes",`${r.from}-${r.to}`),l=w.toString();break}default:ny(t)}this.requestQuic&&(l=ya(l));let p=this.abortAllController.signal,h;if(n){let w=new ke;if(h=JM(oy(this.abortAllController.signal,"abort"),oy(n,"abort")).subscribe(()=>{try{w.abort()}catch(H){Ea(H)}}),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch(H){Ea(H)}p=w.signal}let f=Ia();c.log("startRequest",ei({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield dt(l,{priority:s,headers:d,signal:p}).catch(Ea),g=Ia();if(!b)return c.error("error",{message:"No response in request"}),c.end(),h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let w=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:w}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let w=Ia(),H={requestStartedAt:f,requestEndedAt:w,duration:w-f};return c.log("endRequest",ei(H)),c.end(),b.arrayBuffer()}let[v,S]=b.body.tee(),y=v.getReader();o&&((k=this.throughputEstimator)==null||k.trackStream(S,u));let E=0,I=new Uint8Array(0),R=!1,D=w=>{h==null||h.unsubscribe(),R=!0,Ea(w)},G=Ta(p,async function*({done:w,value:H}){if(E===0&&this.lastRequestFirstBytes$.next(Ia()-f),p.aborted){h==null||h.unsubscribe();return}if(!w&&H){let J=new Uint8Array(I.length+H.length);J.set(I),J.set(H,I.length),I=J,E+=H.byteLength,i==null||i(new DataView(I.buffer),E),yield y==null?void 0:y.read().then(G,D)}}.bind(this));yield y==null?void 0:y.read().then(G,D),h==null||h.unsubscribe();let $=Ia(),V={failed:R,requestStartedAt:f,requestEndedAt:$,duration:$-f};return R?(c.error("endRequest",ei(V)),c.end(),null):(c.log("endRequest",ei(V)),c.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ta(this.abortAllController.signal,async function*(e,t,r){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!c)return null;let p=new DataView(c,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ta(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=ay(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:ny(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ea=a=>{if(!va(a))throw a};var cr=(a,e,t)=>t*e+(1-t)*a,Ll=(a,e)=>a.reduce((t,r)=>t+r,0)/e,uy=(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 ZM,ValueSubject as ly}from"@vkontakte/videoplayer-shared";var Nt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ly(e.initial),this.debounced$=new ly(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new he(`raw_${t}`),this.smoothedSeries$=new he(`smoothed_${t}`),this.reportedSeries$=new he(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(ZM(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var pn=class extends Nt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=cr(this.slow,e,this.params.emaAlphaSlow),this.fast=cr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var hn=class extends Nt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ll(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cr(this.emaSmoothed,e,this.params.emaAlpha);let r=uy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var fn=class extends Nt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?cr(this.smoothed,t,this.params.emaAlpha):t}};var dr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new pn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new hn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new fn({initial:e,label:"liveEdgeDelay",...t})}};var Ml=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as eC,ValueSubject as tC}from"@vkontakte/videoplayer-shared";var xa=class a{constructor(e,t){this.currentRepresentation$=new tC(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(!eC(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(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Re(t.segmentReference))}};var lC=["timeupdate","progress","play","seeked","stalled","waiting"],cC=["timeupdate","progress","loadeddata","playing","seeked"];var bn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new hy;this.representationSubscription=new hy;this.state$=new M("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new py;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.liveDuration$=new K(0);this.liveAvailabilityStartTime$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.isLowLatency$=new K(!1);this.isActiveLowLatency$=new K(!1);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new py;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=Cl(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ce(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ft.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Cl(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ft.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=JS(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Gv(e))!=null?n:{id:"ManifestParsing",category:Ft.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,d)=>{var c,p,h,f;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,l)&&((f=(h=pt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${d}"`))||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 d=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),c=new Set(d.map(({codecs:h})=>h)),p=Ev(c);if(p&&(i[u]=d.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);aC.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",Aa(s)),s}.bind(this));this.initRepresentations=Cl(this.destroyController.signal,async function*(e,t,r){var p;this.tracer.log("initRepresentationsStart",Aa({initialVideo:e,initialAudio:t,sourceHls:r})),pr(this.manifest),pr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=h=>{this.representationSubscription.add(hr(h,"error").pipe(mn(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ft.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?nv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&zs())if(r){let h=document.createElement("source");i(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((h,f)=>[...h,...f.representations],[]);if(this.videoBufferManager=new Sa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],dy(t)){let h=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new Sa("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}xa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new xa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ol(1e3).subscribe(h=>{var f;if((f=this.element)!=null&&f.paused){let b=Vs(this.manifestUrlString,2);this.manifestUrlString=ce(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(fr(...cC.map(h=>hr(this.element,h))).pipe(wa(h=>this.element?tt(this.element.buffered,this.element.currentTime*1e3):0),Dl(),oC(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(fr(hr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Dl()).subscribe(f=>Ml(this.element,1))),this.representationSubscription.add(Pa({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(mn(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(Pa({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(mn(({isLive:f})=>f),wa(f=>({...f})),Dl((f,b)=>b.bufferLength<f.bufferLength),wa(({rtt:f,bufferLength:b,segmentServerLatency:g})=>{let v=Vs(this.manifestUrlString,2);return(f/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Pa({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=f-g,E=1;Math.abs(y)>v&&(E=1+Math.sign(y)*S),Ml(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,v;let b=0;if(f){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var I,R;return(R=(I=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?R:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let h=0;this.representationSubscription.add(Pa({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(uC(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:b})=>{if(pr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Vs(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,R=isFinite(f)?f:b,D=this.isActiveLowLatency$.getValue(),G=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(D&&G);let $="none";if(D?$="active_low_latency":this.isLowLatency$.getValue()&&G?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(V=>V.proceedLowLatencyLive()),$="active_low_latency"):v!==0&&R<y?$="live_forward_buffering":R<y+I&&($="live_with_target_offset"),isFinite(f)&&(h=f>h?f:h),$==="live_forward_buffering"||$==="live_with_target_offset"){let V=h-(y+E),_=this.normolizeLiveOffset(Math.trunc(v+V/g)),k=Math.abs(_-v),w;!f||k<=this.tuning.dashCmafLive.offsetCalculationError?w=v:_>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=_:w=0,this.manifestUrlString=ce(this.manifestUrlString,w,2)}$!=="none"&&$!=="active_low_latency"&&(h=0,this.updateLive())}))}let l=fr(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(wa(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=fr(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(wa(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add(fr(this.forceEnded$,Pa({allBuffersFull:l,someBufferEnded:d}).pipe(mn(({allBuffersFull:h,someBufferEnded:f})=>h&&f))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(h=this.source)==null||h.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ft.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(fr(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(h=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",h)}));let c=[(p=this.manifest.duration)!=null?p:0,...(0,Bl.default)((0,Bl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Re(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&dy(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Ol(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Ft.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new dn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=dr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;pr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ce(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){pr(this.element),this.state$.setState("running"),this.subscription.add(fr(...lC.map(e=>hr(this.element,e)),hr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ft.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(hr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(hr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Bt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,v,S,y,E,I,R;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=nC(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,d=(E=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?E:0,c=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let D=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(D),(R=this.audioBufferManager)==null||R.maintain(D),i.position=D}this.tracer.log("stallIntervalCallback",Aa(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Ol(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Ft.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u;pr(this.element),pr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Bt(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Aa({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=sC(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Aa(t)))}}};var gn=class{constructor(e,t){this.fov=e,this.orientation=t}};var vn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var fy=`attribute vec2 a_vertex;
69
70
  attribute vec2 a_texel;
70
71
 
71
72
  varying vec2 v_texel;
@@ -76,7 +77,7 @@ void main(void) {
76
77
  // save texel vector to pass to fragment shader
77
78
  v_texel = a_texel;
78
79
  }
79
- `;var fS=`#ifdef GL_ES
80
+ `;var my=`#ifdef GL_ES
80
81
  precision highp float;
81
82
  precision highp int;
82
83
  #else
@@ -119,6 +120,5 @@ void main(void) {
119
120
  // sample using new coordinates
120
121
  gl_FragColor = texture2D(u_texture, tc);
121
122
  }
122
- `;var rn=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new en(this.params.fov,this.params.orientation),this.cameraRotationManager=new tn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(hS,this.gl.VERTEX_SHADER),i=this.createShader(fS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,h=t+r;return[s,n,o,u,l,d,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as OR,now as mS,Subscription as _R,filter as NR,combine as bS,ValueSubject as gS,isNonNullable as FR}from"@vkontakte/videoplayer-shared";var ll=class{constructor(){this.isSeeked$=new gS(!1);this.isBuffering$=new gS(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new _R}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(bS({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(NR(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(bS({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:i})=>{if(OR(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:r,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),d=this.videoLastDataObtainedTimestamp$.getValue(),c=mS(),h=n&&this.currentStallsCount>=n,p=r&&!i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=r+u&&t>=r,f=s&&c-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&c-d>=s+u&&t>=s;(h||p||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,FR(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=mS(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},SS=ll;var ni=class{constructor(e){this.subscription=new zR;this.videoState=new L("stopped");this.elementSize$=new KR(void 0);this.textTracksManager=new Ve;this.droppedFramesManager=new Ms;this.stallsManager=new SS;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ar;this.audioTrackSwitchHistory=new Ar;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(r.position-l,r.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()):(i==null?void 0:i.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()):(i==null?void 0:i.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()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return HR(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new rn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.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=he(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(te(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 Zs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=be(this.video),r=this.constructor.name,s=o=>{e.error$.next({id:r,category:cl.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var d;let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(vS(c=>!!c.length),TS()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(dl(c=>c.to.state!=="none"),ba());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ba()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(vS(yS),TS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(dl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(me(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,r)),s(YR(this.video),this.elementSize$),s(Oe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),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 h=this.player.getStreams();if(jR(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let m of h.audio){f.push(Xu(m));let g=[];for(let v of m.representations){let S=Jg(v);g.push(S),this.audioTracksMap.set(S,{stream:m,representation:v})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(f)}let p=[];for(let f of h.video){p.push(Ju(f));let m=[];for(let g of f.representations){let v=Xg(g);v&&(m.push(v),this.videoTracksMap.set(v,{stream:f,representation:g}))}this.videoStreamsMap.set(f,m)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let f of h.text)for(let m of f.representations){let g=Zg(f,m);this.textTracksMap.set(g,{stream:f,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let o=c=>e.error$.next({id:"RepresentationSwitch",category:cl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(an(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,QR(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),h=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||h)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[f,m]=p,g=[...this.videoTracksMap.keys()].find(S=>{var T;return((T=this.videoTracksMap.get(S))==null?void 0:T.representation.id)===f.id});yS(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")this.player.initRepresentations(f.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",f.id).catch(o),m){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,S).catch(o)}},r)),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(ba()).subscribe(c=>{let h=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Ju(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ba()).subscribe(c=>{let h=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Xu(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var h,p;if(c!=null&&c.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),(d=this.textTracksManager)==null||d.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(dl(({to:c})=>c==="ready"),ba());this.subscription.add(an(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(an(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=an(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,WR(["init"])).pipe(GR(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,D,H,w,V,B,k,A,q,z,y,R,F;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=($=e.videoTrack.getState())==null?void 0:$.id,n=[...this.videoTracksMap.keys()].find(({id:C})=>C===r),o=t.currentVideoTrack$.getValue(),u=((w=(H=e.videoStream.getState())!=null?H:n&&((D=this.videoTracksMap.get(n))==null?void 0:D.stream))!=null?w:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:C})=>C===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=et(this.video.buffered,this.video.currentTime*1e3),h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(c/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,m=(B=[...this.audioStreamsMap.keys()].find(({id:C})=>C===(f==null?void 0:f.id)))!=null?B:this.audioStreamsMap.keys().next().value,g=0;if(m){if(n&&!i){let C=ks(n,d,(k=this.audioStreamsMap.get(m))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(A=C==null?void 0:C.bitrate)!=null?A:-1/0)}if(o){let C=ks(o,d,(q=this.audioStreamsMap.get(m))!=null?q:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(z=C==null?void 0:C.bitrate)!=null?z:-1/0)}}let v=At(d,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),S=i?v!=null?v:n:n!=null?n:v,T=m&&Rb(S,d,(y=this.audioStreamsMap.get(m))!=null?y:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(R=this.videoTracksMap.get(S))==null?void 0:R.representation,I=T&&((F=this.audioTracksMap.get(T))==null?void 0:F.representation);if(E&&I)return[E,I];if(E&&!I&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ge(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:cl.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),fe(this.video),this.tracer.end()}};var ga=class extends ni{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as IS,interval as XR,map as ES}from"@vkontakte/videoplayer-shared";var Sa=class extends ni{constructor(e){super(e),this.liveOffset=new ot,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,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(i.isLowLatency.stateChangeEnded$.pipe(ES(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(IS({interval:XR(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(IS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ES(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=eS(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,r)})}};var PS=Ue(Ps(),1);import{assertNever as va,assertNonNullable as xS,debounce as JR,ErrorCategory as sn,filter as ZR,isNonNullable as e$,isNullable as t$,map as nn,merge as i$,Observable as r$,observableFrom as a$,Subscription as s$,videoSizeToQuality as n$}from"@vkontakte/videoplayer-shared";var Ye={};var Hi=(a,e)=>new r$(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),ya=class{constructor(e){this.subscription=new s$;this.videoState=new L("initializing");this.textTracksManager=new Ve;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:va(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:va(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:va(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:va(e)}break;default:va(t)}};this.video=he(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(te(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),fe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:sn.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,PS.default)(import("hls.js").then(r=>{e||(Ye.Hls=r.default,Ye.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){xS(Ye.Hls,"hls.js not loaded"),this.hls=new Ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){xS(Ye.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:sn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=be(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Je(this.video,e.isLooped,i)),this.subscription.add(me(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,e.playbackRate,r.playbackRateState$,i)),s(Oe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(nn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Hi(this.hls,Ye.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:sn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Hi(this.hls,Ye.Events.MANIFEST_PARSED).pipe(nn(({levels:l})=>l.reduce((d,c)=>{var S,T;let h=c.name||c.height.toString(10),{width:p,height:f}=c,m=(T=xt((S=c.attrs.QUALITY)!=null?S:""))!=null?T:n$({width:p,height:f});if(!m)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:m,bitrate:c.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),s(Hi(this.hls,Ye.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let h=c.name,p=c.attrs.URI||"",f=c.lang;d.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Hi(this.hls,Ye.Events.LEVEL_LOADING).pipe(nn(({url:l})=>te(l))),t.hostname$),s(Hi(this.hls,Ye.Events.FRAG_CHANGED),l=>{var h,p,f,m;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=d==null?void 0:d.endPTS)!=null?h:0)-((p=d==null?void 0:d.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((m=c==null?void 0:c.startPTS)!=null?m:0))*1e3)}),this.subscription.add(Tt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=Hi(this.hls,Ye.Events.LEVEL_SWITCHED).pipe(nn(({level:l})=>n(this.hls.levels[l])));o.pipe(ZR(e$)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Tt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(t$(l))return;let d=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!d)return;let c=this.hls.levels.indexOf(d),h=this.hls.currentLevel,p=this.hls.levels[h];!p||d.bitrate>p.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),s(r.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$,a$(["init"])).pipe(JR(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sn.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 AS="X-Playback-Duration",pl=async a=>{var r;let e=await Qe(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(AS)?parseInt(e.headers.get(AS),10):void 0};import{assertNever as S$,combine as v$,debounce as y$,ErrorCategory as ln,filter as T$,filterChanged as I$,isNonNullable as RS,isNullable as cn,map as $S,merge as E$,observableFrom as x$,Subscription as P$,ValueSubject as ml,VideoQuality as A$}from"@vkontakte/videoplayer-shared";var fl=Ue(ko(),1);import{videoSizeToQuality as o$,getExponentialDelay as u$}from"@vkontakte/videoplayer-shared";var l$=a=>{let e=null;if(a.QUALITY&&(e=xt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=o$({width:t,height:i})}return e!=null?e:null},c$=(a,e)=>{var s,n;let t=a.split(`
123
- `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,fl.default)(l[1].split(",").map(S=>S.split("="))),h=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,p=l$(c),f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[S,T]=c.RESOLUTION.split("x").map(E=>parseInt(E,10));S&&T&&(g={width:S,height:T})}let v=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:v,bandwidth:f,size:g,fps:m})}if(d){let c=(0,fl.default)(d[1].split(",").map(m=>{let g=m.indexOf("=");return[m.substring(0,g),m.substring(g+1)]}).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,f=c.NAME;h&&p&&r.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},d$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),hl=0,wS=async(a,e=a,t,i)=>{let s=await(await Qe(a,i)).text();hl+=1;try{let{qualityManifests:n,textTracks:o}=c$(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(hl<=t.manifestRetryMaxCount)return await d$(u$(hl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),wS(a,e,t)}return{qualityManifests:[],textTracks:[]}},on=wS;import{isNonNullable as p$,Subscription as h$,throttle as f$,ValueSubject as kS,Logger as m$,Subject as b$,ErrorCategory as g$}from"@vkontakte/videoplayer-shared";var un=class{constructor(e,t,i,r){this.subscription=new h$;this.abortControllers={destroy:new ne,nextManifest:null};this.numberFormat=new Intl.NumberFormat("ru-RU",{maximumFractionDigits:2,minimumFractionDigits:2,useGrouping:!0});this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new kS(null);this.getCurrentTime$=new kS(null);this.error$=new b$;this.logger=new m$,this.log=this.logger.createComponentLog("LiveTextManager"),this.params={fetchManifestData:i,sourceUrl:r},this.subscription.add(e.pipe(f$(1e3)).subscribe(s=>{this.processLiveTime(s)})).add(this.logger.log$.subscribe(s=>{console.debug(`%c${s.component}`,"background:#258b6d;",s.message)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString();this.log({message:"[parseTextTracks]"}),this.log({message:r});let n=await(await Qe(r,{signal:this.abortControllers.destroy.signal})).text();this.log({message:n});let o=this.parsePlaylist(n,r);return this.log({message:JSON.stringify(o,void 0,2)}),{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
124
- `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(p$(e)&&this.currentTextTrackData){this.log({message:`[processLiveTime] ${e.toFixed(2)}, ${new Date(e).toISOString()}`});let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i){this.log({message:`[processLiveTime] out of bounds (before) ! ${i-e}`});return}if(e>r){this.log({message:`[processLiveTime] out of bounds (after) !' ${e-r}`});return}let s=r-e;this.log({message:`Current segments time left: ${this.numberFormat.format(s)} ms`}),s<4e3&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ne;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:g$.WTF,thrown:t,message:e})}};var Ta=class{constructor(e){this.subscription=new P$;this.videoState=new L("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ml([]);this.liveOffset=new ot;this.manifestStartTime$=new ml(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return S$(t)}};var i;this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:A$.INVARIANT,url:this.params.source.url};let t=(r,s)=>on(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new un(this.params.output.liveTime$,this.video,t,this.params.source.url):this.textTracksManager=new Ve,t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ln.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:ln.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(te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ml((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:ln.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=be(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(me(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,i)),s(Oe(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(I$(),$S(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&RS(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(te(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(v$({startTime:this.manifestStartTime$.pipe(T$(RS)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe($S(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=E$(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,x$(["init"])).pipe(y$(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(cn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),pl(n).then(d=>{var c;if(!cn(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(cn(h)||!isFinite(h))&&Qe(n).then(p=>p.text()).then(p=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();pl(g).then(v=>{cn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){ge(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:ln.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=se(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as w$,debounce as k$,ErrorCategory as bl,fromEvent as gl,isNonNullable as R$,isNullable as $$,map as LS,merge as MS,observableFrom as DS,Subscription as L$,ValueSubject as M$,VideoQuality as D$,clientChecker as C$}from"@vkontakte/videoplayer-shared";var Ia=class{constructor(e){this.subscription=new L$;this.videoState=new L("stopped");this.textTracksManager=new Ve;this.manifests$=new M$([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return w$(t)}};this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:D$.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(te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),on(se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:bl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:bl.WTF,message:"HlsProvider internal logic error",thrown:o})},r=be(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(LS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,i)),this.subscription.add(me(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&R$(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(te(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(LS(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!C$.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(MS(gl(o,"addtrack"),gl(o,"removetrack"),gl(o,"change"),DS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=MS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,DS(["init"])).pipe(k$(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){var s,n;let e=this.selectManifest();if($$(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){ge(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:bl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as V$,assertNonNullable as CS,debounce as B$,ErrorCategory as VS,isHigher as O$,isHigherOrEqual as _$,isInvariantQuality as BS,isLowerOrEqual as N$,isNonNullable as F$,merge as U$,observableFrom as q$,Subscription as H$,map as j$}from"@vkontakte/videoplayer-shared";var Ea=class{constructor(e){this.subscription=new H$;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Ve;this.syncPlayback=()=>{var u,l,d;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((d=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:d.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.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()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return V$(e)}};this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),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,i=o=>{e.error$.next({id:"MpegProvider",category:VS.WTF,message:"MpegProvider internal logic error",thrown:o})},r=be(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(j$(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,i)),this.subscription.add(me(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,i)),s(Oe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.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&&F$(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=U$(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,q$(["init"])).pipe(B$(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),fe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;CS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];CS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=la(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(te(t))}playIfAllowed(){ge(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 r,s,n,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(s=Object.values(this.trackUrls).find(c=>!BS(c.track.quality)&&N$(c.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,d=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&d&&_$(d.quality,u.quality)&&(t=u),!t){let c=Object.values(this.trackUrls).filter(p=>!BS(p.track.quality)&&O$(p.track.quality,e)),h=c.length;h&&(t=c[h-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=At(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as _S,debounce as Y$,merge as NS,observableFrom as z$,Subscription as K$,map as FS,ValueSubject as X$,ErrorCategory as vl,VideoQuality as J$}from"@vkontakte/videoplayer-shared";import{ErrorCategory as G$}from"@vkontakte/videoplayer-shared";var OS=["stun:videostun.mycdn.me:80"],Q$=1e3,W$=3,Sl=()=>null,dn=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=Sl;this.externalStopCallback=Sl;this.externalErrorCallback=Sl;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:OS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:G$.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(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),Q$)}normalizeOptions(e={}){let t={stunServerList:OS,maxRetryNumber:W$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var xa=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new X$(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return _S(e)}};this.subscription=new K$,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=he(e.container,e.tuning),this.liveStreamClient=new dn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:vl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};NS(this.videoState.stateChangeStarted$.pipe(FS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(FS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let r=be(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),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(Oe(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(me(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return _S(n.to)}},i)).add(NS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,z$(["init"])).pipe(Y$(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(te(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:J$.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:vl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ge(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:vl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Pa=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 wa,assertNonNullable as Mt,ErrorCategory as pn,filter as QS,isNonNullable as WS,isNullable as nL,map as oL,merge as uL,once as lL,Subject as ye,Subscription as YS,ValueSubject as M,flattenObject as zS}from"@vkontakte/videoplayer-shared";import{Observable as Z$,map as US,Subscription as eL,Subject as tL}from"@vkontakte/videoplayer-shared";var qS=a=>new Z$(e=>{let t=new eL,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(US(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(US(({type:l})=>l!==void 0)),n=new tL,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.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 iL,Subscription as rL,combine as aL,filter as jS,once as GS}from"@vkontakte/videoplayer-shared";function HS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as sL}from"@vkontakte/videoplayer-shared";var Aa=class Aa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ne;this.subscriptions=new rL;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(jS(s=>!!s.type),GS()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){sL.isSafari&&e!=="MPEG"||this.subscriptions.add(aL({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(jS(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),GS()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=HS();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!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:Aa.errorId,category:iL.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Aa.errorId} exception`,thrown:e})}};Aa.errorId="VolumeMultiplierManager";var ji=Aa;var cL={chunkDuration:5e3,maxParallelRequests:5},ka=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ye;this.noAvailableProvidersError$=new ye;this.volumeMultiplierError$=new ye;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new ye,warning$:new ye,willSeekEvent$:new ye,soundProhibitedEvent$:new ye,seekedEvent$:new ye,loopedEvent$:new ye,endedEvent$:new ye,firstBytesEvent$:new ye,loadedMetadataEvent$:new ye,firstFrameEvent$:new ye,canplay$:new ye,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M(""),getCurrentTime$:new M(null)};this.subscription=new YS;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=rg([...sg(this.params.tuning),...ag(this.params.tuning)],this.params.tuning).filter(l=>WS(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",zS(s)),this.screenFormatsIterator=new Pa(s);let n=[...Cu(!0),...Cu(!1)];this.chromecastFormatsIterator=new Pa(n.filter(l=>WS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ji.isSupported()&&(this.volumeMultiplierManager=new ji(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(nL(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:pn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return wa(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:r,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 Mt(o),new ga({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Sa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Mt(o),_i||!this.params.tuning.useHlsJs?new Ia({...n,source:o}):new ya({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Ta({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Ea({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Fb({...n,source:o,config:{...cL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new xa({container:i,source:o,desiredState:r,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 wa(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Mt(o),new Ir({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,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 wa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return wa(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 wa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,KS.default)(Object.entries(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new YS,t=!1,i=0;return e.add(uL(this.providerOutput.error$.pipe(QS(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),qS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(oL(r=>({id:`ProviderHangup:${r}`,category:pn.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(QS(({to:s})=>s==="playing"),lL()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===pn.NETWORK,u=r.category===pn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",zS(n))})),e}};import{fromEvent as hn,once as dL,combine as pL,Subscription as XS,ValueSubject as yl,map as hL,filter as fL,isNonNullable as fn,now as ke,safeStorage as Tl}from"@vkontakte/videoplayer-shared";var mL=5e3,JS="one_video_throughput",ZS="one_video_rtt",dt=window.navigator.connection,ev=()=>{let a=dt==null?void 0:dt.downlink;if(fn(a)&&a!==10)return a*1e3},tv=()=>{let a=dt==null?void 0:dt.rtt;if(fn(a)&&a!==3e3)return a},iv=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Il=class a{constructor(e){this.subscription=new XS;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(JS)||(e.useBrowserEstimation?ev():void 0)||mL,i=(s=(r=a.load(ZS))!=null?r:e.useBrowserEstimation?tv():void 0)!=null?s:0;if(this.throughput$=new yl(t),this.rtt$=new yl(i),this.rttAdjustedThroughput$=new yl(iv(t,i,e.rttPenaltyRequestSize)),this.throughput=ii.getSmoothedValue(t,-1,e),this.rtt=ii.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=ev();u&&this.throughput.next(u);let l=tv();fn(l)&&this.rtt.next(l)};dt&&"onchange"in dt&&this.subscription.add(hn(dt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Tl.set(JS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Tl.set(ZS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(pL({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(hL(({throughput:n,rtt:o})=>iv(n,o,e.rttPenaltyRequestSize)),fL(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,i=ke(),r=new XS;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(hn(e,"progress").pipe(dL()).subscribe(s=>{t=s.loaded,i=ke()}));break;case 1:case 0:r.add(hn(e,"loadstart").subscribe(()=>{t=0,i=ke()}));break}r.add(hn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ke(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=ke(),n=0,o=ke(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,ke()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=ke();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,s=ke()}else n+=c.byteLength;o=ke()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ke()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ke()-o,this.concurrentDownloads.size),n=0,o=ke());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=Tl.get(e);if(fn(t))return(i=parseInt(t,10))!=null?i:void 0}},rv=Il;import{fillWithDefault as bL,VideoQuality as av}from"@vkontakte/videoplayer-shared";var sv={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,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:av.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:av.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,shortVideoBufferStallSize:0,longVideoBufferStallSize:0},qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,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,useHlsLiveNewTextManager:!1},nv=a=>{var e;return{...bL(a,sv),configName:[...(e=a.configName)!=null?e:[],...sv.configName]}};import{assertNonNullable as mn,combine as Dt,ErrorCategory as bn,filter as ce,filterChanged as N,fromEvent as xl,isNonNullable as EL,isNullable as xL,Logger as PL,map as O,mapTo as cv,merge as Ct,now as gn,once as tt,Subject as j,Subscription as dv,tap as pv,ValueSubject as P,isHigher as AL,isInvariantQuality as hv,flattenObject as Vt,throttle as Pl,getTraceSubscriptionMethod as fv,Tracer as wL}from"@vkontakte/videoplayer-shared";import{merge as gL,map as SL,filter as ov,isNonNullable as vL}from"@vkontakte/videoplayer-shared";var El=({seekState:a,position$:e})=>gL(a.stateChangeEnded$.pipe(SL(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),ov(vL)),e.pipe(ov(()=>a.getState().state==="none")));import{assertNonNullable as yL}from"@vkontakte/videoplayer-shared";var uv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return yL(e,`Wrong container or containerId {${a.container}}`),e};import{filter as TL,once as IL}from"@vkontakte/videoplayer-shared";var lv=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(TL(r=>r.length>0),IL()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var Sn=class{constructor(e={configName:[]},t=wL.createRootTracer(!1)){this.subscription=new dv;this.logger=new PL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),isLowLatency:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,autoplaySoundProhibited$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:yb,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=nv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ja({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new rv(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:bn.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var r,s,n;this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",Vt(i)),this.domContainer=uv(e),this.chromecastInitializer.contentId=(r=e.meta)==null?void 0:r.videoId,this.providerContainer=new ka({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),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&&!Lr()?(this.tracer.log("request play from hidden tab"),xl(document,"visibilitychange").pipe(tt()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;return e>=i&&!r&&(s=i-.1),this.tracer.log("seekTime",{duration:i,isLive:r,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){mn(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(ce(i=>i.length>0),tt()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Vt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;mn(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.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",Vt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return lv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.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(xL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return EL(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ce(({from:e})=>e==="stopped"),tt()).subscribe(()=>{this.initedAt=gn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Vt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:bn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(tt()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Vt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(O(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(O(n=>n.destination),N()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(O(n=>n.map(({quality:o})=>o).sort((o,u)=>hv(o)?1:hv(u)?-1:AL(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(N()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(N()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(N()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(N()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(O(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Dt({hasLiveOffsetByPaused:Ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(n=>n.to),N(),O(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Dt({atLiveEdge:Dt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:El({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(O(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),N(),pv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(O(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Dt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(O(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),N(),pv(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(O(n=>n.muted),N()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(O(n=>n.volume),N()).subscribe(this.info.volume$)).add(El({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ct(e.providerOutput.endedEvent$.pipe(cv(!0)),e.providerOutput.seekedEvent$.pipe(cv(!1))).pipe(N()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(O(n=>({id:n?`No${n}`:"NoProviders",category:bn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(tt(),O(n=>n!=null?n:gn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(tt(),O(()=>gn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(tt(),O(()=>gn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new P(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ce(({to:n})=>n==="playing"),tt()).subscribe(()=>i.next(!1)));let r=0,s=Ct(e.providerOutput.isBuffering$,t,i).pipe(O(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),N());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ct(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(Ct(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(O(e=>e==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 dv;this.subscription.add(t),this.subscription.add(e.current$.pipe(N((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ce(i=>i.length>0),tt()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r,s;let t;this.wasSetStartedQuality=!0;let i=(s=this.explicitInitialQuality)!=null?s:(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:n})=>n===i),t||this.setAutoQuality(!0)),t||(t=At(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Ct(this.desiredState.videoTrack.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(O(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;mn(this.providerContainer),mn(e),vb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Sb(i)),this.providerContainer.current$.subscribe(({type:i})=>Pr("provider",i)),e.duration$.subscribe(i=>Pr("duration",i)),e.availableVideoTracks$.pipe(ce(i=>!!i.length),tt()).subscribe(i=>Pr("tracks",i)),this.events.fatalError$.subscribe(new le("fatalError")),this.events.managedError$.subscribe(new le("managedError")),e.position$.subscribe(new le("position")),e.currentVideoTrack$.pipe(O(i=>i==null?void 0:i.quality)).subscribe(new le("quality")),this.info.currentBuffer$.subscribe(new le("buffer")),e.isBuffering$.subscribe(new le("isBuffering"))].forEach(i=>this.subscription.add(i)),Pr("codecs",ig())}initTracerSubscription(){let e=fv(this.tracer.log.bind(this.tracer)),t=fv(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(N()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Dt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ce(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),N((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ce(i=>i>0),N()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ce(i=>i>0),N()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Dt({currentBuffer:this.info.currentBuffer$.pipe(ce(i=>i.end>0),N((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(N())}).pipe(Pl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(N()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(N()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(N()).subscribe(e("canChangePlaybackSpeed"))).add(Dt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ce(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Pl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(N(),ce(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(N(),ce(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(N()).subscribe(e("muted"))).add(this.info.volume$.pipe(N()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(N(),ce(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Dt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ce(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Pl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(N(),ce(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:bn.DOM,message:String(r)})})};this.subscription.add(Ct(xl(document,"visibilitychange"),xl(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Vt({quality:t,availableTracks:Vt(e),track:Vt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as t2,Observable as i2,Subject as r2,ValueSubject as a2,VideoQuality as s2}from"@vkontakte/videoplayer-shared";var n2=`@vkontakte/videoplayer-core@${nc}`;export{qa as ChromecastState,xn as HttpConnectionType,i2 as Observable,de as PlaybackState,Sn as Player,n2 as SDK_VERSION,r2 as Subject,t2 as Subscription,Pn as Surface,nc as VERSION,a2 as ValueSubject,vt as VideoFormat,s2 as VideoQuality};
123
+ `;var Sn=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 gn(this.params.fov,this.params.orientation),this.cameraRotationManager=new vn(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(fy,this.gl.VERTEX_SHADER),r=this.createShader(my,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,d=t+i,c=e-r,p=t+i;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as hC,now as by,Subscription as fC,filter as mC,combine as gy,ValueSubject as vy,isNonNullable as bC}from"@vkontakte/videoplayer-shared";var Vl=class{constructor(){this.isSeeked$=new vy(!1);this.isBuffering$=new vy(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new fC}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(gy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(mC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(gy({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(hC(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),d=this.videoLastDataObtainedTimestamp$.getValue(),c=by(),p=n&&this.currentStallsCount>=n,h=i&&!r&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,f=s&&c-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&c-d>=s+u&&t>=s;(p||h||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,bC(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=by(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Sy=Vl;var mr=class{constructor(e){this.subscription=new PC;this.videoState=new M("stopped");this.elementSize$=new AC(void 0);this.textTracksManager=new Oe;this.droppedFramesManager=new Gs;this.stallsManager=new Sy;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Bi;this.audioTrackSwitchHistory=new Bi;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 SC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Sn(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(ie(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new bn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Se(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:_l.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var d;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(yy(c=>!!c.length),Iy()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Nl(c=>c.to.state!=="none"),Ra());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ra()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(yy(Ty),Iy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Nl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ze(this.video,t.isLooped,i)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(xC(this.video),this.elementSize$),s(Ve(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if(yC(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(Pl(b));let g=[];for(let v of b.representations){let S=ZS(v);g.push(S),this.audioTracksMap.set(S,{stream:b,representation:v})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let h=[];for(let f of p.video){h.push(Al(f));let b=[];for(let g of f.representations){let v=XS({...g,streamId:f.id});v&&(b.push(v),this.videoTracksMap.set(v,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let f of p.text)for(let b of f.representations){let g=ey(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:_l.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(yn(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,IC(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(!(0,Ey.default)(["manifest_ready","running"],c)||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,b]=h,g=[...this.videoTracksMap.keys()].find(S=>{var y;return((y=this.videoTracksMap.get(S))==null?void 0:y.representation.id)===f.id});Ty(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")this.player.initRepresentations(f.id,b==null?void 0:b.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",f.id).catch(o),b){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",b.id,S).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ra()).subscribe(c=>{let p=[...(0,Fl.default)(this.videoTracksMap)].find(([,{representation:g}])=>g.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=p,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Al(f))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ra()).subscribe(c=>{let p=[...(0,Fl.default)(this.audioTracksMap)].find(([,{representation:g}])=>g.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Pl(f))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}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)),(d=this.textTracksManager)==null||d.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(Nl(({to:c})=>c==="ready"),Ra());this.subscription.add(yn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(yn(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=yn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,EC(["init"])).pipe(TC(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var R,D,G,$,V,_,k,w,H,J,A,T,B;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(R=e.videoTrack.getState())==null?void 0:R.id,n=[...this.videoTracksMap.keys()].find(({id:C})=>C===i),o=t.currentVideoTrack$.getValue(),u=(($=(G=e.videoStream.getState())!=null?G:n&&((D=this.videoTracksMap.get(n))==null?void 0:D.stream))!=null?$:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:C})=>C===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=tt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(V=e.audioStream.getState())!=null?V:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(_=[...this.audioStreamsMap.keys()].find(({id:C})=>C===(f==null?void 0:f.id)))!=null?_:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let C=qs(n,d,(k=this.audioStreamsMap.get(b))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(w=C==null?void 0:C.bitrate)!=null?w:-1/0)}if(o){let C=qs(o,d,(H=this.audioStreamsMap.get(b))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(J=C==null?void 0:C.bitrate)!=null?J:-1/0)}}let v=Ot(d,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),S=r?v!=null?v:n:n!=null?n:v,y=b&&Eg(S,d,(A=this.audioStreamsMap.get(b))!=null?A:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(T=this.videoTracksMap.get(S))==null?void 0:T.representation,I=y&&((B=this.audioTracksMap.get(y))==null?void 0:B.representation);if(E&&I)return[E,I];if(E&&!I&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_l.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.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 $a=class extends mr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as xy,interval as wC,map as Py}from"@vkontakte/videoplayer-shared";var La=class extends mr{constructor(e){super(e),this.liveOffset=new lt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(Py(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(xy({interval:wC(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(xy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Py(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=ty(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var wy=L(Bs(),1),ky=L(ut(),1);import{assertNever as Ma,assertNonNullable as Ay,debounce as kC,ErrorCategory as Tn,filter as RC,isNonNullable as $C,isNullable as LC,map as In,merge as MC,Observable as CC,observableFrom as DC,Subscription as OC,videoSizeToQuality as BC}from"@vkontakte/videoplayer-shared";var We={};var ti=(a,e)=>new CC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ca=class{constructor(e){this.subscription=new OC;this.videoState=new M("initializing");this.textTracksManager=new Oe;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ma(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ma(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ma(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ma(e)}break;default:Ma(t)}};this.video=be(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ge(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Tn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,wy.default)(import("hls.js").then(i=>{e||(We.Hls=i.default,We.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Ay(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Ay(We.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Tn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Se(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(Ze(this.video,e.isLooped,r)),this.subscription.add(ve(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(De(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ve(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(In(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ti(this.hls,We.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Tn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.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(ti(this.hls,We.Events.MANIFEST_PARSED).pipe(In(({levels:l})=>l.reduce((d,c)=>{var S,y;let p=c.name||c.height.toString(10),{width:h,height:f}=c,b=(y=Ct((S=c.attrs.QUALITY)!=null?S:""))!=null?y:BC({width:h,height:f});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),s(ti(this.hls,We.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,h=c.attrs.URI||"",f=c.lang;d.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(ti(this.hls,We.Events.LEVEL_LOADING).pipe(In(({url:l})=>ie(l))),t.hostname$),s(ti(this.hls,We.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=d==null?void 0:d.endPTS)!=null?p:0)-((h=d==null?void 0:d.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((b=c==null?void 0:c.startPTS)!=null?b:0))*1e3)}),this.subscription.add($t(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var d;return(d=Array.from((0,ky.default)(this.trackLevels)).find(({level:c})=>c===l))==null?void 0:d.track},o=ti(this.hls,We.Events.LEVEL_SWITCHED).pipe(In(({level:l})=>n(this.hls.levels[l])));o.pipe(RC($C)).subscribe(t.currentVideoTrack$,r),this.subscription.add($t(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(LC(l))return;let d=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{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=MC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,DC(["init"])).pipe(kC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tn.DOM,thrown:t}))||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0)}};var Ry="X-Playback-Duration",ql=async a=>{var i;let e=await dt(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Ry)?parseInt(e.headers.get(Ry),10):void 0};import{assertNever as UC,combine as HC,debounce as jC,ErrorCategory as xn,filter as GC,filterChanged as QC,isNonNullable as Ly,isNullable as Pn,map as My,merge as WC,observableFrom as YC,Subscription as zC,ValueSubject as jl,VideoQuality as KC}from"@vkontakte/videoplayer-shared";var Hl=L(Wo(),1);import{videoSizeToQuality as VC,getExponentialDelay as _C}from"@vkontakte/videoplayer-shared";var NC=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=VC({width:t,height:r})}return e!=null?e:null},FC=(a,e)=>{var s,n;let t=a.split(`
124
+ `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,Hl.default)(Object,l[1].split(",").map(S=>S.split("="))),p=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,h=NC(c),f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[S,y]=c.RESOLUTION.split("x").map(E=>parseInt(E,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(d){let c=(0,Hl.default)(Object,d[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,f=c.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},qC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Ul=0,$y=async(a,e=a,t)=>{let i=await(await dt(a)).text();Ul+=1;try{let{qualityManifests:s,textTracks:n}=FC(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(Ul<=t.manifestRetryMaxCount)return await qC(_C(Ul-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),$y(a,e,t)}return{qualityManifests:[],textTracks:[]}},En=$y;var Da=class{constructor(e){this.subscription=new zC;this.videoState=new M("stopped");this.textTracksManager=new Oe;this.manifests$=new jl([]);this.liveOffset=new lt;this.manifestStartTime$=new jl(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return UC(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:KC.INVARIANT,url:this.params.source.url},En(ce(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:xn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:xn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new jl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(c=(d=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:xn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Se(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(QC(),My(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Ly(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ie(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(HC({startTime:this.manifestStartTime$.pipe(GC(Ly)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(My(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));let n=WC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,YC(["init"])).pipe(jC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Pn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[c,p]of[[l,"mq"],[d,"lq"]]){let h=String(parseFloat(c||""));p&&c&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ce(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ql(n).then(l=>{var d;if(!Pn(l))this.maxSeekBackTime$.next(l);else{let c=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();if(Pn(c)||!isFinite(c))try{dt(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();ql(b).then(g=>{Pn(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as JC,debounce as XC,ErrorCategory as Gl,fromEvent as Ql,isNonNullable as ZC,isNullable as e0,map as Cy,merge as Dy,observableFrom as Oy,Subscription as t0,ValueSubject as r0,VideoQuality as i0,clientChecker as a0}from"@vkontakte/videoplayer-shared";var Oa=class{constructor(e){this.subscription=new t0;this.videoState=new M("stopped");this.textTracksManager=new Oe;this.manifests$=new r0([]);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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((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 JC(t)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:i0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),En(ce(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Gl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(c=(d=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Gl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Se(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Cy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ze(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&ZC(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===f);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(ie(b.url)))}let c=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(c!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Cy(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!a0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Dy(Ql(o,"addtrack"),Ql(o,"removetrack"),Ql(o,"change"),Oy(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Dy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Oy(["init"])).pipe(XC(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(e0(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,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&i.searchParams.set(d,c)}}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:Gl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Ny=L(kt(),1),Ba=L(ut(),1);import{assertNever as s0,assertNonNullable as By,debounce as n0,ErrorCategory as Vy,isHigher as o0,isHigherOrEqual as u0,isInvariantQuality as _y,isLowerOrEqual as l0,isNonNullable as c0,merge as d0,observableFrom as p0,Subscription as h0,map as f0}from"@vkontakte/videoplayer-shared";var Va=class{constructor(e){this.subscription=new h0;this.videoState=new M("stopped");this.trackUrls={};this.textTracksManager=new Oe;this.syncPlayback=()=>{var u,l,d;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:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((d=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:d.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 s0(e)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Ny.default)(Object,this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ba.default)(Object,this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:Vy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Se(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(f0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ze(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&c0(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=d0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,p0(["init"])).pipe(n0(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;By(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];By(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ya(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ie(t))}playIfAllowed(){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:Vy.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Ba.default)(Object,this.trackUrls).find(c=>!_y(c.track.quality)&&l0(c.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,d=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&d&&u0(d.quality,u.quality)&&(t=u),!t){let c=(0,Ba.default)(Object,this.trackUrls).filter(h=>!_y(h.track.quality)&&o0(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Ba.default)(Object,this.trackUrls).map(l=>l.track);t=Ot(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as qy,debounce as v0,merge as Uy,observableFrom as S0,Subscription as y0,map as Hy,ValueSubject as T0,ErrorCategory as Yl,VideoQuality as I0}from"@vkontakte/videoplayer-shared";import{ErrorCategory as m0}from"@vkontakte/videoplayer-shared";var Fy=["stun:videostun.mycdn.me:80"],b0=1e3,g0=3,Wl=()=>null,An=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Wl;this.externalStopCallback=Wl;this.externalErrorCallback=Wl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Fy}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:m0.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),b0)}normalizeOptions(e={}){let t={stunServerList:Fy,maxRetryNumber:g0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var _a=class{constructor(e){this.videoState=new M("stopped");this.maxSeekBackTime$=new T0(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 qy(e)}};this.subscription=new y0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=be(e.container,e.tuning),this.liveStreamClient=new An(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Yl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Uy(this.videoState.stateChangeStarted$.pipe(Hy(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Hy(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Se(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Ve(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ve(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return qy(n.to)}},r)).add(Uy(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,S0(["init"])).pipe(v0(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:I0.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:Yl.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:Yl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Na=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as qa,assertNonNullable as qt,ErrorCategory as wn,filter as zy,isNonNullable as Ky,isNullable as $0,map as L0,merge as M0,once as C0,Subject as Ee,Subscription as Jy,ValueSubject as O,flattenObject as Xy}from"@vkontakte/videoplayer-shared";import{Observable as E0,map as jy,Subscription as x0,Subject as P0}from"@vkontakte/videoplayer-shared";var Gy=a=>new E0(e=>{let t=new x0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(jy(({from:l,to:d})=>`${l}-${d}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(jy(({type:l})=>l!==void 0)),n=new P0,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 A0,Subscription as w0,combine as k0,filter as Wy,once as Yy}from"@vkontakte/videoplayer-shared";function Qy(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as R0}from"@vkontakte/videoplayer-shared";var Fa=class Fa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ke;this.subscriptions=new w0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Wy(s=>!!s.type),Yy()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){R0.isSafari&&e!=="MPEG"||this.subscriptions.add(k0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Wy(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),Yy()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=Qy();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Fa.errorId,category:A0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Fa.errorId} exception`,thrown:e})}};Fa.errorId="VolumeMultiplierManager";var ri=Fa;var D0={chunkDuration:5e3,maxParallelRequests:5},Ua=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),liveLatency$: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 Jy;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=yv([...Iv(this.params.tuning),...Tv(this.params.tuning)],this.params.tuning).filter(l=>Ky(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,zl.default)(i,l)),...t.filter(l=>(0,zl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Xy(s)),this.screenFormatsIterator=new Na(s);let n=[...al(!0),...al(!1)];this.chromecastFormatsIterator=new Na(n.filter(l=>Ky(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ri.isSupported()&&(this.volumeMultiplierManager=new ri(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($0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:wn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return qa(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qt(o),new $a({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return qt(o),new La({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return qt(o),zr||!this.params.tuning.useHlsJs?new Oa({...n,source:o}):new Ca({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return qt(o),new Da({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return qt(o),new Va({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return qt(o),new _g({...n,source:o,config:{...D0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return qt(o),new _a({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return qa(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return qt(o),new Mi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return qa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return qa(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return qa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,eT.default)(Object,(0,Zy.default)(Object,e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new Jy,t=!1,r=0;return e.add(M0(this.providerOutput.error$.pipe(zy(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),Gy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(L0(i=>({id:`ProviderHangup:${i}`,category:wn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(zy(({to:s})=>s==="playing"),C0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===wn.NETWORK,u=i.category===wn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(r++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",Xy(n))})),e}};import{fromEvent as kn,once as O0,combine as B0,Subscription as tT,ValueSubject as Kl,map as V0,filter as _0,isNonNullable as Rn,now as $e,safeStorage as Jl}from"@vkontakte/videoplayer-shared";var N0=5e3,rT="one_video_throughput",iT="one_video_rtt",mt=window.navigator.connection,aT=()=>{let a=mt==null?void 0:mt.downlink;if(Rn(a)&&a!==10)return a*1e3},sT=()=>{let a=mt==null?void 0:mt.rtt;if(Rn(a)&&a!==3e3)return a},nT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Xl=class a{constructor(e){this.subscription=new tT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(rT)||(e.useBrowserEstimation?aT():void 0)||N0,r=(s=(i=a.load(iT))!=null?i:e.useBrowserEstimation?sT():void 0)!=null?s:0;if(this.throughput$=new Kl(t),this.rtt$=new Kl(r),this.rttAdjustedThroughput$=new Kl(nT(t,r,e.rttPenaltyRequestSize)),this.throughput=dr.getSmoothedValue(t,-1,e),this.rtt=dr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=aT();u&&this.throughput.next(u);let l=sT();Rn(l)&&this.rtt.next(l)};mt&&"onchange"in mt&&this.subscription.add(kn(mt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Jl.set(rT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Jl.set(iT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(B0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(V0(({throughput:n,rtt:o})=>nT(n,o,e.rttPenaltyRequestSize)),_0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=$e(),i=new tT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(kn(e,"progress").pipe(O0()).subscribe(s=>{t=s.loaded,r=$e()}));break;case 1:case 0:i.add(kn(e,"loadstart").subscribe(()=>{t=0,r=$e()}));break}i.add(kn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=$e(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=$e(),n=0,o=$e(),u=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(i,$e()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=$e();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,s=$e()}else n+=c.byteLength;o=$e()}else i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&$e()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,$e()-o,this.concurrentDownloads.size),n=0,o=$e());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Jl.get(e);if(Rn(t))return(r=parseInt(t,10))!=null?r:void 0}},oT=Xl;import{fillWithDefault as F0,VideoQuality as uT}from"@vkontakte/videoplayer-shared";var lT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:uT.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:uT.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!0,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1},cT=a=>{var e;return{...F0(a,lT),configName:[...(e=a.configName)!=null?e:[],...lT.configName]}};import{assertNonNullable as $n,combine as bt,ErrorCategory as Ln,filter as de,filterChanged as q,fromEvent as ec,isNonNullable as W0,isNullable as Y0,Logger as z0,map as N,mapTo as fT,merge as Ut,now as Mn,once as it,Subject as j,Subscription as mT,tap as bT,ValueSubject as P,isHigher as K0,isInvariantQuality as gT,flattenObject as Ht,throttle as tc,getTraceSubscriptionMethod as vT,Tracer as J0}from"@vkontakte/videoplayer-shared";import{merge as q0,map as U0,filter as dT,isNonNullable as H0}from"@vkontakte/videoplayer-shared";var Zl=({seekState:a,position$:e})=>q0(a.stateChangeEnded$.pipe(U0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),dT(H0)),e.pipe(dT(()=>a.getState().state==="none")));import{assertNonNullable as j0}from"@vkontakte/videoplayer-shared";var pT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return j0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as G0,once as Q0}from"@vkontakte/videoplayer-shared";var hT=(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(G0(i=>i.length>0),Q0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Cn=class{constructor(e={configName:[]},t=J0.createRootTracer(!1)){this.subscription=new mT;this.logger=new z0;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new M("stopped"),seekState:new M({state:"none"}),volume:new M({volume:1,muted:!1}),videoTrack:new M(void 0),videoStream:new M(void 0),audioStream:new M(void 0),autoVideoTrackSwitching:new M(!0),autoVideoTrackLimits:new M({}),isLooped:new M(!1),isLowLatency:new M(!1),playbackRate:new M(1),externalTextTracks:new M([]),internalTextTracks:new M([]),currentTextTrack:new M(void 0),textTrackCuesSettings:new M({}),cameraOrientation:new M({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,autoplaySoundProhibited$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:hg};if(this.initLogs(),this.tuning=cT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new us({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new oT(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(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,ST.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),d=`Player.${String(i)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Ln.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var i,s,n;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Ht(r)),this.domContainer=pT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new Ua({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),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&&!qi()?(this.tracer.log("request play from hidden tab"),ec(document,"visibilitychange").pipe(it()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){$n(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(de(r=>r.length>0),it()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Ht(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;$n(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Ht(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return hT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Y0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return W0(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(de(({from:e})=>e==="stopped"),it()).subscribe(()=>{this.initedAt=Mn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Ht(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ln.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(it()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Ht(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(N(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(N(n=>n.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(bt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(de(({currentVideoStream:n})=>!!n),N(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>(o==null?void 0:o.id)===u.streamId).map(({quality:u})=>u).sort((u,l)=>gT(u)?1:gT(l)?-1:K0(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(q()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(N(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(bt({hasLiveOffsetByPaused:Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(n=>n.to),q(),N(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(bt({atLiveEdge:bt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(N(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),q(),bT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(N(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(bt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(N(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),bT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(N(n=>n.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(N(n=>n.volume),q()).subscribe(this.info.volume$)).add(Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ut(e.providerOutput.endedEvent$.pipe(fT(!0)),e.providerOutput.seekedEvent$.pipe(fT(!1))).pipe(q()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(N(n=>({id:n?`No${n}`:"NoProviders",category:Ln.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(it(),N(n=>n!=null?n:Mn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(it(),N(()=>Mn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(it(),N(()=>Mn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(de(({to:n})=>n==="playing"),it()).subscribe(()=>r.next(!1)));let i=0,s=Ut(e.providerOutput.isBuffering$,t,r).pipe(N(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),q());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Ut(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Ut(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(N(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new mT;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(de(r=>r.length>0),it()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Ot(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Ut(this.desiredState.videoTrack.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(N(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;$n(this.providerContainer),$n(e),pg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>dg(r)),this.providerContainer.current$.subscribe(({type:r})=>Oi("provider",r)),e.duration$.subscribe(r=>Oi("duration",r)),e.availableVideoTracks$.pipe(de(r=>!!r.length),it()).subscribe(r=>Oi("tracks",r)),this.events.fatalError$.subscribe(new he("fatalError")),this.events.managedError$.subscribe(new he("managedError")),e.position$.subscribe(new he("position")),e.currentVideoTrack$.pipe(N(r=>r==null?void 0:r.quality)).subscribe(new he("quality")),this.info.currentBuffer$.subscribe(new he("buffer")),e.isBuffering$.subscribe(new he("isBuffering"))].forEach(r=>this.subscription.add(r)),Oi("codecs",Sv())}initTracerSubscription(){let e=vT(this.tracer.log.bind(this.tracer)),t=vT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(bt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(de(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(de(r=>r>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(de(r=>r>0),q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(bt({currentBuffer:this.info.currentBuffer$.pipe(de(r=>r.end>0),q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(q())}).pipe(tc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(bt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(de(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),tc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),de(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),de(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(),de(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(bt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(de(({throughputEstimation:r,rtt:i})=>!!r&&!!i),tc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),de(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ln.DOM,message:String(i)})})};this.subscription.add(Ut(ec(document,"visibilitychange"),ec(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Ht({quality:t,availableTracks:Ht(e),track:Ht(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as oz,Observable as uz,Subject as lz,ValueSubject as cz,VideoQuality as dz}from"@vkontakte/videoplayer-shared";var pz=`@vkontakte/videoplayer-core@${Bc}`;export{rs as ChromecastState,Nn as HttpConnectionType,uz as Observable,me as PlaybackState,Cn as Player,pz as SDK_VERSION,lz as Subject,oz as Subscription,Fn as Surface,Bc as VERSION,cz as ValueSubject,Pt as VideoFormat,dz as VideoQuality};