@vkontakte/videoplayer-core 2.0.124-dev.d0d82c74.0 → 2.0.124-dev.d93f994c.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.cjs.js CHANGED
@@ -1,31 +1,31 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.124-dev.d0d82c74.0
3
- * Fri, 17 Jan 2025 13:22:53 GMT
2
+ * @vkontakte/videoplayer-core v2.0.124-dev.d93f994c.0
3
+ * Tue, 21 Jan 2025 12:34:39 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-124/doc/
5
5
  */
6
- "use strict";var IS=Object.create;var rs=Object.defineProperty;var ES=Object.getOwnPropertyDescriptor;var xS=Object.getOwnPropertyNames;var PS=Object.getPrototypeOf,wS=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),AS=(a,e)=>{for(var t in e)rs(a,t,{get:e[t],enumerable:!0})},zl=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of xS(e))!wS.call(a,i)&&i!==t&&rs(a,i,{get:()=>e[i],enumerable:!(r=ES(e,i))||r.enumerable});return a};var W=(a,e,t)=>(t=a!=null?IS(PS(a)):{},zl(e||!a||!a.__esModule?rs(t,"default",{value:a,enumerable:!0}):t,a)),kS=a=>zl(rs({},"__esModule",{value:!0}),a);var de=b((An,Kl)=>{"use strict";var vi=function(a){return a&&a.Math===Math&&a};Kl.exports=vi(typeof globalThis=="object"&&globalThis)||vi(typeof window=="object"&&window)||vi(typeof self=="object"&&self)||vi(typeof global=="object"&&global)||vi(typeof An=="object"&&An)||function(){return this}()||Function("return this")()});var Te=b((s$,Xl)=>{"use strict";Xl.exports=function(a){try{return!!a()}catch(e){return!0}}});var Si=b((n$,Jl)=>{"use strict";var RS=Te();Jl.exports=!RS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var kn=b((o$,rc)=>{"use strict";var $S=Si(),tc=Function.prototype,Zl=tc.apply,ec=tc.call;rc.exports=typeof Reflect=="object"&&Reflect.apply||($S?ec.bind(Zl):function(){return ec.apply(Zl,arguments)})});var be=b((u$,sc)=>{"use strict";var ic=Si(),ac=Function.prototype,Rn=ac.call,LS=ic&&ac.bind.bind(Rn,Rn);sc.exports=ic?LS:function(a){return function(){return Rn.apply(a,arguments)}}});var lr=b((l$,oc)=>{"use strict";var nc=be(),MS=nc({}.toString),DS=nc("".slice);oc.exports=function(a){return DS(MS(a),8,-1)}});var $n=b((c$,uc)=>{"use strict";var CS=lr(),OS=be();uc.exports=function(a){if(CS(a)==="Function")return OS(a)}});var le=b((d$,lc)=>{"use strict";var Ln=typeof document=="object"&&document.all;lc.exports=typeof Ln=="undefined"&&Ln!==void 0?function(a){return typeof a=="function"||a===Ln}:function(a){return typeof a=="function"}});var _e=b((p$,cc)=>{"use strict";var VS=Te();cc.exports=!VS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ne=b((h$,dc)=>{"use strict";var BS=Si(),ss=Function.prototype.call;dc.exports=BS?ss.bind(ss):function(){return ss.apply(ss,arguments)}});var Mn=b(mc=>{"use strict";var pc={}.propertyIsEnumerable,hc=Object.getOwnPropertyDescriptor,_S=hc&&!pc.call({1:2},1);mc.f=_S?function(e){var t=hc(this,e);return!!t&&t.enumerable}:pc});var yi=b((f$,fc)=>{"use strict";fc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var gc=b((b$,bc)=>{"use strict";var NS=be(),FS=Te(),qS=lr(),Dn=Object,US=NS("".split);bc.exports=FS(function(){return!Dn("z").propertyIsEnumerable(0)})?function(a){return qS(a)==="String"?US(a,""):Dn(a)}:Dn});var Dr=b((g$,vc)=>{"use strict";vc.exports=function(a){return a==null}});var jt=b((v$,Sc)=>{"use strict";var HS=Dr(),jS=TypeError;Sc.exports=function(a){if(HS(a))throw new jS("Can't call method on "+a);return a}});var cr=b((S$,yc)=>{"use strict";var GS=gc(),QS=jt();yc.exports=function(a){return GS(QS(a))}});var Fe=b((y$,Tc)=>{"use strict";var WS=le();Tc.exports=function(a){return typeof a=="object"?a!==null:WS(a)}});var Cr=b((T$,Ic)=>{"use strict";Ic.exports={}});var It=b((I$,xc)=>{"use strict";var Cn=Cr(),On=de(),YS=le(),Ec=function(a){return YS(a)?a:void 0};xc.exports=function(a,e){return arguments.length<2?Ec(Cn[a])||Ec(On[a]):Cn[a]&&Cn[a][e]||On[a]&&On[a][e]}});var Ti=b((E$,Pc)=>{"use strict";var zS=be();Pc.exports=zS({}.isPrototypeOf)});var dr=b((x$,kc)=>{"use strict";var KS=de(),wc=KS.navigator,Ac=wc&&wc.userAgent;kc.exports=Ac?String(Ac):""});var Bn=b((P$,Cc)=>{"use strict";var Dc=de(),Vn=dr(),Rc=Dc.process,$c=Dc.Deno,Lc=Rc&&Rc.versions||$c&&$c.version,Mc=Lc&&Lc.v8,rt,ns;Mc&&(rt=Mc.split("."),ns=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!ns&&Vn&&(rt=Vn.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Vn.match(/Chrome\/(\d+)/),rt&&(ns=+rt[1])));Cc.exports=ns});var _n=b((w$,Vc)=>{"use strict";var Oc=Bn(),XS=Te(),JS=de(),ZS=JS.String;Vc.exports=!!Object.getOwnPropertySymbols&&!XS(function(){var a=Symbol("symbol detection");return!ZS(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Oc&&Oc<41})});var Nn=b((A$,Bc)=>{"use strict";var ey=_n();Bc.exports=ey&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Fn=b((k$,_c)=>{"use strict";var ty=It(),ry=le(),iy=Ti(),ay=Nn(),sy=Object;_c.exports=ay?function(a){return typeof a=="symbol"}:function(a){var e=ty("Symbol");return ry(e)&&iy(e.prototype,sy(a))}});var Ii=b((R$,Nc)=>{"use strict";var ny=String;Nc.exports=function(a){try{return ny(a)}catch(e){return"Object"}}});var pt=b(($$,Fc)=>{"use strict";var oy=le(),uy=Ii(),ly=TypeError;Fc.exports=function(a){if(oy(a))return a;throw new ly(uy(a)+" is not a function")}});var Ei=b((L$,qc)=>{"use strict";var cy=pt(),dy=Dr();qc.exports=function(a,e){var t=a[e];return dy(t)?void 0:cy(t)}});var Hc=b((M$,Uc)=>{"use strict";var qn=Ne(),Un=le(),Hn=Fe(),py=TypeError;Uc.exports=function(a,e){var t,r;if(e==="string"&&Un(t=a.toString)&&!Hn(r=qn(t,a))||Un(t=a.valueOf)&&!Hn(r=qn(t,a))||e!=="string"&&Un(t=a.toString)&&!Hn(r=qn(t,a)))return r;throw new py("Can't convert object to primitive value")}});var it=b((D$,jc)=>{"use strict";jc.exports=!0});var Wc=b((C$,Qc)=>{"use strict";var Gc=de(),hy=Object.defineProperty;Qc.exports=function(a,e){try{hy(Gc,a,{value:e,configurable:!0,writable:!0})}catch(t){Gc[a]=e}return e}});var xi=b((O$,Kc)=>{"use strict";var my=it(),fy=de(),by=Wc(),Yc="__core-js_shared__",zc=Kc.exports=fy[Yc]||by(Yc,{});(zc.versions||(zc.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 jn=b((V$,Jc)=>{"use strict";var Xc=xi();Jc.exports=function(a,e){return Xc[a]||(Xc[a]=e||{})}});var Or=b((B$,Zc)=>{"use strict";var gy=jt(),vy=Object;Zc.exports=function(a){return vy(gy(a))}});var at=b((_$,ed)=>{"use strict";var Sy=be(),yy=Or(),Ty=Sy({}.hasOwnProperty);ed.exports=Object.hasOwn||function(e,t){return Ty(yy(e),t)}});var Gn=b((N$,td)=>{"use strict";var Iy=be(),Ey=0,xy=Math.random(),Py=Iy(1 .toString);td.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Py(++Ey+xy,36)}});var Ie=b((F$,id)=>{"use strict";var wy=de(),Ay=jn(),rd=at(),ky=Gn(),Ry=_n(),$y=Nn(),Vr=wy.Symbol,Qn=Ay("wks"),Ly=$y?Vr.for||Vr:Vr&&Vr.withoutSetter||ky;id.exports=function(a){return rd(Qn,a)||(Qn[a]=Ry&&rd(Vr,a)?Vr[a]:Ly("Symbol."+a)),Qn[a]}});var od=b((q$,nd)=>{"use strict";var My=Ne(),ad=Fe(),sd=Fn(),Dy=Ei(),Cy=Hc(),Oy=Ie(),Vy=TypeError,By=Oy("toPrimitive");nd.exports=function(a,e){if(!ad(a)||sd(a))return a;var t=Dy(a,By),r;if(t){if(e===void 0&&(e="default"),r=My(t,a,e),!ad(r)||sd(r))return r;throw new Vy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Cy(a,e)}});var Wn=b((U$,ud)=>{"use strict";var _y=od(),Ny=Fn();ud.exports=function(a){var e=_y(a,"string");return Ny(e)?e:e+""}});var os=b((H$,cd)=>{"use strict";var Fy=de(),ld=Fe(),Yn=Fy.document,qy=ld(Yn)&&ld(Yn.createElement);cd.exports=function(a){return qy?Yn.createElement(a):{}}});var zn=b((j$,dd)=>{"use strict";var Uy=_e(),Hy=Te(),jy=os();dd.exports=!Uy&&!Hy(function(){return Object.defineProperty(jy("div"),"a",{get:function(){return 7}}).a!==7})});var md=b(hd=>{"use strict";var Gy=_e(),Qy=Ne(),Wy=Mn(),Yy=yi(),zy=cr(),Ky=Wn(),Xy=at(),Jy=zn(),pd=Object.getOwnPropertyDescriptor;hd.f=Gy?pd:function(e,t){if(e=zy(e),t=Ky(t),Jy)try{return pd(e,t)}catch(r){}if(Xy(e,t))return Yy(!Qy(Wy.f,e,t),e[t])}});var Kn=b((Q$,fd)=>{"use strict";var Zy=Te(),eT=le(),tT=/#|\.prototype\./,Pi=function(a,e){var t=iT[rT(a)];return t===sT?!0:t===aT?!1:eT(e)?Zy(e):!!e},rT=Pi.normalize=function(a){return String(a).replace(tT,".").toLowerCase()},iT=Pi.data={},aT=Pi.NATIVE="N",sT=Pi.POLYFILL="P";fd.exports=Pi});var Br=b((W$,gd)=>{"use strict";var bd=$n(),nT=pt(),oT=Si(),uT=bd(bd.bind);gd.exports=function(a,e){return nT(a),e===void 0?a:oT?uT(a,e):function(){return a.apply(e,arguments)}}});var Xn=b((Y$,vd)=>{"use strict";var lT=_e(),cT=Te();vd.exports=lT&&cT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ht=b((z$,Sd)=>{"use strict";var dT=Fe(),pT=String,hT=TypeError;Sd.exports=function(a){if(dT(a))return a;throw new hT(pT(a)+" is not an object")}});var pr=b(Td=>{"use strict";var mT=_e(),fT=zn(),bT=Xn(),us=ht(),yd=Wn(),gT=TypeError,Jn=Object.defineProperty,vT=Object.getOwnPropertyDescriptor,Zn="enumerable",eo="configurable",to="writable";Td.f=mT?bT?function(e,t,r){if(us(e),t=yd(t),us(r),typeof e=="function"&&t==="prototype"&&"value"in r&&to in r&&!r[to]){var i=vT(e,t);i&&i[to]&&(e[t]=r.value,r={configurable:eo in r?r[eo]:i[eo],enumerable:Zn in r?r[Zn]:i[Zn],writable:!1})}return Jn(e,t,r)}:Jn:function(e,t,r){if(us(e),t=yd(t),us(r),fT)try{return Jn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new gT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=b((X$,Id)=>{"use strict";var ST=_e(),yT=pr(),TT=yi();Id.exports=ST?function(a,e,t){return yT.f(a,e,TT(1,t))}:function(a,e,t){return a[e]=t,a}});var he=b((J$,xd)=>{"use strict";var wi=de(),IT=kn(),ET=$n(),xT=le(),PT=md().f,wT=Kn(),Nr=Cr(),AT=Br(),Fr=_r(),Ed=at();xi();var kT=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 IT(a,this,arguments)};return e.prototype=a.prototype,e};xd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?wi:i?wi[t]:wi[t]&&wi[t].prototype,o=r?Nr:Nr[t]||Fr(Nr,t,{})[t],u=o.prototype,l,c,d,p,h,f,g,v,T;for(p in e)l=wT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Ed(n,p),f=o[p],c&&(a.dontCallGetSet?(T=PT(n,p),g=T&&T.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?v=AT(h,wi):a.wrap&&c?v=kT(h):s&&xT(h)?v=ET(h):v=h,(a.sham||h&&h.sham||f&&f.sham)&&Fr(v,"sham",!0),Fr(o,p,v),s&&(d=t+"Prototype",Ed(Nr,d)||Fr(Nr,d,{}),Fr(Nr[d],p,h),a.real&&u&&(l||!u[p])&&Fr(u,p,h)))}});var wd=b((Z$,Pd)=>{"use strict";var RT=Math.ceil,$T=Math.floor;Pd.exports=Math.trunc||function(e){var t=+e;return(t>0?$T:RT)(t)}});var Ai=b((eL,Ad)=>{"use strict";var LT=wd();Ad.exports=function(a){var e=+a;return e!==e||e===0?0:LT(e)}});var Rd=b((tL,kd)=>{"use strict";var MT=Ai(),DT=Math.max,CT=Math.min;kd.exports=function(a,e){var t=MT(a);return t<0?DT(t+e,0):CT(t,e)}});var ro=b((rL,$d)=>{"use strict";var OT=Ai(),VT=Math.min;$d.exports=function(a){var e=OT(a);return e>0?VT(e,9007199254740991):0}});var qr=b((iL,Ld)=>{"use strict";var BT=ro();Ld.exports=function(a){return BT(a.length)}});var io=b((aL,Dd)=>{"use strict";var _T=cr(),NT=Rd(),FT=qr(),Md=function(a){return function(e,t,r){var i=_T(e),s=FT(i);if(s===0)return!a&&-1;var n=NT(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}};Dd.exports={includes:Md(!0),indexOf:Md(!1)}});var ki=b((sL,Cd)=>{"use strict";Cd.exports=function(){}});var Od=b(()=>{"use strict";var qT=he(),UT=io().includes,HT=Te(),jT=ki(),GT=HT(function(){return!Array(1).includes()});qT({target:"Array",proto:!0,forced:GT},{includes:function(e){return UT(this,e,arguments.length>1?arguments[1]:void 0)}});jT("includes")});var Gt=b((uL,Vd)=>{"use strict";var QT=It();Vd.exports=QT});var _d=b((lL,Bd)=>{"use strict";Od();var WT=Gt();Bd.exports=WT("Array","includes")});var Fd=b((cL,Nd)=>{"use strict";var YT=_d();Nd.exports=YT});var st=b((dL,qd)=>{"use strict";var zT=Fd();qd.exports=zT});var cs=b((IL,jd)=>{"use strict";var XT=jn(),JT=Gn(),Hd=XT("keys");jd.exports=function(a){return Hd[a]||(Hd[a]=JT(a))}});var Qd=b((EL,Gd)=>{"use strict";var ZT=Te();Gd.exports=!ZT(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ds=b((xL,Yd)=>{"use strict";var eI=at(),tI=le(),rI=Or(),iI=cs(),aI=Qd(),Wd=iI("IE_PROTO"),ao=Object,sI=ao.prototype;Yd.exports=aI?ao.getPrototypeOf:function(a){var e=rI(a);if(eI(e,Wd))return e[Wd];var t=e.constructor;return tI(t)&&e instanceof t?t.prototype:e instanceof ao?sI:null}});var ps=b((PL,zd)=>{"use strict";zd.exports={}});var Jd=b((wL,Xd)=>{"use strict";var nI=be(),so=at(),oI=cr(),uI=io().indexOf,lI=ps(),Kd=nI([].push);Xd.exports=function(a,e){var t=oI(a),r=0,i=[],s;for(s in t)!so(lI,s)&&so(t,s)&&Kd(i,s);for(;e.length>r;)so(t,s=e[r++])&&(~uI(i,s)||Kd(i,s));return i}});var no=b((AL,Zd)=>{"use strict";Zd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var oo=b((kL,ep)=>{"use strict";var cI=Jd(),dI=no();ep.exports=Object.keys||function(e){return cI(e,dI)}});var uo=b((RL,sp)=>{"use strict";var rp=_e(),pI=Te(),ip=be(),hI=ds(),mI=oo(),fI=cr(),bI=Mn().f,ap=ip(bI),gI=ip([].push),vI=rp&&pI(function(){var a=Object.create(null);return a[2]=2,!ap(a,2)}),tp=function(a){return function(e){for(var t=fI(e),r=mI(t),i=vI&&hI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!rp||(i?u in t:ap(t,u)))&&gI(o,a?[u,t[u]]:t[u]);return o}};sp.exports={entries:tp(!0),values:tp(!1)}});var np=b(()=>{"use strict";var SI=he(),yI=uo().entries;SI({target:"Object",stat:!0},{entries:function(e){return yI(e)}})});var up=b((ML,op)=>{"use strict";np();var TI=Cr();op.exports=TI.Object.entries});var cp=b((DL,lp)=>{"use strict";var II=up();lp.exports=II});var Ur=b((CL,dp)=>{"use strict";var EI=cp();dp.exports=EI});var hr=b((OL,pp)=>{"use strict";pp.exports={}});var fp=b((VL,mp)=>{"use strict";var xI=de(),PI=le(),hp=xI.WeakMap;mp.exports=PI(hp)&&/native code/.test(String(hp))});var ho=b((BL,vp)=>{"use strict";var wI=fp(),gp=de(),AI=Fe(),kI=_r(),lo=at(),co=xi(),RI=cs(),$I=ps(),bp="Object already initialized",po=gp.TypeError,LI=gp.WeakMap,hs,Ri,ms,MI=function(a){return ms(a)?Ri(a):hs(a,{})},DI=function(a){return function(e){var t;if(!AI(e)||(t=Ri(e)).type!==a)throw new po("Incompatible receiver, "+a+" required");return t}};wI||co.state?(nt=co.state||(co.state=new LI),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,hs=function(a,e){if(nt.has(a))throw new po(bp);return e.facade=a,nt.set(a,e),e},Ri=function(a){return nt.get(a)||{}},ms=function(a){return nt.has(a)}):(mr=RI("state"),$I[mr]=!0,hs=function(a,e){if(lo(a,mr))throw new po(bp);return e.facade=a,kI(a,mr,e),e},Ri=function(a){return lo(a,mr)?a[mr]:{}},ms=function(a){return lo(a,mr)});var nt,mr;vp.exports={set:hs,get:Ri,has:ms,enforce:MI,getterFor:DI}});var bo=b((_L,yp)=>{"use strict";var mo=_e(),CI=at(),Sp=Function.prototype,OI=mo&&Object.getOwnPropertyDescriptor,fo=CI(Sp,"name"),VI=fo&&function(){}.name==="something",BI=fo&&(!mo||mo&&OI(Sp,"name").configurable);yp.exports={EXISTS:fo,PROPER:VI,CONFIGURABLE:BI}});var Ip=b(Tp=>{"use strict";var _I=_e(),NI=Xn(),FI=pr(),qI=ht(),UI=cr(),HI=oo();Tp.f=_I&&!NI?Object.defineProperties:function(e,t){qI(e);for(var r=UI(t),i=HI(t),s=i.length,n=0,o;s>n;)FI.f(e,o=i[n++],r[o]);return e}});var go=b((FL,Ep)=>{"use strict";var jI=It();Ep.exports=jI("document","documentElement")});var To=b((qL,$p)=>{"use strict";var GI=ht(),QI=Ip(),xp=no(),WI=ps(),YI=go(),zI=os(),KI=cs(),Pp=">",wp="<",So="prototype",yo="script",kp=KI("IE_PROTO"),vo=function(){},Rp=function(a){return wp+yo+Pp+a+wp+"/"+yo+Pp},Ap=function(a){a.write(Rp("")),a.close();var e=a.parentWindow.Object;return a=null,e},XI=function(){var a=zI("iframe"),e="java"+yo+":",t;return a.style.display="none",YI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Rp("document.F=Object")),t.close(),t.F},fs,bs=function(){try{fs=new ActiveXObject("htmlfile")}catch(e){}bs=typeof document!="undefined"?document.domain&&fs?Ap(fs):XI():Ap(fs);for(var a=xp.length;a--;)delete bs[So][xp[a]];return bs()};WI[kp]=!0;$p.exports=Object.create||function(e,t){var r;return e!==null?(vo[So]=GI(e),r=new vo,vo[So]=null,r[kp]=e):r=bs(),t===void 0?r:QI.f(r,t)}});var Hr=b((UL,Lp)=>{"use strict";var JI=_r();Lp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:JI(a,e,t),a}});var Po=b((HL,Cp)=>{"use strict";var ZI=Te(),eE=le(),tE=Fe(),rE=To(),Mp=ds(),iE=Hr(),aE=Ie(),sE=it(),xo=aE("iterator"),Dp=!1,Et,Io,Eo;[].keys&&(Eo=[].keys(),"next"in Eo?(Io=Mp(Mp(Eo)),Io!==Object.prototype&&(Et=Io)):Dp=!0);var nE=!tE(Et)||ZI(function(){var a={};return Et[xo].call(a)!==a});nE?Et={}:sE&&(Et=rE(Et));eE(Et[xo])||iE(Et,xo,function(){return this});Cp.exports={IteratorPrototype:Et,BUGGY_SAFARI_ITERATORS:Dp}});var gs=b((jL,Vp)=>{"use strict";var oE=Ie(),uE=oE("toStringTag"),Op={};Op[uE]="z";Vp.exports=String(Op)==="[object z]"});var $i=b((GL,Bp)=>{"use strict";var lE=gs(),cE=le(),vs=lr(),dE=Ie(),pE=dE("toStringTag"),hE=Object,mE=vs(function(){return arguments}())==="Arguments",fE=function(a,e){try{return a[e]}catch(t){}};Bp.exports=lE?vs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=fE(e=hE(a),pE))=="string"?t:mE?vs(e):(r=vs(e))==="Object"&&cE(e.callee)?"Arguments":r}});var Np=b((QL,_p)=>{"use strict";var bE=gs(),gE=$i();_p.exports=bE?{}.toString:function(){return"[object "+gE(this)+"]"}});var Li=b((WL,qp)=>{"use strict";var vE=gs(),SE=pr().f,yE=_r(),TE=at(),IE=Np(),EE=Ie(),Fp=EE("toStringTag");qp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(TE(i,Fp)||SE(i,Fp,{configurable:!0,value:e}),r&&!vE&&yE(i,"toString",IE))}});var Hp=b((YL,Up)=>{"use strict";var xE=Po().IteratorPrototype,PE=To(),wE=yi(),AE=Li(),kE=hr(),RE=function(){return this};Up.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=PE(xE,{next:wE(+!r,t)}),AE(a,i,!1,!0),kE[i]=RE,a}});var Gp=b((zL,jp)=>{"use strict";var $E=be(),LE=pt();jp.exports=function(a,e,t){try{return $E(LE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Wp=b((KL,Qp)=>{"use strict";var ME=Fe();Qp.exports=function(a){return ME(a)||a===null}});var zp=b((XL,Yp)=>{"use strict";var DE=Wp(),CE=String,OE=TypeError;Yp.exports=function(a){if(DE(a))return a;throw new OE("Can't set "+CE(a)+" as a prototype")}});var wo=b((JL,Kp)=>{"use strict";var VE=Gp(),BE=Fe(),_E=jt(),NE=zp();Kp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=VE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return _E(i),NE(s),BE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var oh=b((ZL,nh)=>{"use strict";var FE=he(),qE=Ne(),Ss=it(),ah=bo(),UE=le(),HE=Hp(),Xp=ds(),Jp=wo(),jE=Li(),GE=_r(),Ao=Hr(),QE=Ie(),Zp=hr(),sh=Po(),WE=ah.PROPER,YE=ah.CONFIGURABLE,eh=sh.IteratorPrototype,ys=sh.BUGGY_SAFARI_ITERATORS,Mi=QE("iterator"),th="keys",Di="values",rh="entries",ih=function(){return this};nh.exports=function(a,e,t,r,i,s,n){HE(t,e,r);var o=function(T){if(T===i&&p)return p;if(!ys&&T&&T in c)return c[T];switch(T){case th:return function(){return new t(this,T)};case Di:return function(){return new t(this,T)};case rh:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Mi]||c["@@iterator"]||i&&c[i],p=!ys&&d||o(i),h=e==="Array"&&c.entries||d,f,g,v;if(h&&(f=Xp(h.call(new a)),f!==Object.prototype&&f.next&&(!Ss&&Xp(f)!==eh&&(Jp?Jp(f,eh):UE(f[Mi])||Ao(f,Mi,ih)),jE(f,u,!0,!0),Ss&&(Zp[u]=ih))),WE&&i===Di&&d&&d.name!==Di&&(!Ss&&YE?GE(c,"name",Di):(l=!0,p=function(){return qE(d,this)})),i)if(g={values:o(Di),keys:s?p:o(th),entries:o(rh)},n)for(v in g)(ys||l||!(v in c))&&Ao(c,v,g[v]);else FE({target:e,proto:!0,forced:ys||l},g);return(!Ss||n)&&c[Mi]!==p&&Ao(c,Mi,p,{name:i}),Zp[e]=p,g}});var lh=b((eM,uh)=>{"use strict";uh.exports=function(a,e){return{value:a,done:e}}});var Ro=b((tM,mh)=>{"use strict";var zE=cr(),ko=ki(),ch=hr(),ph=ho(),KE=pr().f,XE=oh(),Ts=lh(),JE=it(),ZE=_e(),hh="Array Iterator",ex=ph.set,tx=ph.getterFor(hh);mh.exports=XE(Array,"Array",function(a,e){ex(this,{type:hh,target:zE(a),index:0,kind:e})},function(){var a=tx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ts(void 0,!0);switch(a.kind){case"keys":return Ts(t,!1);case"values":return Ts(e[t],!1)}return Ts([t,e[t]],!1)},"values");var dh=ch.Arguments=ch.Array;ko("keys");ko("values");ko("entries");if(!JE&&ZE&&dh.name!=="values")try{KE(dh,"name",{value:"values"})}catch(a){}});var bh=b((rM,fh)=>{"use strict";var rx=Ie(),ix=hr(),ax=rx("iterator"),sx=Array.prototype;fh.exports=function(a){return a!==void 0&&(ix.Array===a||sx[ax]===a)}});var $o=b((iM,vh)=>{"use strict";var nx=$i(),gh=Ei(),ox=Dr(),ux=hr(),lx=Ie(),cx=lx("iterator");vh.exports=function(a){if(!ox(a))return gh(a,cx)||gh(a,"@@iterator")||ux[nx(a)]}});var yh=b((aM,Sh)=>{"use strict";var dx=Ne(),px=pt(),hx=ht(),mx=Ii(),fx=$o(),bx=TypeError;Sh.exports=function(a,e){var t=arguments.length<2?fx(a):e;if(px(t))return hx(dx(t,a));throw new bx(mx(a)+" is not iterable")}});var Eh=b((sM,Ih)=>{"use strict";var gx=Ne(),Th=ht(),vx=Ei();Ih.exports=function(a,e,t){var r,i;Th(a);try{if(r=vx(a,"return"),!r){if(e==="throw")throw t;return t}r=gx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Th(r),t}});var Es=b((nM,Ah)=>{"use strict";var Sx=Br(),yx=Ne(),Tx=ht(),Ix=Ii(),Ex=bh(),xx=qr(),xh=Ti(),Px=yh(),wx=$o(),Ph=Eh(),Ax=TypeError,Is=function(a,e){this.stopped=a,this.result=e},wh=Is.prototype;Ah.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=Sx(e,r),l,c,d,p,h,f,g,v=function(E){return l&&Ph(l,"normal",E),new Is(!0,E)},T=function(E){return i?(Tx(E),o?u(E[0],E[1],v):u(E[0],E[1])):o?u(E,v):u(E)};if(s)l=a.iterator;else if(n)l=a;else{if(c=wx(a),!c)throw new Ax(Ix(a)+" is not iterable");if(Ex(c)){for(d=0,p=xx(a);p>d;d++)if(h=T(a[d]),h&&xh(wh,h))return h;return new Is(!1)}l=Px(a,c)}for(f=s?a.next:l.next;!(g=yx(f,l)).done;){try{h=T(g.value)}catch(E){Ph(l,"throw",E)}if(typeof h=="object"&&h&&xh(wh,h))return h}return new Is(!1)}});var Rh=b((oM,kh)=>{"use strict";var kx=_e(),Rx=pr(),$x=yi();kh.exports=function(a,e,t){kx?Rx.f(a,e,$x(0,t)):a[e]=t}});var $h=b(()=>{"use strict";var Lx=he(),Mx=Es(),Dx=Rh();Lx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Mx(e,function(r,i){Dx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Mh=b((cM,Lh)=>{"use strict";Ro();$h();var Cx=Cr();Lh.exports=Cx.Object.fromEntries});var Ch=b((dM,Dh)=>{"use strict";Dh.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 Vh=b(()=>{"use strict";Ro();var Ox=Ch(),Vx=de(),Bx=Li(),Oh=hr();for(xs in Ox)Bx(Vx[xs],xs),Oh[xs]=Oh.Array;var xs});var _h=b((mM,Bh)=>{"use strict";var _x=Mh();Vh();Bh.exports=_x});var Lo=b((fM,Nh)=>{"use strict";var Nx=_h();Nh.exports=Nx});var Fh=b(()=>{"use strict"});var Mo=b((vM,qh)=>{"use strict";var Ci=de(),Fx=dr(),qx=lr(),Ps=function(a){return Fx.slice(0,a.length)===a};qh.exports=function(){return Ps("Bun/")?"BUN":Ps("Cloudflare-Workers")?"CLOUDFLARE":Ps("Deno/")?"DENO":Ps("Node.js/")?"NODE":Ci.Bun&&typeof Bun.version=="string"?"BUN":Ci.Deno&&typeof Deno.version=="object"?"DENO":qx(Ci.process)==="process"?"NODE":Ci.window&&Ci.document?"BROWSER":"REST"}()});var ws=b((SM,Uh)=>{"use strict";var Ux=Mo();Uh.exports=Ux==="NODE"});var jh=b((yM,Hh)=>{"use strict";var Hx=pr();Hh.exports=function(a,e,t){return Hx.f(a,e,t)}});var Wh=b((TM,Qh)=>{"use strict";var jx=It(),Gx=jh(),Qx=Ie(),Wx=_e(),Gh=Qx("species");Qh.exports=function(a){var e=jx(a);Wx&&e&&!e[Gh]&&Gx(e,Gh,{configurable:!0,get:function(){return this}})}});var zh=b((IM,Yh)=>{"use strict";var Yx=Ti(),zx=TypeError;Yh.exports=function(a,e){if(Yx(e,a))return a;throw new zx("Incorrect invocation")}});var Co=b((EM,Kh)=>{"use strict";var Kx=be(),Xx=le(),Do=xi(),Jx=Kx(Function.toString);Xx(Do.inspectSource)||(Do.inspectSource=function(a){return Jx(a)});Kh.exports=Do.inspectSource});var Vo=b((xM,tm)=>{"use strict";var Zx=be(),eP=Te(),Xh=le(),tP=$i(),rP=It(),iP=Co(),Jh=function(){},Zh=rP("Reflect","construct"),Oo=/^\s*(?:class|function)\b/,aP=Zx(Oo.exec),sP=!Oo.test(Jh),Oi=function(e){if(!Xh(e))return!1;try{return Zh(Jh,[],e),!0}catch(t){return!1}},em=function(e){if(!Xh(e))return!1;switch(tP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return sP||!!aP(Oo,iP(e))}catch(t){return!0}};em.sham=!0;tm.exports=!Zh||eP(function(){var a;return Oi(Oi.call)||!Oi(Object)||!Oi(function(){a=!0})||a})?em:Oi});var im=b((PM,rm)=>{"use strict";var nP=Vo(),oP=Ii(),uP=TypeError;rm.exports=function(a){if(nP(a))return a;throw new uP(oP(a)+" is not a constructor")}});var Bo=b((wM,sm)=>{"use strict";var am=ht(),lP=im(),cP=Dr(),dP=Ie(),pP=dP("species");sm.exports=function(a,e){var t=am(a).constructor,r;return t===void 0||cP(r=am(t)[pP])?e:lP(r)}});var om=b((AM,nm)=>{"use strict";var hP=be();nm.exports=hP([].slice)});var lm=b((kM,um)=>{"use strict";var mP=TypeError;um.exports=function(a,e){if(a<e)throw new mP("Not enough arguments");return a}});var _o=b((RM,cm)=>{"use strict";var fP=dr();cm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(fP)});var Wo=b(($M,Sm)=>{"use strict";var qe=de(),bP=kn(),gP=Br(),dm=le(),vP=at(),vm=Te(),pm=go(),SP=om(),hm=os(),yP=lm(),TP=_o(),IP=ws(),jo=qe.setImmediate,Go=qe.clearImmediate,EP=qe.process,No=qe.Dispatch,xP=qe.Function,mm=qe.MessageChannel,PP=qe.String,Fo=0,Vi={},fm="onreadystatechange",Bi,fr,qo,Uo;vm(function(){Bi=qe.location});var Qo=function(a){if(vP(Vi,a)){var e=Vi[a];delete Vi[a],e()}},Ho=function(a){return function(){Qo(a)}},bm=function(a){Qo(a.data)},gm=function(a){qe.postMessage(PP(a),Bi.protocol+"//"+Bi.host)};(!jo||!Go)&&(jo=function(e){yP(arguments.length,1);var t=dm(e)?e:xP(e),r=SP(arguments,1);return Vi[++Fo]=function(){bP(t,void 0,r)},fr(Fo),Fo},Go=function(e){delete Vi[e]},IP?fr=function(a){EP.nextTick(Ho(a))}:No&&No.now?fr=function(a){No.now(Ho(a))}:mm&&!TP?(qo=new mm,Uo=qo.port2,qo.port1.onmessage=bm,fr=gP(Uo.postMessage,Uo)):qe.addEventListener&&dm(qe.postMessage)&&!qe.importScripts&&Bi&&Bi.protocol!=="file:"&&!vm(gm)?(fr=gm,qe.addEventListener("message",bm,!1)):fm in hm("script")?fr=function(a){pm.appendChild(hm("script"))[fm]=function(){pm.removeChild(this),Qo(a)}}:fr=function(a){setTimeout(Ho(a),0)});Sm.exports={set:jo,clear:Go}});var Im=b((LM,Tm)=>{"use strict";var ym=de(),wP=_e(),AP=Object.getOwnPropertyDescriptor;Tm.exports=function(a){if(!wP)return ym[a];var e=AP(ym,a);return e&&e.value}});var Yo=b((MM,xm)=>{"use strict";var Em=function(){this.head=null,this.tail=null};Em.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}}};xm.exports=Em});var wm=b((DM,Pm)=>{"use strict";var kP=dr();Pm.exports=/ipad|iphone|ipod/i.test(kP)&&typeof Pebble!="undefined"});var km=b((CM,Am)=>{"use strict";var RP=dr();Am.exports=/web0s(?!.*chrome)/i.test(RP)});var Om=b((OM,Cm)=>{"use strict";var Gr=de(),$P=Im(),Rm=Br(),zo=Wo().set,LP=Yo(),MP=_o(),DP=wm(),CP=km(),Ko=ws(),$m=Gr.MutationObserver||Gr.WebKitMutationObserver,Lm=Gr.document,Mm=Gr.process,As=Gr.Promise,Zo=$P("queueMicrotask"),jr,Xo,Jo,ks,Dm;Zo||(_i=new LP,Ni=function(){var a,e;for(Ko&&(a=Mm.domain)&&a.exit();e=_i.get();)try{e()}catch(t){throw _i.head&&jr(),t}a&&a.enter()},!MP&&!Ko&&!CP&&$m&&Lm?(Xo=!0,Jo=Lm.createTextNode(""),new $m(Ni).observe(Jo,{characterData:!0}),jr=function(){Jo.data=Xo=!Xo}):!DP&&As&&As.resolve?(ks=As.resolve(void 0),ks.constructor=As,Dm=Rm(ks.then,ks),jr=function(){Dm(Ni)}):Ko?jr=function(){Mm.nextTick(Ni)}:(zo=Rm(zo,Gr),jr=function(){zo(Ni)}),Zo=function(a){_i.head||jr(),_i.add(a)});var _i,Ni;Cm.exports=Zo});var Bm=b((VM,Vm)=>{"use strict";Vm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Rs=b((BM,_m)=>{"use strict";_m.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var br=b((_M,Nm)=>{"use strict";var OP=de();Nm.exports=OP.Promise});var Qr=b((NM,Hm)=>{"use strict";var VP=de(),Fi=br(),BP=le(),_P=Kn(),NP=Co(),FP=Ie(),Fm=Mo(),qP=it(),eu=Bn(),qm=Fi&&Fi.prototype,UP=FP("species"),tu=!1,Um=BP(VP.PromiseRejectionEvent),HP=_P("Promise",function(){var a=NP(Fi),e=a!==String(Fi);if(!e&&eu===66||qP&&!(qm.catch&&qm.finally))return!0;if(!eu||eu<51||!/native code/.test(a)){var t=new Fi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[UP]=r,tu=t.then(function(){})instanceof r,!tu)return!0}return!e&&(Fm==="BROWSER"||Fm==="DENO")&&!Um});Hm.exports={CONSTRUCTOR:HP,REJECTION_EVENT:Um,SUBCLASSING:tu}});var Wr=b((FM,Gm)=>{"use strict";var jm=pt(),jP=TypeError,GP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new jP("Bad Promise constructor");e=r,t=i}),this.resolve=jm(e),this.reject=jm(t)};Gm.exports.f=function(a){return new GP(a)}});var df=b(()=>{"use strict";var QP=he(),WP=it(),Ds=ws(),Qt=de(),Xr=Ne(),Qm=Hr(),Wm=wo(),YP=Li(),zP=Wh(),KP=pt(),Ms=le(),XP=Fe(),JP=zh(),ZP=Bo(),Jm=Wo().set,nu=Om(),ew=Bm(),tw=Rs(),rw=Yo(),Zm=ho(),Cs=br(),ou=Qr(),ef=Wr(),Os="Promise",tf=ou.CONSTRUCTOR,iw=ou.REJECTION_EVENT,aw=ou.SUBCLASSING,ru=Zm.getterFor(Os),sw=Zm.set,Yr=Cs&&Cs.prototype,gr=Cs,$s=Yr,rf=Qt.TypeError,iu=Qt.document,uu=Qt.process,au=ef.f,nw=au,ow=!!(iu&&iu.createEvent&&Qt.dispatchEvent),af="unhandledrejection",uw="rejectionhandled",Ym=0,sf=1,lw=2,lu=1,nf=2,Ls,zm,cw,Km,of=function(a){var e;return XP(a)&&Ms(e=a.then)?e:!1},uf=function(a,e){var t=e.value,r=e.state===sf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===nf&&pw(e),e.rejection=lu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new rf("Promise-chain cycle")):(l=of(u))?Xr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},lf=function(a,e){a.notified||(a.notified=!0,nu(function(){for(var t=a.reactions,r;r=t.get();)uf(r,a);a.notified=!1,e&&!a.rejection&&dw(a)}))},cf=function(a,e,t){var r,i;ow?(r=iu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Qt.dispatchEvent(r)):r={promise:e,reason:t},!iw&&(i=Qt["on"+a])?i(r):a===af&&ew("Unhandled promise rejection",t)},dw=function(a){Xr(Jm,Qt,function(){var e=a.facade,t=a.value,r=Xm(a),i;if(r&&(i=tw(function(){Ds?uu.emit("unhandledRejection",t,e):cf(af,e,t)}),a.rejection=Ds||Xm(a)?nf:lu,i.error))throw i.value})},Xm=function(a){return a.rejection!==lu&&!a.parent},pw=function(a){Xr(Jm,Qt,function(){var e=a.facade;Ds?uu.emit("rejectionHandled",e):cf(uw,e,a.value)})},zr=function(a,e,t){return function(r){a(e,r,t)}},Kr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=lw,lf(a,!0))},su=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new rf("Promise can't be resolved itself");var r=of(e);r?nu(function(){var i={done:!1};try{Xr(r,e,zr(su,i,a),zr(Kr,i,a))}catch(s){Kr(i,s,a)}}):(a.value=e,a.state=sf,lf(a,!1))}catch(i){Kr({done:!1},i,a)}}};if(tf&&(gr=function(e){JP(this,$s),KP(e),Xr(Ls,this);var t=ru(this);try{e(zr(su,t),zr(Kr,t))}catch(r){Kr(t,r)}},$s=gr.prototype,Ls=function(e){sw(this,{type:Os,done:!1,notified:!1,parent:!1,reactions:new rw,rejection:!1,state:Ym,value:void 0})},Ls.prototype=Qm($s,"then",function(e,t){var r=ru(this),i=au(ZP(this,gr));return r.parent=!0,i.ok=Ms(e)?e:!0,i.fail=Ms(t)&&t,i.domain=Ds?uu.domain:void 0,r.state===Ym?r.reactions.add(i):nu(function(){uf(i,r)}),i.promise}),zm=function(){var a=new Ls,e=ru(a);this.promise=a,this.resolve=zr(su,e),this.reject=zr(Kr,e)},ef.f=au=function(a){return a===gr||a===cw?new zm(a):nw(a)},!WP&&Ms(Cs)&&Yr!==Object.prototype)){Km=Yr.then,aw||Qm(Yr,"then",function(e,t){var r=this;return new gr(function(i,s){Xr(Km,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Yr.constructor}catch(a){}Wm&&Wm(Yr,$s)}QP({global:!0,constructor:!0,wrap:!0,forced:tf},{Promise:gr});YP(gr,Os,!1,!0);zP(Os)});var bf=b((HM,ff)=>{"use strict";var hw=Ie(),hf=hw("iterator"),mf=!1;try{pf=0,cu={next:function(){return{done:!!pf++}},return:function(){mf=!0}},cu[hf]=function(){return this},Array.from(cu,function(){throw 2})}catch(a){}var pf,cu;ff.exports=function(a,e){try{if(!e&&!mf)return!1}catch(i){return!1}var t=!1;try{var r={};r[hf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var du=b((jM,gf)=>{"use strict";var mw=br(),fw=bf(),bw=Qr().CONSTRUCTOR;gf.exports=bw||!fw(function(a){mw.all(a).then(void 0,function(){})})});var vf=b(()=>{"use strict";var gw=he(),vw=Ne(),Sw=pt(),yw=Wr(),Tw=Rs(),Iw=Es(),Ew=du();gw({target:"Promise",stat:!0,forced:Ew},{all:function(e){var t=this,r=yw.f(t),i=r.resolve,s=r.reject,n=Tw(function(){var o=Sw(t.resolve),u=[],l=0,c=1;Iw(e,function(d){var p=l++,h=!1;c++,vw(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var yf=b(()=>{"use strict";var xw=he(),Pw=it(),ww=Qr().CONSTRUCTOR,hu=br(),Aw=It(),kw=le(),Rw=Hr(),Sf=hu&&hu.prototype;xw({target:"Promise",proto:!0,forced:ww,real:!0},{catch:function(a){return this.then(void 0,a)}});!Pw&&kw(hu)&&(pu=Aw("Promise").prototype.catch,Sf.catch!==pu&&Rw(Sf,"catch",pu,{unsafe:!0}));var pu});var Tf=b(()=>{"use strict";var $w=he(),Lw=Ne(),Mw=pt(),Dw=Wr(),Cw=Rs(),Ow=Es(),Vw=du();$w({target:"Promise",stat:!0,forced:Vw},{race:function(e){var t=this,r=Dw.f(t),i=r.reject,s=Cw(function(){var n=Mw(t.resolve);Ow(e,function(o){Lw(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var If=b(()=>{"use strict";var Bw=he(),_w=Wr(),Nw=Qr().CONSTRUCTOR;Bw({target:"Promise",stat:!0,forced:Nw},{reject:function(e){var t=_w.f(this),r=t.reject;return r(e),t.promise}})});var mu=b((ZM,Ef)=>{"use strict";var Fw=ht(),qw=Fe(),Uw=Wr();Ef.exports=function(a,e){if(Fw(a),qw(e)&&e.constructor===a)return e;var t=Uw.f(a),r=t.resolve;return r(e),t.promise}});var wf=b(()=>{"use strict";var Hw=he(),jw=It(),xf=it(),Gw=br(),Pf=Qr().CONSTRUCTOR,Qw=mu(),Ww=jw("Promise"),Yw=xf&&!Pf;Hw({target:"Promise",stat:!0,forced:xf||Pf},{resolve:function(e){return Qw(Yw&&this===Ww?Gw:this,e)}})});var Af=b(()=>{"use strict";df();vf();yf();Tf();If();wf()});var Lf=b(()=>{"use strict";var zw=he(),Kw=it(),Vs=br(),Xw=Te(),Rf=It(),$f=le(),Jw=Bo(),kf=mu(),Zw=Hr(),bu=Vs&&Vs.prototype,eA=!!Vs&&Xw(function(){bu.finally.call({then:function(){}},function(){})});zw({target:"Promise",proto:!0,real:!0,forced:eA},{finally:function(a){var e=Jw(this,Rf("Promise")),t=$f(a);return this.then(t?function(r){return kf(e,a()).then(function(){return r})}:a,t?function(r){return kf(e,a()).then(function(){throw r})}:a)}});!Kw&&$f(Vs)&&(fu=Rf("Promise").prototype.finally,bu.finally!==fu&&Zw(bu,"finally",fu,{unsafe:!0}));var fu});var Df=b((n0,Mf)=>{"use strict";Fh();Af();Lf();var tA=Gt();Mf.exports=tA("Promise","finally")});var Of=b((o0,Cf)=>{"use strict";var rA=Df();Cf.exports=rA});var Bs=b((u0,Vf)=>{"use strict";var iA=Of();Vf.exports=iA});var Hf=b(()=>{"use strict";var uA=he(),lA=uo().values;uA({target:"Object",stat:!0},{values:function(e){return lA(e)}})});var Gf=b((N0,jf)=>{"use strict";Hf();var cA=Cr();jf.exports=cA.Object.values});var Wf=b((F0,Qf)=>{"use strict";var dA=Gf();Qf.exports=dA});var Jr=b((q0,Yf)=>{"use strict";var pA=Wf();Yf.exports=pA});var Jf=b(()=>{"use strict";var bA=he(),gA=Or(),vA=qr(),SA=Ai(),yA=ki();bA({target:"Array",proto:!0},{at:function(e){var t=gA(this),r=vA(t),i=SA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});yA("at")});var eb=b((dD,Zf)=>{"use strict";Jf();var TA=Gt();Zf.exports=TA("Array","at")});var rb=b((pD,tb)=>{"use strict";var IA=eb();tb.exports=IA});var Zr=b((hD,ib)=>{"use strict";var EA=rb();ib.exports=EA});var Du=b((LC,Eb)=>{"use strict";var CA=lr();Eb.exports=Array.isArray||function(e){return CA(e)==="Array"}});var Pb=b((MC,xb)=>{"use strict";var OA=TypeError,VA=9007199254740991;xb.exports=function(a){if(a>VA)throw OA("Maximum allowed index exceeded");return a}});var kb=b((DC,Ab)=>{"use strict";var BA=Du(),_A=qr(),NA=Pb(),FA=Br(),wb=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?FA(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&BA(d)?(p=_A(d),u=wb(a,e,d,p,u,s-1)-1):(NA(u+1),a[u]=d),u++),l++;return u};Ab.exports=wb});var Mb=b((CC,Lb)=>{"use strict";var Rb=Du(),qA=Vo(),UA=Fe(),HA=Ie(),jA=HA("species"),$b=Array;Lb.exports=function(a){var e;return Rb(a)&&(e=a.constructor,qA(e)&&(e===$b||Rb(e.prototype))?e=void 0:UA(e)&&(e=e[jA],e===null&&(e=void 0))),e===void 0?$b:e}});var Cb=b((OC,Db)=>{"use strict";var GA=Mb();Db.exports=function(a,e){return new(GA(a))(e===0?0:e)}});var Ob=b(()=>{"use strict";var QA=he(),WA=kb(),YA=pt(),zA=Or(),KA=qr(),XA=Cb();QA({target:"Array",proto:!0},{flatMap:function(e){var t=zA(this),r=KA(t),i;return YA(e),i=XA(t,0),i.length=WA(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Vb=b(()=>{"use strict";var JA=ki();JA("flatMap")});var _b=b((FC,Bb)=>{"use strict";Ob();Vb();var ZA=Gt();Bb.exports=ZA("Array","flatMap")});var Fb=b((qC,Nb)=>{"use strict";var ek=_b();Nb.exports=ek});var Cu=b((UC,qb)=>{"use strict";var tk=Fb();qb.exports=tk});var Ji=b((XC,og)=>{"use strict";var lk=$i(),ck=String;og.exports=function(a){if(lk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ck(a)}});var Vu=b((JC,ug)=>{"use strict";ug.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 dg=b((ZC,cg)=>{"use strict";var dk=be(),pk=jt(),hk=Ji(),_u=Vu(),lg=dk("".replace),mk=RegExp("^["+_u+"]+"),fk=RegExp("(^|[^"+_u+"])["+_u+"]+$"),Bu=function(a){return function(e){var t=hk(pk(e));return a&1&&(t=lg(t,mk,"")),a&2&&(t=lg(t,fk,"$1")),t}};cg.exports={start:Bu(1),end:Bu(2),trim:Bu(3)}});var fg=b((eO,mg)=>{"use strict";var bk=bo().PROPER,gk=Te(),pg=Vu(),hg="\u200B\x85\u180E";mg.exports=function(a){return gk(function(){return!!pg[a]()||hg[a]()!==hg||bk&&pg[a].name!==a})}});var Nu=b((tO,bg)=>{"use strict";var vk=dg().start,Sk=fg();bg.exports=Sk("trimStart")?function(){return vk(this)}:"".trimStart});var vg=b(()=>{"use strict";var yk=he(),gg=Nu();yk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==gg},{trimLeft:gg})});var yg=b(()=>{"use strict";vg();var Tk=he(),Sg=Nu();Tk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Sg},{trimStart:Sg})});var Ig=b((nO,Tg)=>{"use strict";yg();var Ik=Gt();Tg.exports=Ik("String","trimLeft")});var xg=b((oO,Eg)=>{"use strict";var Ek=Ig();Eg.exports=Ek});var wg=b((uO,Pg)=>{"use strict";var xk=xg();Pg.exports=xk});var Fg=b(()=>{"use strict"});var qg=b(()=>{"use strict"});var Hg=b((kB,Ug)=>{"use strict";var jk=Fe(),Gk=lr(),Qk=Ie(),Wk=Qk("match");Ug.exports=function(a){var e;return jk(a)&&((e=a[Wk])!==void 0?!!e:Gk(a)==="RegExp")}});var Gg=b((RB,jg)=>{"use strict";var Yk=ht();jg.exports=function(){var a=Yk(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 Yg=b(($B,Wg)=>{"use strict";var zk=Ne(),Kk=at(),Xk=Ti(),Jk=Gg(),Qg=RegExp.prototype;Wg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Qg)&&!Kk(a,"flags")&&Xk(Qg,a)?zk(Jk,a):e}});var Kg=b((LB,zg)=>{"use strict";var Qu=be(),Zk=Or(),eR=Math.floor,ju=Qu("".charAt),tR=Qu("".replace),Gu=Qu("".slice),rR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,iR=/\$([$&'`]|\d{1,2})/g;zg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=iR;return i!==void 0&&(i=Zk(i),u=rR),tR(s,u,function(l,c){var d;switch(ju(c,0)){case"$":return"$";case"&":return a;case"`":return Gu(e,0,t);case"'":return Gu(e,n);case"<":d=i[Gu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=eR(p/10);return h===0?l:h<=o?r[h-1]===void 0?ju(c,1):r[h-1]+ju(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var Zg=b(()=>{"use strict";var aR=he(),sR=Ne(),Yu=be(),Xg=jt(),nR=le(),oR=Dr(),uR=Hg(),ni=Ji(),lR=Ei(),cR=Yg(),dR=Kg(),pR=Ie(),hR=it(),mR=pR("replace"),fR=TypeError,Wu=Yu("".indexOf),bR=Yu("".replace),Jg=Yu("".slice),gR=Math.max;aR({target:"String",proto:!0},{replaceAll:function(e,t){var r=Xg(this),i,s,n,o,u,l,c,d,p,h,f=0,g="";if(!oR(e)){if(i=uR(e),i&&(s=ni(Xg(cR(e))),!~Wu(s,"g")))throw new fR("`.replaceAll` does not allow non-global regexes");if(n=lR(e,mR),n)return sR(n,e,r,t);if(hR&&i)return bR(ni(r),e,t)}for(o=ni(r),u=ni(e),l=nR(t),l||(t=ni(t)),c=u.length,d=gR(1,c),p=Wu(o,u);p!==-1;)h=l?ni(t(u,p,o)):dR(u,o,p,[],void 0,t),g+=Jg(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Wu(o,u,p+d);return f<o.length&&(g+=Jg(o,f)),g}})});var tv=b((CB,ev)=>{"use strict";Fg();qg();Zg();var vR=Gt();ev.exports=vR("String","replaceAll")});var iv=b((OB,rv)=>{"use strict";var SR=tv();rv.exports=SR});var sv=b((VB,av)=>{"use strict";var yR=iv();av.exports=yR});var ov=b((BB,nv)=>{"use strict";var TR=Ai(),IR=Ji(),ER=jt(),xR=RangeError;nv.exports=function(e){var t=IR(ER(this)),r="",i=TR(e);if(i<0||i===1/0)throw new xR("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var pv=b((_B,dv)=>{"use strict";var cv=be(),PR=ro(),uv=Ji(),wR=ov(),AR=jt(),kR=cv(wR),RR=cv("".slice),$R=Math.ceil,lv=function(a){return function(e,t,r){var i=uv(AR(e)),s=PR(t),n=i.length,o=r===void 0?" ":uv(r),u,l;return s<=n||o===""?i:(u=s-n,l=kR(o,$R(u/o.length)),l.length>u&&(l=RR(l,0,u)),a?i+l:l+i)}};dv.exports={start:lv(!1),end:lv(!0)}});var mv=b((NB,hv)=>{"use strict";var LR=dr();hv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(LR)});var fv=b(()=>{"use strict";var MR=he(),DR=pv().start,CR=mv();MR({target:"String",proto:!0,forced:CR},{padStart:function(e){return DR(this,e,arguments.length>1?arguments[1]:void 0)}})});var gv=b((UB,bv)=>{"use strict";fv();var OR=Gt();bv.exports=OR("String","padStart")});var Sv=b((HB,vv)=>{"use strict";var VR=gv();vv.exports=VR});var Tv=b((jB,yv)=>{"use strict";var BR=Sv();yv.exports=BR});var t$={};AS(t$,{ChromecastState:()=>gi,HttpConnectionType:()=>is,Observable:()=>St.Observable,PlaybackState:()=>we,Player:()=>Ha,SDK_VERSION:()=>e$,Subject:()=>St.Subject,Subscription:()=>St.Subscription,Surface:()=>as,VERSION:()=>wn,ValueSubject:()=>St.ValueSubject,VideoFormat:()=>Tt,VideoQuality:()=>St.VideoQuality});module.exports=kS(t$);var wn="2.0.124-dev.d0d82c74.0";var we=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(we||{}),Tt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(Tt||{});var gi=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(gi||{}),is=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(is||{});var as=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(as||{});var hS=W(st(),1);var F=require("@vkontakte/videoplayer-shared/es2018");var Ud=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var ls=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,F.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Ud("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:F.ErrorCategory.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(){(0,F.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,F.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(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(0,F.assertNever)(i.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,F.map)(i=>i.castState)),(0,F.observableFrom)([r.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(KT),(0,F.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,F.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,F.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,F.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,F.isNonNullable)(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:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},KT=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(0,F.assertNever)(a)}};var hl=W(st(),1),eS=W(Ur(),1),tS=W(Lo(),1);var Ff=W(Bs(),1);var gu=require("@vkontakte/videoplayer-shared/es2018");var Ee=(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:(0,gu.assertNever)(t)}return a},_s=(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:(0,gu.assertNever)(e)}};var A=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var mt=require("@vkontakte/videoplayer-shared/es2018"),U=class{constructor(e){this.transitionStarted$=new mt.Subject;this.transitionEnded$=new mt.Subject;this.transitionUpdated$=new mt.Subject;this.forceChanged$=new mt.Subject;this.stateChangeStarted$=(0,mt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,mt.merge)(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||(0,mt.isNonNullable)(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}};var Bf=require("@vkontakte/videoplayer-shared/es2018"),_f=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(0,Bf.assertNever)(a)}};var $=require("@vkontakte/videoplayer-shared/es2018");var aA=5,sA=5,nA=500,Nf=7e3,qi=class{constructor(e){this.subscription=new $.Subscription;this.loadMediaTimeoutSubscription=new $.Subscription;this.videoState=new U("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:(0,$.assertNever)(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:(0,$.assertNever)(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:(0,$.assertNever)(e)}break}default:(0,$.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_f(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 $.Subscription;this.subscription.add(e),this.subscription.add((0,$.merge)(this.videoState.stateChangeStarted$.pipe((0,$.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,$.map)(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 $.Subject;e.add(i.pipe((0,$.debounce)(nA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,$.fromEvent)(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)>aA)&&i.next(o),s=o})),e.add((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,$.fromEvent)(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<sA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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:(0,$.assertNever)(n)}}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,$.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,$.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,$.observableFrom)(["init"])).pipe((0,$.debounce)(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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];(0,$.assertNonNullable)(c);let d=(0,$.getHighestQuality)(Object.keys(c));(0,$.assertNonNullable)(d);let p=c[d];(0,$.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,$.assertNonNullable)(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,$.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,$.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,$.assertNonNullable)(c),r=Ee(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:$.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,$.assertNever)(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(0,$.isNonNullable)(o)&&(n.metadata.title=o),(0,$.isNonNullable)(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((0,$.timeout)(Nf).subscribe(()=>s(`timeout(${Nf})`)))});(0,Ff.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:$.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Lu=W(st(),1);var Tu=require("@vkontakte/videoplayer-shared/es2018");var qf=require("@vkontakte/videoplayer-shared/es2018"),Uf=a=>{try{a.pause(),a.playbackRate=0,(0,qf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Ns=require("@vkontakte/videoplayer-shared/es2018"),vu=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)}},Su=window.WeakMap?new WeakMap:new vu,yu=window.WeakMap?new WeakMap:new Map,oA=(a,e=20)=>{let t=0;return(0,Ns.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Re=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Tu.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),Su.set(t,r);let i=new Ns.Subscription;return i.add(oA(t,e)),yu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},$e=a=>{let e=yu.get(a);e==null||e.unsubscribe(),yu.delete(a);let t=Su.get(a);Su.delete(a),t?(0,Tu.clearVideoElement)(a):Uf(a)};var Iu=W(Jr(),1),L=require("@vkontakte/videoplayer-shared/es2018");var Wt=require("@vkontakte/videoplayer-shared/es2018"),Fs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Wt.isNullable)(i),l=new Wt.Subscription;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ft=(a,e,t)=>Fs(e,()=>a.loop,r=>{(0,Wt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Le=(a,e,t,r)=>Fs(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Wt.isNonNullable)(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}),We=(a,e,t,r)=>Fs(e,()=>a.playbackRate,i=>{(0,Wt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Yt=Fs;var hA=a=>["__",a.language,a.label].join("|"),mA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Eu=class a{constructor(e){this.available$=new L.Subject;this.current$=new L.ValueSubject(void 0);this.error$=new L.Subject;this.subscription=new L.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:L.ErrorCategory.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(Yt(t.internalTextTracks,()=>(0,Iu.default)(this.internalTracks),s=>{(0,L.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Yt(t.externalTextTracks,()=>(0,Iu.default)(this.externalTracks),s=>{(0,L.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,L.isNonNullable)(s)&&(0,L.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,L.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Yt(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(Yt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,L.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,L.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"addtrack"),(0,L.fromEvent)(e,"removetrack"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,L.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,L.merge)((0,L.fromEvent)(e,"change"),(0,L.observableFrom)(["init"])).pipe((0,L.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,L.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,L.filterChanged)()).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((0,L.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,L.fromEvent)(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;(0,L.isNonNullable)(t.align)&&(i.align=t.align),(0,L.isNonNullable)(t.position)&&(i.position=t.position),(0,L.isNonNullable)(t.size)&&(i.size=t.size),(0,L.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,L.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:hA(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,L.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,L.isNullable)(e)||!mA(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){(0,L.assertNonNullable)(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,L.assertNonNullable)(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)}},Ye=Eu;var Pt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var zf=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},xu=a=>{let e=zf(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Kf=a=>{let e=zf(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared/es2018");var fA=3,Xf=(a,e,t=fA)=>{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 Me=a=>{let e=x=>(0,D.fromEvent)(a,x).pipe((0,D.mapTo)(void 0)),r=(0,D.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,D.fromEvent)(a,x))).pipe((0,D.map)(x=>x.type==="ended"?a.readyState<2:a.readyState<3),(0,D.filterChanged)()),i=(0,D.merge)((0,D.fromEvent)(a,"progress"),(0,D.fromEvent)(a,"timeupdate")).pipe((0,D.map)(()=>Xf(a.buffered,a.currentTime))),s=D.clientChecker.isSafari?(0,D.combine)({play:e("play").pipe((0,D.once)()),playing:e("playing")}).pipe((0,D.mapTo)(void 0)):e("playing"),n=(0,D.fromEvent)(a,"volumechange").pipe((0,D.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,D.fromEvent)(a,"ratechange").pipe((0,D.map)(()=>a.playbackRate)),u=(0,D.fromEvent)(a,"error").pipe((0,D.filter)(()=>!!(a.error||a.played.length)),(0,D.map)(()=>{var k;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:D.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(k=a.error)!=null?k:void 0}})),l=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(()=>a.currentTime)),c=new D.Subject,d=.3,p;l.subscribe(x=>{a.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(x)&&p>=a.duration-d&&x<=d&&c.next(p),p=x});let h=e("pause").pipe((0,D.filter)(()=>!a.error&&p!==a.duration)),f=(0,D.fromEvent)(a,"enterpictureinpicture"),g=(0,D.fromEvent)(a,"leavepictureinpicture"),v=new D.ValueSubject(Kf(a));f.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let T=new D.ValueSubject(xu(a));return(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.map)(()=>xu(a))).subscribe(T),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,D.fromEvent)(a,"durationchange").pipe((0,D.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:T,enterPip$:f,leavePip$:g}};var wt=require("@vkontakte/videoplayer-shared/es2018"),zt=a=>{switch(a){case"mobile":return wt.VideoQuality.Q_144P;case"lowest":return wt.VideoQuality.Q_240P;case"low":return wt.VideoQuality.Q_360P;case"sd":case"medium":return wt.VideoQuality.Q_480P;case"hd":case"high":return wt.VideoQuality.Q_720P;case"fullhd":case"full":return wt.VideoQuality.Q_1080P;case"quadhd":case"quad":return wt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return wt.VideoQuality.Q_2160P}};var Kt=W(Zr(),1),ub=W(st(),1),qs=W(Ur(),1),M=require("@vkontakte/videoplayer-shared/es2018");var Pu=!1,At={},ab=a=>{Pu=a},sb=()=>{At={}},nb=a=>{a(At)},Ui=(a,e)=>{var t;Pu&&(At.meta=(t=At.meta)!=null?t:{},At.meta[a]=e)},Ae=class{constructor(e){this.name=e}next(e){var r,i;if(!Pu)return;At.series=(r=At.series)!=null?r:{};let t=(i=At.series[this.name])!=null?i:[];t.push([Date.now(),e]),At.series[this.name]=t}};var xA=new Ae("best_bitrate"),lb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var wu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Hi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},cb='Assertion "ABR Tracks is empty array" failed',Us=(a,e,t,r)=>{var u;let i=[...e].sort(wu(1)),s=[...t].sort(wu(1)),n=s.filter(l=>(0,M.isNonNullable)(l.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Kt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Kt.default)(s,-1);return o&&(0,ub.default)(n,o)?o:n.length?(0,Kt.default)(n,-1):(0,Kt.default)(s,0)},ob=a=>"quality"in a,db=(a,e,t,r)=>{var n;let i=(0,M.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,M.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,M.now)()-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=ob(o)?"video":"audio",l=ob(o)?o.quality:o.bitrate;return e({message:`
6
+ "use strict";var PS=Object.create;var is=Object.defineProperty;var wS=Object.getOwnPropertyDescriptor;var AS=Object.getOwnPropertyNames;var kS=Object.getPrototypeOf,RS=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),LS=(a,e)=>{for(var t in e)is(a,t,{get:e[t],enumerable:!0})},Xl=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of AS(e))!RS.call(a,i)&&i!==t&&is(a,i,{get:()=>e[i],enumerable:!(r=wS(e,i))||r.enumerable});return a};var G=(a,e,t)=>(t=a!=null?PS(kS(a)):{},Xl(e||!a||!a.__esModule?is(t,"default",{value:a,enumerable:!0}):t,a)),$S=a=>Xl(is({},"__esModule",{value:!0}),a);var pe=b((Rn,Jl)=>{"use strict";var yi=function(a){return a&&a.Math===Math&&a};Jl.exports=yi(typeof globalThis=="object"&&globalThis)||yi(typeof window=="object"&&window)||yi(typeof self=="object"&&self)||yi(typeof global=="object"&&global)||yi(typeof Rn=="object"&&Rn)||function(){return this}()||Function("return this")()});var ye=b((lL,Zl)=>{"use strict";Zl.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ti=b((cL,ec)=>{"use strict";var MS=ye();ec.exports=!MS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Ln=b((dL,ac)=>{"use strict";var DS=Ti(),ic=Function.prototype,tc=ic.apply,rc=ic.call;ac.exports=typeof Reflect=="object"&&Reflect.apply||(DS?rc.bind(tc):function(){return rc.apply(tc,arguments)})});var be=b((pL,oc)=>{"use strict";var sc=Ti(),nc=Function.prototype,$n=nc.call,CS=sc&&nc.bind.bind($n,$n);oc.exports=sc?CS:function(a){return function(){return $n.apply(a,arguments)}}});var ur=b((hL,lc)=>{"use strict";var uc=be(),VS=uc({}.toString),OS=uc("".slice);lc.exports=function(a){return OS(VS(a),8,-1)}});var Mn=b((fL,cc)=>{"use strict";var BS=ur(),_S=be();cc.exports=function(a){if(BS(a)==="Function")return _S(a)}});var ce=b((mL,dc)=>{"use strict";var Dn=typeof document=="object"&&document.all;dc.exports=typeof Dn=="undefined"&&Dn!==void 0?function(a){return typeof a=="function"||a===Dn}:function(a){return typeof a=="function"}});var Fe=b((bL,pc)=>{"use strict";var NS=ye();pc.exports=!NS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var qe=b((gL,hc)=>{"use strict";var FS=Ti(),ns=Function.prototype.call;hc.exports=FS?ns.bind(ns):function(){return ns.apply(ns,arguments)}});var Cn=b(bc=>{"use strict";var fc={}.propertyIsEnumerable,mc=Object.getOwnPropertyDescriptor,qS=mc&&!fc.call({1:2},1);bc.f=qS?function(e){var t=mc(this,e);return!!t&&t.enumerable}:fc});var Ii=b((SL,gc)=>{"use strict";gc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Sc=b((yL,vc)=>{"use strict";var US=be(),HS=ye(),jS=ur(),Vn=Object,QS=US("".split);vc.exports=HS(function(){return!Vn("z").propertyIsEnumerable(0)})?function(a){return jS(a)==="String"?QS(a,""):Vn(a)}:Vn});var Cr=b((TL,yc)=>{"use strict";yc.exports=function(a){return a==null}});var Ht=b((IL,Tc)=>{"use strict";var GS=Cr(),WS=TypeError;Tc.exports=function(a){if(GS(a))throw new WS("Can't call method on "+a);return a}});var lr=b((EL,Ic)=>{"use strict";var YS=Sc(),zS=Ht();Ic.exports=function(a){return YS(zS(a))}});var Ue=b((xL,Ec)=>{"use strict";var KS=ce();Ec.exports=function(a){return typeof a=="object"?a!==null:KS(a)}});var Vr=b((PL,xc)=>{"use strict";xc.exports={}});var It=b((wL,wc)=>{"use strict";var On=Vr(),Bn=pe(),XS=ce(),Pc=function(a){return XS(a)?a:void 0};wc.exports=function(a,e){return arguments.length<2?Pc(On[a])||Pc(Bn[a]):On[a]&&On[a][e]||Bn[a]&&Bn[a][e]}});var Ei=b((AL,Ac)=>{"use strict";var JS=be();Ac.exports=JS({}.isPrototypeOf)});var cr=b((kL,Lc)=>{"use strict";var ZS=pe(),kc=ZS.navigator,Rc=kc&&kc.userAgent;Lc.exports=Rc?String(Rc):""});var Nn=b((RL,Oc)=>{"use strict";var Vc=pe(),_n=cr(),$c=Vc.process,Mc=Vc.Deno,Dc=$c&&$c.versions||Mc&&Mc.version,Cc=Dc&&Dc.v8,rt,os;Cc&&(rt=Cc.split("."),os=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!os&&_n&&(rt=_n.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=_n.match(/Chrome\/(\d+)/),rt&&(os=+rt[1])));Oc.exports=os});var Fn=b((LL,_c)=>{"use strict";var Bc=Nn(),ey=ye(),ty=pe(),ry=ty.String;_c.exports=!!Object.getOwnPropertySymbols&&!ey(function(){var a=Symbol("symbol detection");return!ry(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Bc&&Bc<41})});var qn=b(($L,Nc)=>{"use strict";var iy=Fn();Nc.exports=iy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Un=b((ML,Fc)=>{"use strict";var ay=It(),sy=ce(),ny=Ei(),oy=qn(),uy=Object;Fc.exports=oy?function(a){return typeof a=="symbol"}:function(a){var e=ay("Symbol");return sy(e)&&ny(e.prototype,uy(a))}});var xi=b((DL,qc)=>{"use strict";var ly=String;qc.exports=function(a){try{return ly(a)}catch(e){return"Object"}}});var pt=b((CL,Uc)=>{"use strict";var cy=ce(),dy=xi(),py=TypeError;Uc.exports=function(a){if(cy(a))return a;throw new py(dy(a)+" is not a function")}});var Pi=b((VL,Hc)=>{"use strict";var hy=pt(),fy=Cr();Hc.exports=function(a,e){var t=a[e];return fy(t)?void 0:hy(t)}});var Qc=b((OL,jc)=>{"use strict";var Hn=qe(),jn=ce(),Qn=Ue(),my=TypeError;jc.exports=function(a,e){var t,r;if(e==="string"&&jn(t=a.toString)&&!Qn(r=Hn(t,a))||jn(t=a.valueOf)&&!Qn(r=Hn(t,a))||e!=="string"&&jn(t=a.toString)&&!Qn(r=Hn(t,a)))return r;throw new my("Can't convert object to primitive value")}});var it=b((BL,Gc)=>{"use strict";Gc.exports=!0});var zc=b((_L,Yc)=>{"use strict";var Wc=pe(),by=Object.defineProperty;Yc.exports=function(a,e){try{by(Wc,a,{value:e,configurable:!0,writable:!0})}catch(t){Wc[a]=e}return e}});var wi=b((NL,Jc)=>{"use strict";var gy=it(),vy=pe(),Sy=zc(),Kc="__core-js_shared__",Xc=Jc.exports=vy[Kc]||Sy(Kc,{});(Xc.versions||(Xc.versions=[])).push({version:"3.38.0",mode:gy?"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 Gn=b((FL,ed)=>{"use strict";var Zc=wi();ed.exports=function(a,e){return Zc[a]||(Zc[a]=e||{})}});var Or=b((qL,td)=>{"use strict";var yy=Ht(),Ty=Object;td.exports=function(a){return Ty(yy(a))}});var at=b((UL,rd)=>{"use strict";var Iy=be(),Ey=Or(),xy=Iy({}.hasOwnProperty);rd.exports=Object.hasOwn||function(e,t){return xy(Ey(e),t)}});var Wn=b((HL,id)=>{"use strict";var Py=be(),wy=0,Ay=Math.random(),ky=Py(1 .toString);id.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+ky(++wy+Ay,36)}});var Te=b((jL,sd)=>{"use strict";var Ry=pe(),Ly=Gn(),ad=at(),$y=Wn(),My=Fn(),Dy=qn(),Br=Ry.Symbol,Yn=Ly("wks"),Cy=Dy?Br.for||Br:Br&&Br.withoutSetter||$y;sd.exports=function(a){return ad(Yn,a)||(Yn[a]=My&&ad(Br,a)?Br[a]:Cy("Symbol."+a)),Yn[a]}});var ld=b((QL,ud)=>{"use strict";var Vy=qe(),nd=Ue(),od=Un(),Oy=Pi(),By=Qc(),_y=Te(),Ny=TypeError,Fy=_y("toPrimitive");ud.exports=function(a,e){if(!nd(a)||od(a))return a;var t=Oy(a,Fy),r;if(t){if(e===void 0&&(e="default"),r=Vy(t,a,e),!nd(r)||od(r))return r;throw new Ny("Can't convert object to primitive value")}return e===void 0&&(e="number"),By(a,e)}});var zn=b((GL,cd)=>{"use strict";var qy=ld(),Uy=Un();cd.exports=function(a){var e=qy(a,"string");return Uy(e)?e:e+""}});var us=b((WL,pd)=>{"use strict";var Hy=pe(),dd=Ue(),Kn=Hy.document,jy=dd(Kn)&&dd(Kn.createElement);pd.exports=function(a){return jy?Kn.createElement(a):{}}});var Xn=b((YL,hd)=>{"use strict";var Qy=Fe(),Gy=ye(),Wy=us();hd.exports=!Qy&&!Gy(function(){return Object.defineProperty(Wy("div"),"a",{get:function(){return 7}}).a!==7})});var bd=b(md=>{"use strict";var Yy=Fe(),zy=qe(),Ky=Cn(),Xy=Ii(),Jy=lr(),Zy=zn(),eT=at(),tT=Xn(),fd=Object.getOwnPropertyDescriptor;md.f=Yy?fd:function(e,t){if(e=Jy(e),t=Zy(t),tT)try{return fd(e,t)}catch(r){}if(eT(e,t))return Xy(!zy(Ky.f,e,t),e[t])}});var Jn=b((KL,gd)=>{"use strict";var rT=ye(),iT=ce(),aT=/#|\.prototype\./,Ai=function(a,e){var t=nT[sT(a)];return t===uT?!0:t===oT?!1:iT(e)?rT(e):!!e},sT=Ai.normalize=function(a){return String(a).replace(aT,".").toLowerCase()},nT=Ai.data={},oT=Ai.NATIVE="N",uT=Ai.POLYFILL="P";gd.exports=Ai});var _r=b((XL,Sd)=>{"use strict";var vd=Mn(),lT=pt(),cT=Ti(),dT=vd(vd.bind);Sd.exports=function(a,e){return lT(a),e===void 0?a:cT?dT(a,e):function(){return a.apply(e,arguments)}}});var Zn=b((JL,yd)=>{"use strict";var pT=Fe(),hT=ye();yd.exports=pT&&hT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ht=b((ZL,Td)=>{"use strict";var fT=Ue(),mT=String,bT=TypeError;Td.exports=function(a){if(fT(a))return a;throw new bT(mT(a)+" is not an object")}});var dr=b(Ed=>{"use strict";var gT=Fe(),vT=Xn(),ST=Zn(),ls=ht(),Id=zn(),yT=TypeError,eo=Object.defineProperty,TT=Object.getOwnPropertyDescriptor,to="enumerable",ro="configurable",io="writable";Ed.f=gT?ST?function(e,t,r){if(ls(e),t=Id(t),ls(r),typeof e=="function"&&t==="prototype"&&"value"in r&&io in r&&!r[io]){var i=TT(e,t);i&&i[io]&&(e[t]=r.value,r={configurable:ro in r?r[ro]:i[ro],enumerable:to in r?r[to]:i[to],writable:!1})}return eo(e,t,r)}:eo:function(e,t,r){if(ls(e),t=Id(t),ls(r),vT)try{return eo(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new yT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Nr=b((t$,xd)=>{"use strict";var IT=Fe(),ET=dr(),xT=Ii();xd.exports=IT?function(a,e,t){return ET.f(a,e,xT(1,t))}:function(a,e,t){return a[e]=t,a}});var fe=b((r$,wd)=>{"use strict";var ki=pe(),PT=Ln(),wT=Mn(),AT=ce(),kT=bd().f,RT=Jn(),Fr=Vr(),LT=_r(),qr=Nr(),Pd=at();wi();var $T=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 PT(a,this,arguments)};return e.prototype=a.prototype,e};wd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ki:i?ki[t]:ki[t]&&ki[t].prototype,o=r?Fr:Fr[t]||qr(Fr,t,{})[t],u=o.prototype,l,c,d,p,h,m,g,v,I;for(p in e)l=RT(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Pd(n,p),m=o[p],c&&(a.dontCallGetSet?(I=kT(n,p),g=I&&I.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?v=LT(h,ki):a.wrap&&c?v=$T(h):s&&AT(h)?v=wT(h):v=h,(a.sham||h&&h.sham||m&&m.sham)&&qr(v,"sham",!0),qr(o,p,v),s&&(d=t+"Prototype",Pd(Fr,d)||qr(Fr,d,{}),qr(Fr[d],p,h),a.real&&u&&(l||!u[p])&&qr(u,p,h)))}});var kd=b((i$,Ad)=>{"use strict";var MT=Math.ceil,DT=Math.floor;Ad.exports=Math.trunc||function(e){var t=+e;return(t>0?DT:MT)(t)}});var Ri=b((a$,Rd)=>{"use strict";var CT=kd();Rd.exports=function(a){var e=+a;return e!==e||e===0?0:CT(e)}});var $d=b((s$,Ld)=>{"use strict";var VT=Ri(),OT=Math.max,BT=Math.min;Ld.exports=function(a,e){var t=VT(a);return t<0?OT(t+e,0):BT(t,e)}});var ao=b((n$,Md)=>{"use strict";var _T=Ri(),NT=Math.min;Md.exports=function(a){var e=_T(a);return e>0?NT(e,9007199254740991):0}});var Ur=b((o$,Dd)=>{"use strict";var FT=ao();Dd.exports=function(a){return FT(a.length)}});var so=b((u$,Vd)=>{"use strict";var qT=lr(),UT=$d(),HT=Ur(),Cd=function(a){return function(e,t,r){var i=qT(e),s=HT(i);if(s===0)return!a&&-1;var n=UT(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}};Vd.exports={includes:Cd(!0),indexOf:Cd(!1)}});var Li=b((l$,Od)=>{"use strict";Od.exports=function(){}});var Bd=b(()=>{"use strict";var jT=fe(),QT=so().includes,GT=ye(),WT=Li(),YT=GT(function(){return!Array(1).includes()});jT({target:"Array",proto:!0,forced:YT},{includes:function(e){return QT(this,e,arguments.length>1?arguments[1]:void 0)}});WT("includes")});var jt=b((p$,_d)=>{"use strict";var zT=It();_d.exports=zT});var Fd=b((h$,Nd)=>{"use strict";Bd();var KT=jt();Nd.exports=KT("Array","includes")});var Ud=b((f$,qd)=>{"use strict";var XT=Fd();qd.exports=XT});var st=b((m$,Hd)=>{"use strict";var JT=Ud();Hd.exports=JT});var ds=b((w$,Gd)=>{"use strict";var eI=Gn(),tI=Wn(),Qd=eI("keys");Gd.exports=function(a){return Qd[a]||(Qd[a]=tI(a))}});var Yd=b((A$,Wd)=>{"use strict";var rI=ye();Wd.exports=!rI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ps=b((k$,Kd)=>{"use strict";var iI=at(),aI=ce(),sI=Or(),nI=ds(),oI=Yd(),zd=nI("IE_PROTO"),no=Object,uI=no.prototype;Kd.exports=oI?no.getPrototypeOf:function(a){var e=sI(a);if(iI(e,zd))return e[zd];var t=e.constructor;return aI(t)&&e instanceof t?t.prototype:e instanceof no?uI:null}});var hs=b((R$,Xd)=>{"use strict";Xd.exports={}});var ep=b((L$,Zd)=>{"use strict";var lI=be(),oo=at(),cI=lr(),dI=so().indexOf,pI=hs(),Jd=lI([].push);Zd.exports=function(a,e){var t=cI(a),r=0,i=[],s;for(s in t)!oo(pI,s)&&oo(t,s)&&Jd(i,s);for(;e.length>r;)oo(t,s=e[r++])&&(~dI(i,s)||Jd(i,s));return i}});var uo=b(($$,tp)=>{"use strict";tp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var lo=b((M$,rp)=>{"use strict";var hI=ep(),fI=uo();rp.exports=Object.keys||function(e){return hI(e,fI)}});var co=b((D$,op)=>{"use strict";var ap=Fe(),mI=ye(),sp=be(),bI=ps(),gI=lo(),vI=lr(),SI=Cn().f,np=sp(SI),yI=sp([].push),TI=ap&&mI(function(){var a=Object.create(null);return a[2]=2,!np(a,2)}),ip=function(a){return function(e){for(var t=vI(e),r=gI(t),i=TI&&bI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!ap||(i?u in t:np(t,u)))&&yI(o,a?[u,t[u]]:t[u]);return o}};op.exports={entries:ip(!0),values:ip(!1)}});var up=b(()=>{"use strict";var II=fe(),EI=co().entries;II({target:"Object",stat:!0},{entries:function(e){return EI(e)}})});var cp=b((O$,lp)=>{"use strict";up();var xI=Vr();lp.exports=xI.Object.entries});var pp=b((B$,dp)=>{"use strict";var PI=cp();dp.exports=PI});var Hr=b((_$,hp)=>{"use strict";var wI=pp();hp.exports=wI});var pr=b((N$,fp)=>{"use strict";fp.exports={}});var gp=b((F$,bp)=>{"use strict";var AI=pe(),kI=ce(),mp=AI.WeakMap;bp.exports=kI(mp)&&/native code/.test(String(mp))});var mo=b((q$,yp)=>{"use strict";var RI=gp(),Sp=pe(),LI=Ue(),$I=Nr(),po=at(),ho=wi(),MI=ds(),DI=hs(),vp="Object already initialized",fo=Sp.TypeError,CI=Sp.WeakMap,fs,$i,ms,VI=function(a){return ms(a)?$i(a):fs(a,{})},OI=function(a){return function(e){var t;if(!LI(e)||(t=$i(e)).type!==a)throw new fo("Incompatible receiver, "+a+" required");return t}};RI||ho.state?(nt=ho.state||(ho.state=new CI),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,fs=function(a,e){if(nt.has(a))throw new fo(vp);return e.facade=a,nt.set(a,e),e},$i=function(a){return nt.get(a)||{}},ms=function(a){return nt.has(a)}):(hr=MI("state"),DI[hr]=!0,fs=function(a,e){if(po(a,hr))throw new fo(vp);return e.facade=a,$I(a,hr,e),e},$i=function(a){return po(a,hr)?a[hr]:{}},ms=function(a){return po(a,hr)});var nt,hr;yp.exports={set:fs,get:$i,has:ms,enforce:VI,getterFor:OI}});var vo=b((U$,Ip)=>{"use strict";var bo=Fe(),BI=at(),Tp=Function.prototype,_I=bo&&Object.getOwnPropertyDescriptor,go=BI(Tp,"name"),NI=go&&function(){}.name==="something",FI=go&&(!bo||bo&&_I(Tp,"name").configurable);Ip.exports={EXISTS:go,PROPER:NI,CONFIGURABLE:FI}});var xp=b(Ep=>{"use strict";var qI=Fe(),UI=Zn(),HI=dr(),jI=ht(),QI=lr(),GI=lo();Ep.f=qI&&!UI?Object.defineProperties:function(e,t){jI(e);for(var r=QI(t),i=GI(t),s=i.length,n=0,o;s>n;)HI.f(e,o=i[n++],r[o]);return e}});var So=b((j$,Pp)=>{"use strict";var WI=It();Pp.exports=WI("document","documentElement")});var Eo=b((Q$,Mp)=>{"use strict";var YI=ht(),zI=xp(),wp=uo(),KI=hs(),XI=So(),JI=us(),ZI=ds(),Ap=">",kp="<",To="prototype",Io="script",Lp=ZI("IE_PROTO"),yo=function(){},$p=function(a){return kp+Io+Ap+a+kp+"/"+Io+Ap},Rp=function(a){a.write($p("")),a.close();var e=a.parentWindow.Object;return a=null,e},eE=function(){var a=JI("iframe"),e="java"+Io+":",t;return a.style.display="none",XI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write($p("document.F=Object")),t.close(),t.F},bs,gs=function(){try{bs=new ActiveXObject("htmlfile")}catch(e){}gs=typeof document!="undefined"?document.domain&&bs?Rp(bs):eE():Rp(bs);for(var a=wp.length;a--;)delete gs[To][wp[a]];return gs()};KI[Lp]=!0;Mp.exports=Object.create||function(e,t){var r;return e!==null?(yo[To]=YI(e),r=new yo,yo[To]=null,r[Lp]=e):r=gs(),t===void 0?r:zI.f(r,t)}});var jr=b((G$,Dp)=>{"use strict";var tE=Nr();Dp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:tE(a,e,t),a}});var Ao=b((W$,Op)=>{"use strict";var rE=ye(),iE=ce(),aE=Ue(),sE=Eo(),Cp=ps(),nE=jr(),oE=Te(),uE=it(),wo=oE("iterator"),Vp=!1,Et,xo,Po;[].keys&&(Po=[].keys(),"next"in Po?(xo=Cp(Cp(Po)),xo!==Object.prototype&&(Et=xo)):Vp=!0);var lE=!aE(Et)||rE(function(){var a={};return Et[wo].call(a)!==a});lE?Et={}:uE&&(Et=sE(Et));iE(Et[wo])||nE(Et,wo,function(){return this});Op.exports={IteratorPrototype:Et,BUGGY_SAFARI_ITERATORS:Vp}});var vs=b((Y$,_p)=>{"use strict";var cE=Te(),dE=cE("toStringTag"),Bp={};Bp[dE]="z";_p.exports=String(Bp)==="[object z]"});var Mi=b((z$,Np)=>{"use strict";var pE=vs(),hE=ce(),Ss=ur(),fE=Te(),mE=fE("toStringTag"),bE=Object,gE=Ss(function(){return arguments}())==="Arguments",vE=function(a,e){try{return a[e]}catch(t){}};Np.exports=pE?Ss:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=vE(e=bE(a),mE))=="string"?t:gE?Ss(e):(r=Ss(e))==="Object"&&hE(e.callee)?"Arguments":r}});var qp=b((K$,Fp)=>{"use strict";var SE=vs(),yE=Mi();Fp.exports=SE?{}.toString:function(){return"[object "+yE(this)+"]"}});var Di=b((X$,Hp)=>{"use strict";var TE=vs(),IE=dr().f,EE=Nr(),xE=at(),PE=qp(),wE=Te(),Up=wE("toStringTag");Hp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(xE(i,Up)||IE(i,Up,{configurable:!0,value:e}),r&&!TE&&EE(i,"toString",PE))}});var Qp=b((J$,jp)=>{"use strict";var AE=Ao().IteratorPrototype,kE=Eo(),RE=Ii(),LE=Di(),$E=pr(),ME=function(){return this};jp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=kE(AE,{next:RE(+!r,t)}),LE(a,i,!1,!0),$E[i]=ME,a}});var Wp=b((Z$,Gp)=>{"use strict";var DE=be(),CE=pt();Gp.exports=function(a,e,t){try{return DE(CE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var zp=b((eM,Yp)=>{"use strict";var VE=Ue();Yp.exports=function(a){return VE(a)||a===null}});var Xp=b((tM,Kp)=>{"use strict";var OE=zp(),BE=String,_E=TypeError;Kp.exports=function(a){if(OE(a))return a;throw new _E("Can't set "+BE(a)+" as a prototype")}});var ko=b((rM,Jp)=>{"use strict";var NE=Wp(),FE=Ue(),qE=Ht(),UE=Xp();Jp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=NE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return qE(i),UE(s),FE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var lh=b((iM,uh)=>{"use strict";var HE=fe(),jE=qe(),ys=it(),nh=vo(),QE=ce(),GE=Qp(),Zp=ps(),eh=ko(),WE=Di(),YE=Nr(),Ro=jr(),zE=Te(),th=pr(),oh=Ao(),KE=nh.PROPER,XE=nh.CONFIGURABLE,rh=oh.IteratorPrototype,Ts=oh.BUGGY_SAFARI_ITERATORS,Ci=zE("iterator"),ih="keys",Vi="values",ah="entries",sh=function(){return this};uh.exports=function(a,e,t,r,i,s,n){GE(t,e,r);var o=function(I){if(I===i&&p)return p;if(!Ts&&I&&I in c)return c[I];switch(I){case ih:return function(){return new t(this,I)};case Vi:return function(){return new t(this,I)};case ah:return function(){return new t(this,I)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Ci]||c["@@iterator"]||i&&c[i],p=!Ts&&d||o(i),h=e==="Array"&&c.entries||d,m,g,v;if(h&&(m=Zp(h.call(new a)),m!==Object.prototype&&m.next&&(!ys&&Zp(m)!==rh&&(eh?eh(m,rh):QE(m[Ci])||Ro(m,Ci,sh)),WE(m,u,!0,!0),ys&&(th[u]=sh))),KE&&i===Vi&&d&&d.name!==Vi&&(!ys&&XE?YE(c,"name",Vi):(l=!0,p=function(){return jE(d,this)})),i)if(g={values:o(Vi),keys:s?p:o(ih),entries:o(ah)},n)for(v in g)(Ts||l||!(v in c))&&Ro(c,v,g[v]);else HE({target:e,proto:!0,forced:Ts||l},g);return(!ys||n)&&c[Ci]!==p&&Ro(c,Ci,p,{name:i}),th[e]=p,g}});var dh=b((aM,ch)=>{"use strict";ch.exports=function(a,e){return{value:a,done:e}}});var $o=b((sM,bh)=>{"use strict";var JE=lr(),Lo=Li(),ph=pr(),fh=mo(),ZE=dr().f,ex=lh(),Is=dh(),tx=it(),rx=Fe(),mh="Array Iterator",ix=fh.set,ax=fh.getterFor(mh);bh.exports=ex(Array,"Array",function(a,e){ix(this,{type:mh,target:JE(a),index:0,kind:e})},function(){var a=ax(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Is(void 0,!0);switch(a.kind){case"keys":return Is(t,!1);case"values":return Is(e[t],!1)}return Is([t,e[t]],!1)},"values");var hh=ph.Arguments=ph.Array;Lo("keys");Lo("values");Lo("entries");if(!tx&&rx&&hh.name!=="values")try{ZE(hh,"name",{value:"values"})}catch(a){}});var vh=b((nM,gh)=>{"use strict";var sx=Te(),nx=pr(),ox=sx("iterator"),ux=Array.prototype;gh.exports=function(a){return a!==void 0&&(nx.Array===a||ux[ox]===a)}});var Mo=b((oM,yh)=>{"use strict";var lx=Mi(),Sh=Pi(),cx=Cr(),dx=pr(),px=Te(),hx=px("iterator");yh.exports=function(a){if(!cx(a))return Sh(a,hx)||Sh(a,"@@iterator")||dx[lx(a)]}});var Ih=b((uM,Th)=>{"use strict";var fx=qe(),mx=pt(),bx=ht(),gx=xi(),vx=Mo(),Sx=TypeError;Th.exports=function(a,e){var t=arguments.length<2?vx(a):e;if(mx(t))return bx(fx(t,a));throw new Sx(gx(a)+" is not iterable")}});var Ph=b((lM,xh)=>{"use strict";var yx=qe(),Eh=ht(),Tx=Pi();xh.exports=function(a,e,t){var r,i;Eh(a);try{if(r=Tx(a,"return"),!r){if(e==="throw")throw t;return t}r=yx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Eh(r),t}});var xs=b((cM,Rh)=>{"use strict";var Ix=_r(),Ex=qe(),xx=ht(),Px=xi(),wx=vh(),Ax=Ur(),wh=Ei(),kx=Ih(),Rx=Mo(),Ah=Ph(),Lx=TypeError,Es=function(a,e){this.stopped=a,this.result=e},kh=Es.prototype;Rh.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=Ix(e,r),l,c,d,p,h,m,g,v=function(E){return l&&Ah(l,"normal",E),new Es(!0,E)},I=function(E){return i?(xx(E),o?u(E[0],E[1],v):u(E[0],E[1])):o?u(E,v):u(E)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Rx(a),!c)throw new Lx(Px(a)+" is not iterable");if(wx(c)){for(d=0,p=Ax(a);p>d;d++)if(h=I(a[d]),h&&wh(kh,h))return h;return new Es(!1)}l=kx(a,c)}for(m=s?a.next:l.next;!(g=Ex(m,l)).done;){try{h=I(g.value)}catch(E){Ah(l,"throw",E)}if(typeof h=="object"&&h&&wh(kh,h))return h}return new Es(!1)}});var $h=b((dM,Lh)=>{"use strict";var $x=Fe(),Mx=dr(),Dx=Ii();Lh.exports=function(a,e,t){$x?Mx.f(a,e,Dx(0,t)):a[e]=t}});var Mh=b(()=>{"use strict";var Cx=fe(),Vx=xs(),Ox=$h();Cx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Vx(e,function(r,i){Ox(t,r,i)},{AS_ENTRIES:!0}),t}})});var Ch=b((fM,Dh)=>{"use strict";$o();Mh();var Bx=Vr();Dh.exports=Bx.Object.fromEntries});var Oh=b((mM,Vh)=>{"use strict";Vh.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 _h=b(()=>{"use strict";$o();var _x=Oh(),Nx=pe(),Fx=Di(),Bh=pr();for(Ps in _x)Fx(Nx[Ps],Ps),Bh[Ps]=Bh.Array;var Ps});var Fh=b((vM,Nh)=>{"use strict";var qx=Ch();_h();Nh.exports=qx});var Do=b((SM,qh)=>{"use strict";var Ux=Fh();qh.exports=Ux});var Uh=b(()=>{"use strict"});var Co=b((IM,Hh)=>{"use strict";var Oi=pe(),Hx=cr(),jx=ur(),ws=function(a){return Hx.slice(0,a.length)===a};Hh.exports=function(){return ws("Bun/")?"BUN":ws("Cloudflare-Workers")?"CLOUDFLARE":ws("Deno/")?"DENO":ws("Node.js/")?"NODE":Oi.Bun&&typeof Bun.version=="string"?"BUN":Oi.Deno&&typeof Deno.version=="object"?"DENO":jx(Oi.process)==="process"?"NODE":Oi.window&&Oi.document?"BROWSER":"REST"}()});var As=b((EM,jh)=>{"use strict";var Qx=Co();jh.exports=Qx==="NODE"});var Gh=b((xM,Qh)=>{"use strict";var Gx=dr();Qh.exports=function(a,e,t){return Gx.f(a,e,t)}});var zh=b((PM,Yh)=>{"use strict";var Wx=It(),Yx=Gh(),zx=Te(),Kx=Fe(),Wh=zx("species");Yh.exports=function(a){var e=Wx(a);Kx&&e&&!e[Wh]&&Yx(e,Wh,{configurable:!0,get:function(){return this}})}});var Xh=b((wM,Kh)=>{"use strict";var Xx=Ei(),Jx=TypeError;Kh.exports=function(a,e){if(Xx(e,a))return a;throw new Jx("Incorrect invocation")}});var Oo=b((AM,Jh)=>{"use strict";var Zx=be(),eP=ce(),Vo=wi(),tP=Zx(Function.toString);eP(Vo.inspectSource)||(Vo.inspectSource=function(a){return tP(a)});Jh.exports=Vo.inspectSource});var _o=b((kM,af)=>{"use strict";var rP=be(),iP=ye(),Zh=ce(),aP=Mi(),sP=It(),nP=Oo(),ef=function(){},tf=sP("Reflect","construct"),Bo=/^\s*(?:class|function)\b/,oP=rP(Bo.exec),uP=!Bo.test(ef),Bi=function(e){if(!Zh(e))return!1;try{return tf(ef,[],e),!0}catch(t){return!1}},rf=function(e){if(!Zh(e))return!1;switch(aP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return uP||!!oP(Bo,nP(e))}catch(t){return!0}};rf.sham=!0;af.exports=!tf||iP(function(){var a;return Bi(Bi.call)||!Bi(Object)||!Bi(function(){a=!0})||a})?rf:Bi});var nf=b((RM,sf)=>{"use strict";var lP=_o(),cP=xi(),dP=TypeError;sf.exports=function(a){if(lP(a))return a;throw new dP(cP(a)+" is not a constructor")}});var No=b((LM,uf)=>{"use strict";var of=ht(),pP=nf(),hP=Cr(),fP=Te(),mP=fP("species");uf.exports=function(a,e){var t=of(a).constructor,r;return t===void 0||hP(r=of(t)[mP])?e:pP(r)}});var cf=b(($M,lf)=>{"use strict";var bP=be();lf.exports=bP([].slice)});var pf=b((MM,df)=>{"use strict";var gP=TypeError;df.exports=function(a,e){if(a<e)throw new gP("Not enough arguments");return a}});var Fo=b((DM,hf)=>{"use strict";var vP=cr();hf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(vP)});var zo=b((CM,If)=>{"use strict";var He=pe(),SP=Ln(),yP=_r(),ff=ce(),TP=at(),Tf=ye(),mf=So(),IP=cf(),bf=us(),EP=pf(),xP=Fo(),PP=As(),Go=He.setImmediate,Wo=He.clearImmediate,wP=He.process,qo=He.Dispatch,AP=He.Function,gf=He.MessageChannel,kP=He.String,Uo=0,_i={},vf="onreadystatechange",Ni,fr,Ho,jo;Tf(function(){Ni=He.location});var Yo=function(a){if(TP(_i,a)){var e=_i[a];delete _i[a],e()}},Qo=function(a){return function(){Yo(a)}},Sf=function(a){Yo(a.data)},yf=function(a){He.postMessage(kP(a),Ni.protocol+"//"+Ni.host)};(!Go||!Wo)&&(Go=function(e){EP(arguments.length,1);var t=ff(e)?e:AP(e),r=IP(arguments,1);return _i[++Uo]=function(){SP(t,void 0,r)},fr(Uo),Uo},Wo=function(e){delete _i[e]},PP?fr=function(a){wP.nextTick(Qo(a))}:qo&&qo.now?fr=function(a){qo.now(Qo(a))}:gf&&!xP?(Ho=new gf,jo=Ho.port2,Ho.port1.onmessage=Sf,fr=yP(jo.postMessage,jo)):He.addEventListener&&ff(He.postMessage)&&!He.importScripts&&Ni&&Ni.protocol!=="file:"&&!Tf(yf)?(fr=yf,He.addEventListener("message",Sf,!1)):vf in bf("script")?fr=function(a){mf.appendChild(bf("script"))[vf]=function(){mf.removeChild(this),Yo(a)}}:fr=function(a){setTimeout(Qo(a),0)});If.exports={set:Go,clear:Wo}});var Pf=b((VM,xf)=>{"use strict";var Ef=pe(),RP=Fe(),LP=Object.getOwnPropertyDescriptor;xf.exports=function(a){if(!RP)return Ef[a];var e=LP(Ef,a);return e&&e.value}});var Ko=b((OM,Af)=>{"use strict";var wf=function(){this.head=null,this.tail=null};wf.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}}};Af.exports=wf});var Rf=b((BM,kf)=>{"use strict";var $P=cr();kf.exports=/ipad|iphone|ipod/i.test($P)&&typeof Pebble!="undefined"});var $f=b((_M,Lf)=>{"use strict";var MP=cr();Lf.exports=/web0s(?!.*chrome)/i.test(MP)});var _f=b((NM,Bf)=>{"use strict";var Gr=pe(),DP=Pf(),Mf=_r(),Xo=zo().set,CP=Ko(),VP=Fo(),OP=Rf(),BP=$f(),Jo=As(),Df=Gr.MutationObserver||Gr.WebKitMutationObserver,Cf=Gr.document,Vf=Gr.process,ks=Gr.Promise,tu=DP("queueMicrotask"),Qr,Zo,eu,Rs,Of;tu||(Fi=new CP,qi=function(){var a,e;for(Jo&&(a=Vf.domain)&&a.exit();e=Fi.get();)try{e()}catch(t){throw Fi.head&&Qr(),t}a&&a.enter()},!VP&&!Jo&&!BP&&Df&&Cf?(Zo=!0,eu=Cf.createTextNode(""),new Df(qi).observe(eu,{characterData:!0}),Qr=function(){eu.data=Zo=!Zo}):!OP&&ks&&ks.resolve?(Rs=ks.resolve(void 0),Rs.constructor=ks,Of=Mf(Rs.then,Rs),Qr=function(){Of(qi)}):Jo?Qr=function(){Vf.nextTick(qi)}:(Xo=Mf(Xo,Gr),Qr=function(){Xo(qi)}),tu=function(a){Fi.head||Qr(),Fi.add(a)});var Fi,qi;Bf.exports=tu});var Ff=b((FM,Nf)=>{"use strict";Nf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ls=b((qM,qf)=>{"use strict";qf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var mr=b((UM,Uf)=>{"use strict";var _P=pe();Uf.exports=_P.Promise});var Wr=b((HM,Gf)=>{"use strict";var NP=pe(),Ui=mr(),FP=ce(),qP=Jn(),UP=Oo(),HP=Te(),Hf=Co(),jP=it(),ru=Nn(),jf=Ui&&Ui.prototype,QP=HP("species"),iu=!1,Qf=FP(NP.PromiseRejectionEvent),GP=qP("Promise",function(){var a=UP(Ui),e=a!==String(Ui);if(!e&&ru===66||jP&&!(jf.catch&&jf.finally))return!0;if(!ru||ru<51||!/native code/.test(a)){var t=new Ui(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[QP]=r,iu=t.then(function(){})instanceof r,!iu)return!0}return!e&&(Hf==="BROWSER"||Hf==="DENO")&&!Qf});Gf.exports={CONSTRUCTOR:GP,REJECTION_EVENT:Qf,SUBCLASSING:iu}});var Yr=b((jM,Yf)=>{"use strict";var Wf=pt(),WP=TypeError,YP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new WP("Bad Promise constructor");e=r,t=i}),this.resolve=Wf(e),this.reject=Wf(t)};Yf.exports.f=function(a){return new YP(a)}});var hm=b(()=>{"use strict";var zP=fe(),KP=it(),Cs=As(),Qt=pe(),Jr=qe(),zf=jr(),Kf=ko(),XP=Di(),JP=zh(),ZP=pt(),Ds=ce(),ew=Ue(),tw=Xh(),rw=No(),tm=zo().set,uu=_f(),iw=Ff(),aw=Ls(),sw=Ko(),rm=mo(),Vs=mr(),lu=Wr(),im=Yr(),Os="Promise",am=lu.CONSTRUCTOR,nw=lu.REJECTION_EVENT,ow=lu.SUBCLASSING,au=rm.getterFor(Os),uw=rm.set,zr=Vs&&Vs.prototype,br=Vs,$s=zr,sm=Qt.TypeError,su=Qt.document,cu=Qt.process,nu=im.f,lw=nu,cw=!!(su&&su.createEvent&&Qt.dispatchEvent),nm="unhandledrejection",dw="rejectionhandled",Xf=0,om=1,pw=2,du=1,um=2,Ms,Jf,hw,Zf,lm=function(a){var e;return ew(a)&&Ds(e=a.then)?e:!1},cm=function(a,e){var t=e.value,r=e.state===om,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===um&&mw(e),e.rejection=du),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new sm("Promise-chain cycle")):(l=lm(u))?Jr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},dm=function(a,e){a.notified||(a.notified=!0,uu(function(){for(var t=a.reactions,r;r=t.get();)cm(r,a);a.notified=!1,e&&!a.rejection&&fw(a)}))},pm=function(a,e,t){var r,i;cw?(r=su.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Qt.dispatchEvent(r)):r={promise:e,reason:t},!nw&&(i=Qt["on"+a])?i(r):a===nm&&iw("Unhandled promise rejection",t)},fw=function(a){Jr(tm,Qt,function(){var e=a.facade,t=a.value,r=em(a),i;if(r&&(i=aw(function(){Cs?cu.emit("unhandledRejection",t,e):pm(nm,e,t)}),a.rejection=Cs||em(a)?um:du,i.error))throw i.value})},em=function(a){return a.rejection!==du&&!a.parent},mw=function(a){Jr(tm,Qt,function(){var e=a.facade;Cs?cu.emit("rejectionHandled",e):pm(dw,e,a.value)})},Kr=function(a,e,t){return function(r){a(e,r,t)}},Xr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=pw,dm(a,!0))},ou=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new sm("Promise can't be resolved itself");var r=lm(e);r?uu(function(){var i={done:!1};try{Jr(r,e,Kr(ou,i,a),Kr(Xr,i,a))}catch(s){Xr(i,s,a)}}):(a.value=e,a.state=om,dm(a,!1))}catch(i){Xr({done:!1},i,a)}}};if(am&&(br=function(e){tw(this,$s),ZP(e),Jr(Ms,this);var t=au(this);try{e(Kr(ou,t),Kr(Xr,t))}catch(r){Xr(t,r)}},$s=br.prototype,Ms=function(e){uw(this,{type:Os,done:!1,notified:!1,parent:!1,reactions:new sw,rejection:!1,state:Xf,value:void 0})},Ms.prototype=zf($s,"then",function(e,t){var r=au(this),i=nu(rw(this,br));return r.parent=!0,i.ok=Ds(e)?e:!0,i.fail=Ds(t)&&t,i.domain=Cs?cu.domain:void 0,r.state===Xf?r.reactions.add(i):uu(function(){cm(i,r)}),i.promise}),Jf=function(){var a=new Ms,e=au(a);this.promise=a,this.resolve=Kr(ou,e),this.reject=Kr(Xr,e)},im.f=nu=function(a){return a===br||a===hw?new Jf(a):lw(a)},!KP&&Ds(Vs)&&zr!==Object.prototype)){Zf=zr.then,ow||zf(zr,"then",function(e,t){var r=this;return new br(function(i,s){Jr(Zf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete zr.constructor}catch(a){}Kf&&Kf(zr,$s)}zP({global:!0,constructor:!0,wrap:!0,forced:am},{Promise:br});XP(br,Os,!1,!0);JP(Os)});var vm=b((WM,gm)=>{"use strict";var bw=Te(),mm=bw("iterator"),bm=!1;try{fm=0,pu={next:function(){return{done:!!fm++}},return:function(){bm=!0}},pu[mm]=function(){return this},Array.from(pu,function(){throw 2})}catch(a){}var fm,pu;gm.exports=function(a,e){try{if(!e&&!bm)return!1}catch(i){return!1}var t=!1;try{var r={};r[mm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var hu=b((YM,Sm)=>{"use strict";var gw=mr(),vw=vm(),Sw=Wr().CONSTRUCTOR;Sm.exports=Sw||!vw(function(a){gw.all(a).then(void 0,function(){})})});var ym=b(()=>{"use strict";var yw=fe(),Tw=qe(),Iw=pt(),Ew=Yr(),xw=Ls(),Pw=xs(),ww=hu();yw({target:"Promise",stat:!0,forced:ww},{all:function(e){var t=this,r=Ew.f(t),i=r.resolve,s=r.reject,n=xw(function(){var o=Iw(t.resolve),u=[],l=0,c=1;Pw(e,function(d){var p=l++,h=!1;c++,Tw(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Im=b(()=>{"use strict";var Aw=fe(),kw=it(),Rw=Wr().CONSTRUCTOR,mu=mr(),Lw=It(),$w=ce(),Mw=jr(),Tm=mu&&mu.prototype;Aw({target:"Promise",proto:!0,forced:Rw,real:!0},{catch:function(a){return this.then(void 0,a)}});!kw&&$w(mu)&&(fu=Lw("Promise").prototype.catch,Tm.catch!==fu&&Mw(Tm,"catch",fu,{unsafe:!0}));var fu});var Em=b(()=>{"use strict";var Dw=fe(),Cw=qe(),Vw=pt(),Ow=Yr(),Bw=Ls(),_w=xs(),Nw=hu();Dw({target:"Promise",stat:!0,forced:Nw},{race:function(e){var t=this,r=Ow.f(t),i=r.reject,s=Bw(function(){var n=Vw(t.resolve);_w(e,function(o){Cw(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var xm=b(()=>{"use strict";var Fw=fe(),qw=Yr(),Uw=Wr().CONSTRUCTOR;Fw({target:"Promise",stat:!0,forced:Uw},{reject:function(e){var t=qw.f(this),r=t.reject;return r(e),t.promise}})});var bu=b((iD,Pm)=>{"use strict";var Hw=ht(),jw=Ue(),Qw=Yr();Pm.exports=function(a,e){if(Hw(a),jw(e)&&e.constructor===a)return e;var t=Qw.f(a),r=t.resolve;return r(e),t.promise}});var km=b(()=>{"use strict";var Gw=fe(),Ww=It(),wm=it(),Yw=mr(),Am=Wr().CONSTRUCTOR,zw=bu(),Kw=Ww("Promise"),Xw=wm&&!Am;Gw({target:"Promise",stat:!0,forced:wm||Am},{resolve:function(e){return zw(Xw&&this===Kw?Yw:this,e)}})});var Rm=b(()=>{"use strict";hm();ym();Im();Em();xm();km()});var Dm=b(()=>{"use strict";var Jw=fe(),Zw=it(),Bs=mr(),eA=ye(),$m=It(),Mm=ce(),tA=No(),Lm=bu(),rA=jr(),vu=Bs&&Bs.prototype,iA=!!Bs&&eA(function(){vu.finally.call({then:function(){}},function(){})});Jw({target:"Promise",proto:!0,real:!0,forced:iA},{finally:function(a){var e=tA(this,$m("Promise")),t=Mm(a);return this.then(t?function(r){return Lm(e,a()).then(function(){return r})}:a,t?function(r){return Lm(e,a()).then(function(){throw r})}:a)}});!Zw&&Mm(Bs)&&(gu=$m("Promise").prototype.finally,vu.finally!==gu&&rA(vu,"finally",gu,{unsafe:!0}));var gu});var Vm=b((cD,Cm)=>{"use strict";Uh();Rm();Dm();var aA=jt();Cm.exports=aA("Promise","finally")});var Bm=b((dD,Om)=>{"use strict";var sA=Vm();Om.exports=sA});var _s=b((pD,_m)=>{"use strict";var nA=Bm();_m.exports=nA});var Qm=b(()=>{"use strict";var dA=fe(),pA=co().values;dA({target:"Object",stat:!0},{values:function(e){return pA(e)}})});var Wm=b((HD,Gm)=>{"use strict";Qm();var hA=Vr();Gm.exports=hA.Object.values});var zm=b((jD,Ym)=>{"use strict";var fA=Wm();Ym.exports=fA});var Zr=b((QD,Km)=>{"use strict";var mA=zm();Km.exports=mA});var eb=b(()=>{"use strict";var SA=fe(),yA=Or(),TA=Ur(),IA=Ri(),EA=Li();SA({target:"Array",proto:!0},{at:function(e){var t=yA(this),r=TA(t),i=IA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});EA("at")});var rb=b((mC,tb)=>{"use strict";eb();var xA=jt();tb.exports=xA("Array","at")});var ab=b((bC,ib)=>{"use strict";var PA=rb();ib.exports=PA});var ei=b((gC,sb)=>{"use strict";var wA=ab();sb.exports=wA});var Vu=b((U0,wb)=>{"use strict";var _A=ur();wb.exports=Array.isArray||function(e){return _A(e)==="Array"}});var kb=b((H0,Ab)=>{"use strict";var NA=TypeError,FA=9007199254740991;Ab.exports=function(a){if(a>FA)throw NA("Maximum allowed index exceeded");return a}});var $b=b((j0,Lb)=>{"use strict";var qA=Vu(),UA=Ur(),HA=kb(),jA=_r(),Rb=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?jA(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&qA(d)?(p=UA(d),u=Rb(a,e,d,p,u,s-1)-1):(HA(u+1),a[u]=d),u++),l++;return u};Lb.exports=Rb});var Vb=b((Q0,Cb)=>{"use strict";var Mb=Vu(),QA=_o(),GA=Ue(),WA=Te(),YA=WA("species"),Db=Array;Cb.exports=function(a){var e;return Mb(a)&&(e=a.constructor,QA(e)&&(e===Db||Mb(e.prototype))?e=void 0:GA(e)&&(e=e[YA],e===null&&(e=void 0))),e===void 0?Db:e}});var Bb=b((G0,Ob)=>{"use strict";var zA=Vb();Ob.exports=function(a,e){return new(zA(a))(e===0?0:e)}});var _b=b(()=>{"use strict";var KA=fe(),XA=$b(),JA=pt(),ZA=Or(),ek=Ur(),tk=Bb();KA({target:"Array",proto:!0},{flatMap:function(e){var t=ZA(this),r=ek(t),i;return JA(e),i=tk(t,0),i.length=XA(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Nb=b(()=>{"use strict";var rk=Li();rk("flatMap")});var qb=b((X0,Fb)=>{"use strict";_b();Nb();var ik=jt();Fb.exports=ik("Array","flatMap")});var Hb=b((J0,Ub)=>{"use strict";var ak=qb();Ub.exports=ak});var Ou=b((Z0,jb)=>{"use strict";var sk=Hb();jb.exports=sk});var ea=b((uV,cg)=>{"use strict";var hk=Mi(),fk=String;cg.exports=function(a){if(hk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fk(a)}});var _u=b((lV,dg)=>{"use strict";dg.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 fg=b((cV,hg)=>{"use strict";var mk=be(),bk=Ht(),gk=ea(),Fu=_u(),pg=mk("".replace),vk=RegExp("^["+Fu+"]+"),Sk=RegExp("(^|[^"+Fu+"])["+Fu+"]+$"),Nu=function(a){return function(e){var t=gk(bk(e));return a&1&&(t=pg(t,vk,"")),a&2&&(t=pg(t,Sk,"$1")),t}};hg.exports={start:Nu(1),end:Nu(2),trim:Nu(3)}});var vg=b((dV,gg)=>{"use strict";var yk=vo().PROPER,Tk=ye(),mg=_u(),bg="\u200B\x85\u180E";gg.exports=function(a){return Tk(function(){return!!mg[a]()||bg[a]()!==bg||yk&&mg[a].name!==a})}});var qu=b((pV,Sg)=>{"use strict";var Ik=fg().start,Ek=vg();Sg.exports=Ek("trimStart")?function(){return Ik(this)}:"".trimStart});var Tg=b(()=>{"use strict";var xk=fe(),yg=qu();xk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==yg},{trimLeft:yg})});var Eg=b(()=>{"use strict";Tg();var Pk=fe(),Ig=qu();Pk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ig},{trimStart:Ig})});var Pg=b((gV,xg)=>{"use strict";Eg();var wk=jt();xg.exports=wk("String","trimLeft")});var Ag=b((vV,wg)=>{"use strict";var Ak=Pg();wg.exports=Ak});var Rg=b((SV,kg)=>{"use strict";var kk=Ag();kg.exports=kk});var Hg=b(()=>{"use strict"});var jg=b(()=>{"use strict"});var Gg=b((NB,Qg)=>{"use strict";var Yk=Ue(),zk=ur(),Kk=Te(),Xk=Kk("match");Qg.exports=function(a){var e;return Yk(a)&&((e=a[Xk])!==void 0?!!e:zk(a)==="RegExp")}});var Yg=b((FB,Wg)=>{"use strict";var Jk=ht();Wg.exports=function(){var a=Jk(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 Xg=b((qB,Kg)=>{"use strict";var Zk=qe(),eR=at(),tR=Ei(),rR=Yg(),zg=RegExp.prototype;Kg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in zg)&&!eR(a,"flags")&&tR(zg,a)?Zk(rR,a):e}});var Zg=b((UB,Jg)=>{"use strict";var Yu=be(),iR=Or(),aR=Math.floor,Gu=Yu("".charAt),sR=Yu("".replace),Wu=Yu("".slice),nR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,oR=/\$([$&'`]|\d{1,2})/g;Jg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=oR;return i!==void 0&&(i=iR(i),u=nR),sR(s,u,function(l,c){var d;switch(Gu(c,0)){case"$":return"$";case"&":return a;case"`":return Wu(e,0,t);case"'":return Wu(e,n);case"<":d=i[Wu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=aR(p/10);return h===0?l:h<=o?r[h-1]===void 0?Gu(c,1):r[h-1]+Gu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var rv=b(()=>{"use strict";var uR=fe(),lR=qe(),Ku=be(),ev=Ht(),cR=ce(),dR=Cr(),pR=Gg(),oi=ea(),hR=Pi(),fR=Xg(),mR=Zg(),bR=Te(),gR=it(),vR=bR("replace"),SR=TypeError,zu=Ku("".indexOf),yR=Ku("".replace),tv=Ku("".slice),TR=Math.max;uR({target:"String",proto:!0},{replaceAll:function(e,t){var r=ev(this),i,s,n,o,u,l,c,d,p,h,m=0,g="";if(!dR(e)){if(i=pR(e),i&&(s=oi(ev(fR(e))),!~zu(s,"g")))throw new SR("`.replaceAll` does not allow non-global regexes");if(n=hR(e,vR),n)return lR(n,e,r,t);if(gR&&i)return yR(oi(r),e,t)}for(o=oi(r),u=oi(e),l=cR(t),l||(t=oi(t)),c=u.length,d=TR(1,c),p=zu(o,u);p!==-1;)h=l?oi(t(u,p,o)):mR(u,o,p,[],void 0,t),g+=tv(o,m,p)+h,m=p+c,p=p+d>o.length?-1:zu(o,u,p+d);return m<o.length&&(g+=tv(o,m)),g}})});var av=b((QB,iv)=>{"use strict";Hg();jg();rv();var IR=jt();iv.exports=IR("String","replaceAll")});var nv=b((GB,sv)=>{"use strict";var ER=av();sv.exports=ER});var uv=b((WB,ov)=>{"use strict";var xR=nv();ov.exports=xR});var cv=b((YB,lv)=>{"use strict";var PR=Ri(),wR=ea(),AR=Ht(),kR=RangeError;lv.exports=function(e){var t=wR(AR(this)),r="",i=PR(e);if(i<0||i===1/0)throw new kR("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var mv=b((zB,fv)=>{"use strict";var hv=be(),RR=ao(),dv=ea(),LR=cv(),$R=Ht(),MR=hv(LR),DR=hv("".slice),CR=Math.ceil,pv=function(a){return function(e,t,r){var i=dv($R(e)),s=RR(t),n=i.length,o=r===void 0?" ":dv(r),u,l;return s<=n||o===""?i:(u=s-n,l=MR(o,CR(u/o.length)),l.length>u&&(l=DR(l,0,u)),a?i+l:l+i)}};fv.exports={start:pv(!1),end:pv(!0)}});var gv=b((KB,bv)=>{"use strict";var VR=cr();bv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(VR)});var vv=b(()=>{"use strict";var OR=fe(),BR=mv().start,_R=gv();OR({target:"String",proto:!0,forced:_R},{padStart:function(e){return BR(this,e,arguments.length>1?arguments[1]:void 0)}})});var yv=b((ZB,Sv)=>{"use strict";vv();var NR=jt();Sv.exports=NR("String","padStart")});var Iv=b((e_,Tv)=>{"use strict";var FR=yv();Tv.exports=FR});var xv=b((t_,Ev)=>{"use strict";var qR=Iv();Ev.exports=qR});var sL={};LS(sL,{ChromecastState:()=>Si,HttpConnectionType:()=>as,Observable:()=>St.Observable,PlaybackState:()=>Ae,Player:()=>ja,PredefinedQualityLimits:()=>Dr,SDK_VERSION:()=>aL,Subject:()=>St.Subject,Subscription:()=>St.Subscription,Surface:()=>ss,VERSION:()=>kn,ValueSubject:()=>St.ValueSubject,VideoFormat:()=>Tt,VideoQuality:()=>St.VideoQuality});module.exports=$S(sL);var kn="2.0.124-dev.d93f994c.0";var Ae=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Ae||{}),Tt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(Tt||{});var Si=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Si||{}),as=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(as||{});var ss=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ss||{}),Dr=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(Dr||{});var bS=G(st(),1);var N=require("@vkontakte/videoplayer-shared/es2018");var jd=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var cs=class{constructor(e){this.connection$=new N.ValueSubject(void 0);this.castState$=new N.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new N.Subject;this.realCastState$=new N.ValueSubject("NOT_AVAILABLE");this.subscription=new N.Subscription;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,N.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||jd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:N.ErrorCategory.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(){(0,N.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,N.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,N.fromEvent)(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(0,N.assertNever)(i.sessionState)}})).add((0,N.merge)((0,N.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,N.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,N.map)(i=>i.castState)),(0,N.observableFrom)([r.getCastState()])).pipe((0,N.filterChanged)(),(0,N.map)(ZT),(0,N.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,N.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,N.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,N.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,N.isNonNullable)(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:N.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},ZT=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(0,N.assertNever)(a)}};var ml=G(st(),1),iS=G(Hr(),1),aS=G(Do(),1);var Um=G(_s(),1);var Su=require("@vkontakte/videoplayer-shared/es2018");var Ie=(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:(0,Su.assertNever)(t)}return a},Ns=(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:(0,Su.assertNever)(e)}};var A=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var ft=require("@vkontakte/videoplayer-shared/es2018"),q=class{constructor(e){this.transitionStarted$=new ft.Subject;this.transitionEnded$=new ft.Subject;this.transitionUpdated$=new ft.Subject;this.forceChanged$=new ft.Subject;this.stateChangeStarted$=(0,ft.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,ft.merge)(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||(0,ft.isNonNullable)(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}};var Nm=require("@vkontakte/videoplayer-shared/es2018"),Fm=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(0,Nm.assertNever)(a)}};var L=require("@vkontakte/videoplayer-shared/es2018");var oA=5,uA=5,lA=500,qm=7e3,Hi=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new q("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:(0,L.assertNever)(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:(0,L.assertNever)(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:(0,L.assertNever)(e)}break}default:(0,L.assertNever)(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Fm(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 L.Subscription;this.subscription.add(e),this.subscription.add((0,L.merge)(this.videoState.stateChangeStarted$.pipe((0,L.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,L.map)(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 L.Subject;e.add(i.pipe((0,L.debounce)(lA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,L.fromEvent)(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)>oA)&&i.next(o),s=o})),e.add((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,L.fromEvent)(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<uA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(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:(0,L.assertNever)(n)}}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,L.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,L.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,L.observableFrom)(["init"])).pipe((0,L.debounce)(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"),A(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),A(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];(0,L.assertNonNullable)(c);let d=(0,L.getHighestQuality)(Object.keys(c));(0,L.assertNonNullable)(d);let p=c[d];(0,L.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),r=Ie(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,L.assertNever)(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(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(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((0,L.timeout)(qm).subscribe(()=>s(`timeout(${qm})`)))});(0,Um.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:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Du=G(st(),1);var Eu=require("@vkontakte/videoplayer-shared/es2018");var Hm=require("@vkontakte/videoplayer-shared/es2018"),jm=a=>{try{a.pause(),a.playbackRate=0,(0,Hm.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Fs=require("@vkontakte/videoplayer-shared/es2018"),yu=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)}},Tu=window.WeakMap?new WeakMap:new yu,Iu=window.WeakMap?new WeakMap:new Map,cA=(a,e=20)=>{let t=0;return(0,Fs.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},$e=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Eu.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),Tu.set(t,r);let i=new Fs.Subscription;return i.add(cA(t,e)),Iu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Me=a=>{let e=Iu.get(a);e==null||e.unsubscribe(),Iu.delete(a);let t=Tu.get(a);Tu.delete(a),t?(0,Eu.clearVideoElement)(a):jm(a)};var xu=G(Zr(),1),$=require("@vkontakte/videoplayer-shared/es2018");var Gt=require("@vkontakte/videoplayer-shared/es2018"),qs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Gt.isNullable)(i),l=new Gt.Subscription;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},mt=(a,e,t)=>qs(e,()=>a.loop,r=>{(0,Gt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),De=(a,e,t,r)=>qs(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Gt.isNonNullable)(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}),We=(a,e,t,r)=>qs(e,()=>a.playbackRate,i=>{(0,Gt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Wt=qs;var bA=a=>["__",a.language,a.label].join("|"),gA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Pu=class a{constructor(e){this.available$=new $.Subject;this.current$=new $.ValueSubject(void 0);this.error$=new $.Subject;this.subscription=new $.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:$.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Wt(t.internalTextTracks,()=>(0,xu.default)(this.internalTracks),s=>{(0,$.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Wt(t.externalTextTracks,()=>(0,xu.default)(this.externalTracks),s=>{(0,$.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,$.isNonNullable)(s)&&(0,$.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,$.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Wt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Wt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,$.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,$.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"addtrack"),(0,$.fromEvent)(e,"removetrack"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,$.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,$.merge)((0,$.fromEvent)(e,"change"),(0,$.observableFrom)(["init"])).pipe((0,$.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,$.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,$.filterChanged)()).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((0,$.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,$.fromEvent)(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;(0,$.isNonNullable)(t.align)&&(i.align=t.align),(0,$.isNonNullable)(t.position)&&(i.position=t.position),(0,$.isNonNullable)(t.size)&&(i.size=t.size),(0,$.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,$.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:bA(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,$.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,$.isNullable)(e)||!gA(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){(0,$.assertNonNullable)(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,$.assertNonNullable)(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)}},Ye=Pu;var Pt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Xm=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},wu=a=>{let e=Xm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Jm=a=>{let e=Xm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared/es2018");var vA=3,Zm=(a,e,t=vA)=>{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 Ce=a=>{let e=x=>(0,D.fromEvent)(a,x).pipe((0,D.mapTo)(void 0)),r=(0,D.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,D.fromEvent)(a,x))).pipe((0,D.map)(x=>x.type==="ended"?a.readyState<2:a.readyState<3),(0,D.filterChanged)()),i=(0,D.merge)((0,D.fromEvent)(a,"progress"),(0,D.fromEvent)(a,"timeupdate")).pipe((0,D.map)(()=>Zm(a.buffered,a.currentTime))),s=D.clientChecker.isSafari?(0,D.combine)({play:e("play").pipe((0,D.once)()),playing:e("playing")}).pipe((0,D.mapTo)(void 0)):e("playing"),n=(0,D.fromEvent)(a,"volumechange").pipe((0,D.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,D.fromEvent)(a,"ratechange").pipe((0,D.map)(()=>a.playbackRate)),u=(0,D.fromEvent)(a,"error").pipe((0,D.filter)(()=>!!(a.error||a.played.length)),(0,D.map)(()=>{var k;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:D.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(k=a.error)!=null?k:void 0}})),l=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(()=>a.currentTime)),c=new D.Subject,d=.3,p;l.subscribe(x=>{a.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(x)&&p>=a.duration-d&&x<=d&&c.next(p),p=x});let h=e("pause").pipe((0,D.filter)(()=>!a.error&&p!==a.duration)),m=(0,D.fromEvent)(a,"enterpictureinpicture"),g=(0,D.fromEvent)(a,"leavepictureinpicture"),v=new D.ValueSubject(Jm(a));m.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let I=new D.ValueSubject(wu(a));return(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.map)(()=>wu(a))).subscribe(I),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,D.fromEvent)(a,"durationchange").pipe((0,D.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:I,enterPip$:m,leavePip$:g}};var wt=require("@vkontakte/videoplayer-shared/es2018"),Yt=a=>{switch(a){case"mobile":return wt.VideoQuality.Q_144P;case"lowest":return wt.VideoQuality.Q_240P;case"low":return wt.VideoQuality.Q_360P;case"sd":case"medium":return wt.VideoQuality.Q_480P;case"hd":case"high":return wt.VideoQuality.Q_720P;case"fullhd":case"full":return wt.VideoQuality.Q_1080P;case"quadhd":case"quad":return wt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return wt.VideoQuality.Q_2160P}};var zt=G(ei(),1),cb=G(st(),1),Hs=G(Hr(),1),M=require("@vkontakte/videoplayer-shared/es2018");var Au=!1,At={},nb=a=>{Au=a},ob=()=>{At={}},ub=a=>{a(At)},ji=(a,e)=>{var t;Au&&(At.meta=(t=At.meta)!=null?t:{},At.meta[a]=e)},ke=class{constructor(e){this.name=e}next(e){var r,i;if(!Au)return;At.series=(r=At.series)!=null?r:{};let t=(i=At.series[this.name])!=null?i:[];t.push([Date.now(),e]),At.series[this.name]=t}};function Us({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}var AA=new ke("best_bitrate"),db=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ku=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Qi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},pb='Assertion "ABR Tracks is empty array" failed',js=(a,e,t,r)=>{var u;let i=[...e].sort(ku(1)),s=[...t].sort(ku(1)),n=s.filter(l=>(0,M.isNonNullable)(l.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,zt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,zt.default)(s,-1);return o&&(0,cb.default)(n,o)?o:n.length?(0,zt.default)(n,-1):(0,zt.default)(s,0)},lb=a=>"quality"in a,hb=(a,e,t,r)=>{var n;let i=(0,M.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,M.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,M.now)()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=lb(o)?"video":"audio",l=lb(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return r==null||r.recordSwitch(t),t},PA=(a,e)=>Math.log(e)/Math.log(a),Xt=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{var J,C,_,ie,pe,R;(0,M.assertNotEmptyArray)(a,cb);let g=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let P=window.devicePixelRatio;if(r.pixelRatioMultiplier)g*=r.pixelRatioMultiplier*(P-1)+1;else{let q=r.pixelRatioLogBase,[N=0,fe=0,je=0]=r.pixelRatioLogCoefficients,Ot=PA(q,N*P+fe)+je;Number.isFinite(Ot)&&(g*=Ot)}}let v=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*g,height:e.height*g}:void 0,T=r.considerPlaybackRate&&(0,M.isNonNullable)(o)?o:1,E=a.filter(P=>!(0,M.isInvariantQuality)(P.quality)).sort((P,q)=>(0,M.isHigher)(P.quality,q.quality)?-1:1),x=(J=(0,Kt.default)(E,-1))==null?void 0:J.quality,k=(C=(0,Kt.default)(E,0))==null?void 0:C.quality,w=(0,M.isNullable)(i)||(0,M.isNonNullable)(i.min)&&(0,M.isNonNullable)(i.max)&&(0,M.isLower)(i.max,i.min)||(0,M.isNonNullable)(i.min)&&k&&(0,M.isHigher)(i.min,k)||(0,M.isNonNullable)(i.max)&&x&&(0,M.isLower)(i.max,x),j=T*lb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),Q={},Y=E.filter(P=>{let q=!0;if(v)if(P.size)q=P.size.width<=v.width&&P.size.height<=v.height;else{let ye=v&&(0,M.videoSizeToQuality)(v);q=ye?(0,M.isLowerOrEqual)(P.quality,ye):!0}if(!q)return Q[P.quality]="FitsContainer",!1;let N=h||t;if(!((0,M.isNonNullable)(N)&&isFinite(N)&&(0,M.isNonNullable)(P.bitrate)?N-s>=P.bitrate*j:!0))return Q[P.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,M.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,M.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,M.isHigher)(P.quality,u.quality))return Q[P.quality]="Buffer",!1;if(!!d&&(0,M.isHigherOrEqual)(P.quality,d))return Q[P.quality]="DroppedFramesLimit",!1;if(!!p&&(0,M.isHigherOrEqual)(P.quality,p))return Q[P.quality]="StallsLimit",!1;let Z=w||((0,M.isNullable)(i.max)||(0,M.isLowerOrEqual)(P.quality,i.max))&&((0,M.isNullable)(i.min)||(0,M.isHigherOrEqual)(P.quality,i.min)),Se=(0,M.isNonNullable)(c)&&!c?(0,M.isLowerOrEqual)(P.quality,r.backgroundVideoQualityLimit):!0;return!Z||!Se?(Q[P.quality]="FitsQualityLimits",!1):!0})[0];Y&&Y.bitrate&&xA.next(Y.bitrate);let X=(_=Y!=null?Y:(0,Kt.default)(E,-1))!=null?_:a[0];return X.quality!==((ie=l==null?void 0:l.last)==null?void 0:ie.quality)&&f({message:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},kA=(a,e)=>Math.log(e)/Math.log(a),RA=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&window.devicePixelRatio){let i=window.devicePixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=kA(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return mb({tuning:a,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Kt=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{var X,C,_,ie,he,R;(0,M.assertNotEmptyArray)(a,pb);let{containerSizeFactor:g,containerSizeLimit:v}=RA({container:e,tuning:r,limits:i}),I=r.considerPlaybackRate&&(0,M.isNonNullable)(o)?o:1,E=a.filter(P=>!(0,M.isInvariantQuality)(P.quality)).sort((P,Q)=>(0,M.isHigher)(P.quality,Q.quality)?-1:1),x=(X=(0,zt.default)(E,-1))==null?void 0:X.quality,k=(C=(0,zt.default)(E,0))==null?void 0:C.quality,w=(0,M.isNullable)(i)||(0,M.isNonNullable)(i.min)&&(0,M.isNonNullable)(i.max)&&(0,M.isLower)(i.max,i.min)||(0,M.isNonNullable)(i.min)&&k&&(0,M.isHigher)(i.min,k)||(0,M.isNonNullable)(i.max)&&x&&(0,M.isLower)(i.max,x),F=I*db(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),j={},W=E.filter(P=>{let Q=!0;if(v)if(P.size)Q=P.size.width<=v.width&&P.size.height<=v.height;else{let Pe=v&&(0,M.videoSizeToQuality)(v);Q=Pe?(0,M.isLowerOrEqual)(P.quality,Pe):!0}if(!Q)return j[P.quality]="FitsContainer",!1;let ae=h||t,J=(0,M.isNonNullable)(ae)&&isFinite(ae)&&(0,M.isNonNullable)(P.bitrate)?ae-s>=P.bitrate*F:!0,Ne=mb({tuning:r,limits:i})&&(i==null?void 0:i.min)===P.quality;if(!J&&!Ne)return j[P.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,M.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,M.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,M.isHigher)(P.quality,u.quality))return j[P.quality]="Buffer",!1;if(!!d&&(0,M.isHigherOrEqual)(P.quality,d)&&!Ne)return j[P.quality]="DroppedFramesLimit",!1;if(!!p&&(0,M.isHigherOrEqual)(P.quality,p)&&!Ne)return j[P.quality]="StallsLimit",!1;let Se=w||((0,M.isNullable)(i.max)||(0,M.isLowerOrEqual)(P.quality,i.max))&&((0,M.isNullable)(i.min)||(0,M.isHigherOrEqual)(P.quality,i.min)),xe=(0,M.isNonNullable)(c)&&!c?(0,M.isLowerOrEqual)(P.quality,r.backgroundVideoQualityLimit):!0;return!Se||!xe?(j[P.quality]="FitsQualityLimits",!1):!0})[0];W&&W.bitrate&&AA.next(W.bitrate);let K=(_=W!=null?W:(0,zt.default)(E,-1))!=null?_:a[0];return K.quality!==((ie=l==null?void 0:l.last)==null?void 0:ie.quality)&&m({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(P=>{var q,N;return`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${(q=P.size)==null?void 0:q.width}:${(N=P.size)==null?void 0:N.height} }`}).join(`
12
+ ${a.map(P=>{var Q,ae;return`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${(Q=P.size)==null?void 0:Q.width}:${(ae=P.size)==null?void 0:ae.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,qs.default)(r!=null?r:{}).map(([P,q])=>`${P}: ${q}`).join(`
16
+ ${(0,Hs.default)(r!=null?r:{}).map(([P,Q])=>`${P}: ${Q}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
20
  containerSizeFactor: ${g},
21
- containerSizeLimit: ${(pe=v==null?void 0:v.width)!=null?pe:0} x ${(R=v==null?void 0:v.height)!=null?R:0},
21
+ containerSizeLimit: ${(he=v==null?void 0:v.width)!=null?he:0} x ${(R=v==null?void 0:v.height)!=null?R:0},
22
22
  estimatedThroughput: ${t},
23
23
  stallsPredictedThroughput: ${h},
24
24
  reserve: ${s},
25
25
  playbackRate: ${o},
26
- playbackRateFactor: ${T},
26
+ playbackRateFactor: ${I},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${j},
28
+ bitrateFactor: ${F},
29
29
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
30
30
  droppedVideoMaxQualityLimit: ${d},
31
31
  stallsVideoMaxQualityLimit: ${p},
@@ -34,19 +34,19 @@
34
34
  minQualityLimit: ${i==null?void 0:i.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,qs.default)(Q).map(([P,q])=>`${P}: ${q}`).join(`
37
+ ${(0,Hs.default)(j).map(([P,Q])=>`${P}: ${Q}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
- [best video track] ${Y==null?void 0:Y.quality}
41
- [selected video track] ${X==null?void 0:X.quality}
42
- `}),db(r,f,X,l)},pb=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var T;(0,M.assertNotEmptyArray)(t,cb);let c=i.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,d=[...t].sort(wu(-1)),p=a.bitrate;(0,M.assertNonNullable)(p);let h=c*lb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,g=Us(a,e,t,i.minVideoAudioRatio),v=l||r;return(0,M.isNonNullable)(v)&&isFinite(v)&&(f=d.find(E=>(0,M.isNonNullable)(E.bitrate)&&(0,M.isNonNullable)(g==null?void 0:g.bitrate)?v-p>=E.bitrate*h&&E.bitrate>=g.bitrate:!1)),f||(f=g),(f==null?void 0:f.bitrate)!==((T=o==null?void 0:o.last)==null?void 0:T.bitrate)&&u({message:`
40
+ [best video track] ${W==null?void 0:W.quality}
41
+ [selected video track] ${K==null?void 0:K.quality}
42
+ `}),hb(r,m,K,l)},fb=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var I;(0,M.assertNotEmptyArray)(t,pb);let c=i.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,d=[...t].sort(ku(-1)),p=a.bitrate;(0,M.assertNonNullable)(p);let h=c*db(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,g=js(a,e,t,i.minVideoAudioRatio),v=l||r;return(0,M.isNonNullable)(v)&&isFinite(v)&&(m=d.find(E=>(0,M.isNonNullable)(E.bitrate)&&(0,M.isNonNullable)(g==null?void 0:g.bitrate)?v-p>=E.bitrate*h&&E.bitrate>=g.bitrate:!1)),m||(m=g),(m==null?void 0:m.bitrate)!==((I=o==null?void 0:o.last)==null?void 0:I.bitrate)&&u({message:`
43
43
  [AUDIO TRACKS ABR]
44
44
  [available audio tracks]
45
45
  ${t.map(E=>`{ id: ${E.id}, bitrate: ${E.bitrate} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,qs.default)(i!=null?i:{}).map(([E,x])=>`${E}: ${x}`).join(`
49
+ ${(0,Hs.default)(i!=null?i:{}).map(([E,x])=>`${E}: ${x}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
@@ -59,15 +59,15 @@
59
59
  bitrateFactor: ${h},
60
60
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
61
61
 
62
- [selected audio track] ${f==null?void 0:f.id}
63
- `}),f&&db(i,u,f,o)};var ge=a=>new URL(a).hostname;var O=require("@vkontakte/videoplayer-shared/es2018");var mb=W(st(),1),hb=a=>{if(a instanceof DOMException&&(0,mb.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"))},De=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!hb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return hb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};var Ue=require("@vkontakte/videoplayer-shared/es2018");var fb=W(Jr(),1),bt=require("@vkontakte/videoplayer-shared/es2018");function ve(){return(0,bt.now)()}function Au(a){return ve()-a}function ku(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 bb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ei(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,g=2e3,v=()=>{if(u)return;(0,bt.assertNonNullable)(c);let C=Au(c),_;if(C<g){_=g-C,setTimeout(v,_);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new i,j()},T=C=>(s=C,J),E=C=>(d=C,J),x=()=>(h="json",J),k=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},w=C=>(p=C,J),j=()=>{c=ve(),n=new i,n.open("get",a);let C=0,_,ie=0,pe=()=>((0,bt.assertNonNullable)(c),Math.max(c,Math.max(_||0,ie||0)));if(s&&n.addEventListener("progress",R=>{let P=ve();s.updateChunk&&R.loaded>C&&(s.updateChunk(pe(),R.loaded-C),C=R.loaded,_=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>k())),n.addEventListener("load",()=>{if(u)return;(0,bt.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&s){let P=n.response.byteLength-C;P&&s.updateChunk&&s.updateChunk(pe(),P)}n.responseType==="json"&&!(0,fb.default)(n.response).length?k():(d&&d(),e(n.response))}else k()}),n.addEventListener("error",()=>{k()}),p){let R=()=>{(0,bt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ie=ve(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=h,n.send(),J},J={withBitrateReporting:T,withParallel:w,withJSONResponse:x,withRetryCount:C=>(l=C,J),withRetryInterval:(C,_)=>((0,bt.isNonNullable)(C)&&(g=C),(0,bt.isNonNullable)(_)&&(f=_),J),withTimeout:C=>(o=C,J),withFinally:E,send:j,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return J}var ji=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 gb=W(Jr(),1);var Gi=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=ve(),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=ve()-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=ei(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=ve()}_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=ve();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,gb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var vb=require("@vkontakte/videoplayer-shared/es2018"),Hs=1e4,Ru=3;var AA=6e4,kA=10,RA=1,$A=500,Qi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new vb.Subject,this.chunkRateEstimator=new ji(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 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=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,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||(0,Ue.isNonNullable)(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=()=>{bb(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 Gi(Ru,Hs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let k=s&&(!c||c===this.rep);return k||t("Not running!"),k},p=(k,w,j)=>{u&&u.abort(),u=ei(this.urlResolver.resolve(k,!1),w,j,()=>this._retryCallback()).withTimeout(Hs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ru).withFinally(()=>{u=null}).send()},h=(k,w,j)=>{(0,Ue.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(k,!1),w,j,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=k=>{let w=r.playbackRate;r.playbackRate!==k&&(t(`Playback rate switch: ${w}=>${k}`),r.playbackRate=k)},g=k=>{this.lowLatency=k,t(`lowLatency changed to ${k}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let k=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let j=ve()-1e4,Q=0;for(let Y=0;Y<this.bufferStates.length;Y++){let X=this.bufferStates[Y];k=Math.min(k,X.buf),X.ts<j&&Q++}this.bufferStates.splice(0,Q),t(`update playback rate; minBuffer=${k} drop=${Q} jitter=${this.sourceJitter}`);let ee=k-RA;this.sourceJitter>=0?ee-=this.sourceJitter/2:this.sourceJitter-=1,ee>3?f(1.15):ee>1?f(1.1):ee>.3?f(1.05):f(1)}},T=k=>{let w,j=()=>w&&w.start?w.start.length:0,Q=R=>w.start[R]/1e3,ee=R=>w.dur[R]/1e3,Y=R=>w.fragIndex+R,X=(R,P)=>({chunkIdx:Y(R),startTS:Q(R),dur:ee(R),discontinuity:P}),J=()=>{let R=0;if(w&&w.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,N=P;this.sourceJitter>1&&(N+=this.sourceJitter-1);let fe=w.dur.length-1;for(;fe>=0&&(N-=w.dur[fe],!(N<=0));--fe);R=Math.min(fe,w.dur.length-1-q),R=Math.max(R,0)}return X(R,!0)},C=R=>{let P=j();if(!(P<=0)){if((0,Ue.isNonNullable)(R)){for(let q=0;q<P;q++)if(Q(q)>R)return X(q)}return J()}},_=R=>{let P=j(),q=R?R.chunkIdx+1:0,N=q-w.fragIndex;if(!(P<=0)){if(!R||N<0||N-P>kA)return t(`Resync: offset=${N} bChunks=${P} chunk=`+JSON.stringify(R)),J();if(!(N>=P))return X(q-w.fragIndex,!1)}},ie=(R,P,q)=>{l&&l.abort(),l=ei(this.urlResolver.resolve(R,!0,this.lowLatency),P,q,()=>this._retryCallback()).withTimeout(Hs).withRetryCount(Ru).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,P)=>{ie(k,q=>{if(!d())return;w=q;let N=!!w.lowLatency;N!==this.lowLatency&&g(N);let fe=0;for(let je=0;je<w.dur.length;++je)fe+=w.dur[je];fe>0&&((0,Ue.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(fe/w.dur.length)),i({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,R(C(P))},()=>this._handleNetworkError())},nextChunk:_}},E=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ue.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:k=>{let{videoElement:w,logger:j}=this.params,Q=T(e.jidxUrl),ee,Y,X,J,C=0,_,ie,pe,R=()=>{_&&(clearTimeout(_),_=void 0);let Z=Math.max($A,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=C+Z,ye=ve(),Ge=Math.min(1e4,Se-ye);C=ye;let Vt=()=>{l||d()&&Q.seek(()=>{d()&&(C=ve(),P(),R())})};Ge>0?_=window.setTimeout(()=>{this.paused?R():Vt()},Ge):Vt()},P=()=>{let Z;for(;Z=Q.nextChunk(J);)J=Z,Ot(Z);let Se=Q.nextChunk(X);if(Se){if(X&&Se.discontinuity){j("Detected discontinuity; restarting playback"),this.paused?R():(E(),this._initPlayerWith(e));return}je(Se)}else R()},q=(Z,Se)=>{if(!d()||!this.sourceBuffer)return;let ye,Ge,Vt,Pr=Bt=>{window.setTimeout(()=>{d()&&q(Z,Se)},Bt)};if(this.sourceBuffer.updating)j("Source buffer is updating; delaying appendBuffer"),Pr(100);else{let Bt=ve(),rr=w.currentTime;!this.paused&&w.buffered.length>1&&ie===rr&&Bt-pe>500&&(j("Stall suspected; trying to fix"),this._fixupStall()),ie!==rr&&(ie=rr,pe=Bt);let wr=this._getBufferSizeSec();if(wr>30)j(`Buffered ${wr} seconds; delaying appendBuffer`),Pr(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:Bt,buf:wr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(ci){if(ci.name==="QuotaExceededError")j("QuotaExceededError; delaying appendBuffer"),Vt=this.sourceBuffer.buffered.length,Vt!==0&&(ye=this.sourceBuffer.buffered.start(0),Ge=rr,Ge-ye>4&&this.sourceBuffer.remove(ye,Ge-3)),Pr(1e3);else throw ci}}},N=()=>{Y&&ee&&(j([`Appending chunk, sz=${Y.byteLength}:`,JSON.stringify(X)]),q(Y,function(){Y=null,P()}))},fe=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),je=Z=>{d()&&h(fe(Z),(Se,ye)=>{if(d()){if(ye/=1e3,Y=Se,X=Z,n=Z.startTS,ye){let Ge=Math.min(10,Z.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ge:Ge}N()}},()=>this._handleNetworkError())},Ot=Z=>{d()&&((0,Ue.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(fe(Z),!1)))},xr=Z=>{d()&&(e.cachedHeader=Z,q(Z,()=>{ee=!0,N()}))};s=!0,Q.seek(Z=>{if(d()){if(C=ve(),!Z){R();return}J=Z,!(0,Ue.isNullable)(k)||Z.startTS>k?je(Z):(X=Z,P())}},k),e.cachedHeader?xr(e.cachedHeader):p(e.headerUrl,xr,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ue.isNonNullable)(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,(0,Ue.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ue.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ve();if(this.chunkRateEstimator.addInterval(p,f,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Au(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ve();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ei(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Hs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;De(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))},AA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Sb=W(Ur(),1),oe=require("@vkontakte/videoplayer-shared/es2018"),$u=class{constructor(){this.onDroopedVideoFramesLimit$=new oe.Subject;this.subscription=new oe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new oe.Subject;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&&!(0,oe.isInvariantQuality)(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&&(0,oe.isHigher)(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((0,oe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,oe.interval)(this.droppedFramesChecker.checkTime).pipe((0,oe.filter)(()=>this.playing),(0,oe.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,oe.debounce)(this.droppedFramesChecker.checkTime)),r=(0,oe.merge)(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,Sb.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,oe.isLower)(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},js=$u;var Gs=require("@vkontakte/videoplayer-shared/es2018"),yb=require("@vkontakte/videoplayer-shared/es2018");var Wi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var LA=(a,e)=>new Gs.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Wi()))},{...r,...e});i.observe(a);let s=(0,yb.fromEvent)(document,"visibilitychange").pipe((0,Gs.map)(n=>!document.hidden||Wi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),ze=LA;var MA=["paused","playing","ready"],DA=["paused","playing","ready"],Yi=class{constructor(e){this.subscription=new O.Subscription;this.videoState=new U("stopped");this.representations$=new O.ValueSubject([]);this.droppedFramesManager=new js;this.maxSeekBackTime$=new O.ValueSubject(1/0);this.zeroTime$=new O.ValueSubject(void 0);this.liveOffset=new Pt;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:O.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=zt(u.name))!=null?r:(0,O.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,O.isNonNullable)(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,Lu.default)(DA,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Lu.default)(MA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ee(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(Ee(this.params.source.url,u))}return;default:return(0,O.assertNever)(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:O.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,O.merge)(this.videoState.stateChangeStarted$.pipe((0,O.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,O.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Re(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(ge(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=Me(this.video);this.subscription.add(this.representations$.pipe((0,O.map)(i=>i.map(({track:s})=>s)),(0,O.filter)(i=>!!i.length),(0,O.once)()).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((0,O.filterChanged)(),(0,O.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,O.combine)({zeroTime:this.zeroTime$.pipe((0,O.filter)(O.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ft(this.video,this.params.desiredState.isLooped,t)).add(Le(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(We(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(ze(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,O.videoQualityToHeight)(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(0,O.assertNever)(i.to)}},t)).add((0,O.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,O.observableFrom)(["init"])).pipe((0,O.debounce)(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),$e(this.video)}createLiveDashPlayer(){let e=new Qi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,O.isNonNullable)(t)?t:Xt(e.map(({track:g})=>g),{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 g=(f=e.find(({track:v})=>v.id===s))==null?void 0:f.representation;(0,O.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,O.assertNonNullable)(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(Ee(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Tb=Yi;var jv=W(st(),1);var gt=(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)};var B=require("@vkontakte/videoplayer-shared/es2018");var Qs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ti=class extends Qs{constructor(){super(),this.listeners||Qs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},zi=class{constructor(){Object.defineProperty(this,"signal",{value:new ti,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(zi.prototype[Symbol.toStringTag]="AbortController",ti.prototype[Symbol.toStringTag]="AbortSignal");function Ws(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Mu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Ws({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ki=Ws({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ib=Ki?Mu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ot=Ki?Ib.fetch:window.fetch,kC=Ki?Ib.Request:window.Request,xe=Ki?zi:window.AbortController,RC=Ki?ti:window.AbortSignal;var ol=W(Cu(),1);var rn=W(Zr(),1);var kt=()=>window.ManagedMediaSource||window.MediaSource,Ys=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ub=()=>{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;var vt=require("@vkontakte/videoplayer-shared/es2018"),Ke=document.createElement("video"),ak='video/mp4; codecs="avc1.42000a,mp4a.40.2"',sk='video/mp4; codecs="hev1.1.6.L93.B0"',eg='video/webm; codecs="vp09.00.10.08"',tg='video/webm; codecs="av01.0.00M.08"',nk='audio/mp4; codecs="mp4a.40.2"',ok='audio/webm; codecs="opus"',jb,Gb,Xi={mms:Ys(),mse:Ub(),hls:!!((jb=Ke.canPlayType)!=null&&jb.call(Ke,"application/x-mpegurl")||(Gb=Ke.canPlayType)!=null&&Gb.call(Ke,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Qb,Wb,Ce={mp4:!!((Qb=Ke.canPlayType)!=null&&Qb.call(Ke,"video/mp4")),webm:!!((Wb=Ke.canPlayType)!=null&&Wb.call(Ke,"video/webm")),cmaf:!0},Ks,Yb,Xs,zb,Js,Kb,Zs,Xb,en,Jb,tn,Zb,Oe={h264:!!((Yb=(Ks=kt())==null?void 0:Ks.isTypeSupported)!=null&&Yb.call(Ks,ak)),h265:!!((zb=(Xs=kt())==null?void 0:Xs.isTypeSupported)!=null&&zb.call(Xs,sk)),vp9:!!((Kb=(Js=kt())==null?void 0:Js.isTypeSupported)!=null&&Kb.call(Js,eg)),av1:!!((Xb=(Zs=kt())==null?void 0:Zs.isTypeSupported)!=null&&Xb.call(Zs,tg)),aac:!!((Jb=(en=kt())==null?void 0:en.isTypeSupported)!=null&&Jb.call(en,nk)),opus:!!((Zb=(tn=kt())==null?void 0:tn.isTypeSupported)!=null&&Zb.call(tn,ok))},ri=(Oe.h264||Oe.h265)&&Oe.aac,vr,uk=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}})]);vr={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{uk()}catch(a){console.error(a)}var ii=Xi.hls&&Ce.mp4,rg=()=>Object.keys(Oe).filter(a=>Oe[a]),ig=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Xi.mse&&(!r||!!window.MediaStreamTrack)||Xi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Ce.mp4&&ri;case"DASH_WEBM":return i&&Ce.webm&&Oe.vp9&&Oe.opus;case"DASH_WEBM_AV1":return i&&Ce.webm&&Oe.av1&&Oe.opus;case"DASH_STREAMS":return i&&(Ce.mp4&&ri||Ce.webm&&(Oe.vp9||Oe.av1)&&(Oe.opus||Oe.aac));case"DASH_LIVE":return i&&Ce.mp4&&ri;case"DASH_LIVE_CMAF":return i&&Ce.mp4&&ri&&Ce.cmaf;case"DASH_ONDEMAND":return i&&Ce.mp4&&ri;case"HLS":case"HLS_ONDEMAND":return ii||e&&i&&Ce.mp4&&ri;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ii;case"MPEG":return Ce.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Xi.webrtc&&Xi.ws&&Oe.h264&&(Ce.mp4||Ce.webm);default:return(0,vt.assertNever)(s)}})},zs=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return vr?vr[t].smooth?[t,e]:vr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return vr?vr[t].powerEfficient?[t,e]:vr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,vt.assertNever)(a)}return[e,t]},ag=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...zs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(vt.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...zs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...zs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...zs(a),...i,"HLS","HLS_ONDEMAND"];default:(0,vt.assertNever)(e)}return ii?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},sg=({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=vt.clientChecker.isMac&&vt.clientChecker.isSafari;if(vt.clientChecker.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:(0,vt.assertNever)(a)}else ii&&!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"]},Ou=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,rn.default)(t.value.split("."),0)}for(let t of a){let r=(0,rn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,rn.default)(e.value.split("."),0)};var Ag=W(wg(),1),ai=require("@vkontakte/videoplayer-shared/es2018"),kg=a=>{if(!a)return{id:"EmptyResponse",category:ai.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ai.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,Ag.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ai.ErrorCategory.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:ai.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ai.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Jt=(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};var S=require("@vkontakte/videoplayer-shared/es2018");var an=W(st(),1),oi=W(Zr(),1),sn=W(Cu(),1);var Pk=(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)},wk=a=>window.clearTimeout(a),Rg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),$g=!Rg(window.requestIdleCallback)||!Rg(window.cancelIdleCallback),Fu=$g?Pk:window.requestIdleCallback,Zi=$g?wk:window.cancelIdleCallback;var Vv=W(Bs(),1);var Xe=require("@vkontakte/videoplayer-shared/es2018"),Ak=18,Lg=!1;try{Lg=Xe.clientChecker.isSafari&&!!Xe.clientChecker.macVersion&&Xe.clientChecker.macVersion<=Ak}catch(a){console.error(a)}var qu=class{constructor(e){this.bufferFull$=new Xe.Subject;this.error$=new Xe.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Xe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};Lg&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Xe.ErrorCategory.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:(0,Xe.assertNever)(t)}}},Mg=qu;var Uu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var I=require("@vkontakte/videoplayer-shared/es2018");var te=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 si=class extends te{};var ea=class extends te{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 ta=class extends te{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 ra=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ue=class extends te{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ia=class extends ue{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 aa=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends te{constructor(e,t){super(e,t),this.data=this.content}};var Sr=class extends ue{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 na=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ua=class extends ue{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 la=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ca=class extends ue{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var da=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pa=class extends ue{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 ha=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ma=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ba=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ga=class extends ue{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 va=class extends ue{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 Sa=class extends ue{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 Rk={ftyp:ta,moov:ra,mvhd:ia,moof:aa,mdat:sa,sidx:Sr,trak:na,mdia:da,mfhd:fa,tkhd:pa,traf:ba,tfhd:ga,tfdt:va,trun:Sa,minf:ha,sv3d:oa,st3d:ua,prhd:la,proj:ma,equi:ca,uuid:ea,unknown:si},Rt=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=Rk[e];return r?new r(t,new a):new si(t,new a)}};var Zt=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 Lk=new TextDecoder("ascii"),Mk=a=>Lk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Dk=a=>{let e=new Sr(a,new Rt),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})},Ck=(a,e)=>{let r=new Rt().parse(a),i=new Zt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},Ok=a=>{let t=new Rt().parse(a),r=new Zt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},Vk=a=>{var i;let t=new Rt().parse(a);return(i=new Zt(t).find("sidx"))==null?void 0:i.timescale},Bk=(a,e)=>{let r=new Rt().parse(a),s=new Zt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},_k=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 Rt().parse(a),i=new Zt(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},Dg={validateData:Mk,parseInit:_k,getIndexRange:()=>{},parseSegments:Dk,parseFeedableSegmentChunk:Ck,getChunkEndTime:Bk,getServerLatencyTimestamps:Ok,getTimescaleFromIndex:Vk};var Ta=W(st(),1),$t=require("@vkontakte/videoplayer-shared/es2018");var Og=require("@vkontakte/videoplayer-shared/es2018");var Cg={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"}},Vg=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=ya(a,t),i=r in Cg,s=i?Cg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ya(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ya=(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},ut=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ya(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:(0,Og.assertNever)(e)}},yr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Vg(r);if(!e(i))return;i.type==="master"&&yr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Bg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Vg(a);return yr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=ut(o,n):s===17026?t=ut(o,n):s===17029&&(r=ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var _g=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Nk=[231,22612,22743,167,171,163,160,175],Fk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return yr(a,({tag:p,type:h,value:f,valueSize:g})=>{if(p===21419){let v=ut(f,h);l=ya(v)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=ut(f,h):p===17545?i=ut(f,h):p===21420&&l===475249515?u=ut(f,h):p===374648427?yr(f,({tag:v,type:T,value:E})=>v===30321?(c=ut(E,T)===1,!1):!0):s&&n&&(0,Ta.default)(_g,p)&&(o=!0),!o}),(0,$t.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,$t.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,$t.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},qk=a=>{if((0,$t.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Uk=(a,e)=>{let t=!1,r=!1,i=o=>(0,$t.isNonNullable)(o.time)&&(0,$t.isNonNullable)(o.position),s=[],n;return yr(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=ut(l,u));break;case 183:break;case 241:n&&(n.position=ut(l,u));break;default:t&&(0,Ta.default)(_g,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Hk=a=>{let e=0,t=!1;try{yr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Ta.default)(Nk,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Ta.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},Ng={validateData:Bg,parseInit:Fk,getIndexRange:qk,parseSegments:Uk,parseFeedableSegmentChunk:Hk};var Ia=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Ng;case"mp4":return Dg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var tl=W(sv(),1),Lv=W(Ur(),1),Mv=W(Tv(),1),Dv=W(Zr(),1),rl=W(Jr(),1);var Iv=W(st(),1),zu=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,Iv.default)(["6E","7A","F4"],o)}}return!1};var xa=require("@vkontakte/videoplayer-shared/es2018");var Ev=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var xv=a=>{var e;try{let t=_R(),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 _R(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
62
+ [selected audio track] ${m==null?void 0:m.id}
63
+ `}),m&&hb(i,u,m,o)};function mb({limits:a,tuning:{highQualityLimit:e,trafficSavingLimit:t}}){return!!a&&Us({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}var ge=a=>new URL(a).hostname;var V=require("@vkontakte/videoplayer-shared/es2018");var gb=G(st(),1),bb=a=>{if(a instanceof DOMException&&(0,gb.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"))},Ve=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!bb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return bb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};var je=require("@vkontakte/videoplayer-shared/es2018");var vb=G(Zr(),1),bt=require("@vkontakte/videoplayer-shared/es2018");function ve(){return(0,bt.now)()}function Ru(a){return ve()-a}function Lu(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 Sb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ti(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,g=2e3,v=()=>{if(u)return;(0,bt.assertNonNullable)(c);let C=Ru(c),_;if(C<g){_=g-C,setTimeout(v,_);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,F()},I=C=>(s=C,X),E=C=>(d=C,X),x=()=>(h="json",X),k=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},w=C=>(p=C,X),F=()=>{c=ve(),n=new i,n.open("get",a);let C=0,_,ie=0,he=()=>((0,bt.assertNonNullable)(c),Math.max(c,Math.max(_||0,ie||0)));if(s&&n.addEventListener("progress",R=>{let P=ve();s.updateChunk&&R.loaded>C&&(s.updateChunk(he(),R.loaded-C),C=R.loaded,_=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>k())),n.addEventListener("load",()=>{if(u)return;(0,bt.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){if(n.response.byteLength&&s){let P=n.response.byteLength-C;P&&s.updateChunk&&s.updateChunk(he(),P)}n.responseType==="json"&&!(0,vb.default)(n.response).length?k():(d&&d(),e(n.response))}else k()}),n.addEventListener("error",()=>{k()}),p){let R=()=>{(0,bt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ie=ve(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=h,n.send(),X},X={withBitrateReporting:I,withParallel:w,withJSONResponse:x,withRetryCount:C=>(l=C,X),withRetryInterval:(C,_)=>((0,bt.isNonNullable)(C)&&(g=C),(0,bt.isNonNullable)(_)&&(m=_),X),withTimeout:C=>(o=C,X),withFinally:E,send:F,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return X}var Gi=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 yb=G(Zr(),1);var Wi=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=ve(),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=ve()-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=ti(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=ve()}_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=ve();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,yb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Tb=require("@vkontakte/videoplayer-shared/es2018"),Qs=1e4,$u=3;var $A=6e4,MA=10,DA=1,CA=500,Yi=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 Tb.Subject,this.chunkRateEstimator=new Gi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Lu(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=Lu(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||(0,je.isNonNullable)(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=()=>{Sb(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 Wi($u,Qs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let k=s&&(!c||c===this.rep);return k||t("Not running!"),k},p=(k,w,F)=>{u&&u.abort(),u=ti(this.urlResolver.resolve(k,!1),w,F,()=>this._retryCallback()).withTimeout(Qs).withBitrateReporting(this.bitrateSwitcher).withRetryCount($u).withFinally(()=>{u=null}).send()},h=(k,w,F)=>{(0,je.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(k,!1),w,F,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=k=>{let w=r.playbackRate;r.playbackRate!==k&&(t(`Playback rate switch: ${w}=>${k}`),r.playbackRate=k)},g=k=>{this.lowLatency=k,t(`lowLatency changed to ${k}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let k=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let F=ve()-1e4,j=0;for(let W=0;W<this.bufferStates.length;W++){let K=this.bufferStates[W];k=Math.min(k,K.buf),K.ts<F&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${k} drop=${j} jitter=${this.sourceJitter}`);let ee=k-DA;this.sourceJitter>=0?ee-=this.sourceJitter/2:this.sourceJitter-=1,ee>3?m(1.15):ee>1?m(1.1):ee>.3?m(1.05):m(1)}},I=k=>{let w,F=()=>w&&w.start?w.start.length:0,j=R=>w.start[R]/1e3,ee=R=>w.dur[R]/1e3,W=R=>w.fragIndex+R,K=(R,P)=>({chunkIdx:W(R),startTS:j(R),dur:ee(R),discontinuity:P}),X=()=>{let R=0;if(w&&w.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ae=P;this.sourceJitter>1&&(ae+=this.sourceJitter-1);let J=w.dur.length-1;for(;J>=0&&(ae-=w.dur[J],!(ae<=0));--J);R=Math.min(J,w.dur.length-1-Q),R=Math.max(R,0)}return K(R,!0)},C=R=>{let P=F();if(!(P<=0)){if((0,je.isNonNullable)(R)){for(let Q=0;Q<P;Q++)if(j(Q)>R)return K(Q)}return X()}},_=R=>{let P=F(),Q=R?R.chunkIdx+1:0,ae=Q-w.fragIndex;if(!(P<=0)){if(!R||ae<0||ae-P>MA)return t(`Resync: offset=${ae} bChunks=${P} chunk=`+JSON.stringify(R)),X();if(!(ae>=P))return K(Q-w.fragIndex,!1)}},ie=(R,P,Q)=>{l&&l.abort(),l=ti(this.urlResolver.resolve(R,!0,this.lowLatency),P,Q,()=>this._retryCallback()).withTimeout(Qs).withRetryCount($u).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,P)=>{ie(k,Q=>{if(!d())return;w=Q;let ae=!!w.lowLatency;ae!==this.lowLatency&&g(ae);let J=0;for(let Ne=0;Ne<w.dur.length;++Ne)J+=w.dur[Ne];J>0&&((0,je.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(J/w.dur.length)),i({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,R(C(P))},()=>this._handleNetworkError())},nextChunk:_}},E=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,je.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:k=>{let{videoElement:w,logger:F}=this.params,j=I(e.jidxUrl),ee,W,K,X,C=0,_,ie,he,R=()=>{_&&(clearTimeout(_),_=void 0);let Z=Math.max(CA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=C+Z,xe=ve(),Pe=Math.min(1e4,Se-xe);C=xe;let Vt=()=>{l||d()&&j.seek(()=>{d()&&(C=ve(),P(),R())})};Pe>0?_=window.setTimeout(()=>{this.paused?R():Vt()},Pe):Vt()},P=()=>{let Z;for(;Z=j.nextChunk(X);)X=Z,di(Z);let Se=j.nextChunk(K);if(Se){if(K&&Se.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?R():(E(),this._initPlayerWith(e));return}Ne(Se)}else R()},Q=(Z,Se)=>{if(!d()||!this.sourceBuffer)return;let xe,Pe,Vt,Pr=Ot=>{window.setTimeout(()=>{d()&&Q(Z,Se)},Ot)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),Pr(100);else{let Ot=ve(),tr=w.currentTime;!this.paused&&w.buffered.length>1&&ie===tr&&Ot-he>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),ie!==tr&&(ie=tr,he=Ot);let wr=this._getBufferSizeSec();if(wr>30)F(`Buffered ${wr} seconds; delaying appendBuffer`),Pr(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:wr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(pi){if(pi.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),Vt=this.sourceBuffer.buffered.length,Vt!==0&&(xe=this.sourceBuffer.buffered.start(0),Pe=tr,Pe-xe>4&&this.sourceBuffer.remove(xe,Pe-3)),Pr(1e3);else throw pi}}},ae=()=>{W&&ee&&(F([`Appending chunk, sz=${W.byteLength}:`,JSON.stringify(K)]),Q(W,function(){W=null,P()}))},J=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),Ne=Z=>{d()&&h(J(Z),(Se,xe)=>{if(d()){if(xe/=1e3,W=Se,K=Z,n=Z.startTS,xe){let Pe=Math.min(10,Z.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}ae()}},()=>this._handleNetworkError())},di=Z=>{d()&&((0,je.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(J(Z),!1)))},xr=Z=>{d()&&(e.cachedHeader=Z,Q(Z,()=>{ee=!0,ae()}))};s=!0,j.seek(Z=>{if(d()){if(C=ve(),!Z){R();return}X=Z,!(0,je.isNullable)(k)||Z.startTS>k?Ne(Z):(K=Z,P())}},k),e.cachedHeader?xr(e.cachedHeader):p(e.headerUrl,xr,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,je.isNonNullable)(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,(0,je.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,je.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=ve();if(this.chunkRateEstimator.addInterval(p,m,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Ru(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ve();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ti(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Qs).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ve(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))},$A))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ib=G(Hr(),1),ue=require("@vkontakte/videoplayer-shared/es2018"),Mu=class{constructor(){this.onDroopedVideoFramesLimit$=new ue.Subject;this.subscription=new ue.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ue.Subject;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&&!(0,ue.isInvariantQuality)(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&&(0,ue.isHigher)(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((0,ue.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ue.interval)(this.droppedFramesChecker.checkTime).pipe((0,ue.filter)(()=>this.playing),(0,ue.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,ue.debounce)(this.droppedFramesChecker.checkTime)),r=(0,ue.merge)(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,Ib.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ue.isLower)(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=Mu;var Ws=require("@vkontakte/videoplayer-shared/es2018"),Eb=require("@vkontakte/videoplayer-shared/es2018");var zi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var VA=(a,e)=>new Ws.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||zi()))},{...r,...e});i.observe(a);let s=(0,Eb.fromEvent)(document,"visibilitychange").pipe((0,Ws.map)(n=>!document.hidden||zi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),ze=VA;var OA=["paused","playing","ready"],BA=["paused","playing","ready"],Ki=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new q("stopped");this.representations$=new V.ValueSubject([]);this.droppedFramesManager=new Gs;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new Pt;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:V.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Yt(u.name))!=null?r:(0,V.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p={...u.video};if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,V.isNonNullable)(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,Du.default)(BA,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Du.default)(OA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ie(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(Ie(this.params.source.url,u))}return;default:return(0,V.assertNever)(e)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=$e(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(ge(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=Ce(this.video);this.subscription.add(this.representations$.pipe((0,V.map)(i=>i.map(({track:s})=>s)),(0,V.filter)(i=>!!i.length),(0,V.once)()).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((0,V.filterChanged)(),(0,V.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,V.combine)({zeroTime:this.zeroTime$.pipe((0,V.filter)(V.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(De(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(We(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(ze(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,V.videoQualityToHeight)(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(0,V.assertNever)(i.to)}},t)).add((0,V.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(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),Me(this.video)}createLiveDashPlayer(){let e=new Yi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,V.isNonNullable)(t)?t:Kt(e.map(({track:g})=>g),{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 g=(m=e.find(({track:v})=>v.id===s))==null?void 0:m.representation;(0,V.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,V.assertNonNullable)(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(Ie(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var xb=Ki;var Wv=G(st(),1);var gt=(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)};var B=require("@vkontakte/videoplayer-shared/es2018");var Ys=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ri=class extends Ys{constructor(){super(),this.listeners||Ys.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Xi=class{constructor(){Object.defineProperty(this,"signal",{value:new ri,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&&(Xi.prototype[Symbol.toStringTag]="AbortController",ri.prototype[Symbol.toStringTag]="AbortSignal");function zs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Cu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!zs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ji=zs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Pb=Ji?Cu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ot=Ji?Pb.fetch:window.fetch,N0=Ji?Pb.Request:window.Request,Ee=Ji?Xi:window.AbortController,F0=Ji?ri:window.AbortSignal;var ll=G(Ou(),1);var sn=G(ei(),1);var kt=()=>window.ManagedMediaSource||window.MediaSource,Ks=()=>{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))},Gb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var vt=require("@vkontakte/videoplayer-shared/es2018"),Ke=document.createElement("video"),uk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',lk='video/mp4; codecs="hev1.1.6.L93.B0"',ig='video/webm; codecs="vp09.00.10.08"',ag='video/webm; codecs="av01.0.00M.08"',ck='audio/mp4; codecs="mp4a.40.2"',dk='audio/webm; codecs="opus"',Wb,Yb,Zi={mms:Ks(),mse:Qb(),hls:!!((Wb=Ke.canPlayType)!=null&&Wb.call(Ke,"application/x-mpegurl")||(Yb=Ke.canPlayType)!=null&&Yb.call(Ke,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},zb,Kb,Oe={mp4:!!((zb=Ke.canPlayType)!=null&&zb.call(Ke,"video/mp4")),webm:!!((Kb=Ke.canPlayType)!=null&&Kb.call(Ke,"video/webm")),cmaf:!0},Js,Xb,Zs,Jb,en,Zb,tn,eg,rn,tg,an,rg,Be={h264:!!((Xb=(Js=kt())==null?void 0:Js.isTypeSupported)!=null&&Xb.call(Js,uk)),h265:!!((Jb=(Zs=kt())==null?void 0:Zs.isTypeSupported)!=null&&Jb.call(Zs,lk)),vp9:!!((Zb=(en=kt())==null?void 0:en.isTypeSupported)!=null&&Zb.call(en,ig)),av1:!!((eg=(tn=kt())==null?void 0:tn.isTypeSupported)!=null&&eg.call(tn,ag)),aac:!!((tg=(rn=kt())==null?void 0:rn.isTypeSupported)!=null&&tg.call(rn,ck)),opus:!!((rg=(an=kt())==null?void 0:an.isTypeSupported)!=null&&rg.call(an,dk))},ii=(Be.h264||Be.h265)&&Be.aac,gr,pk=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:ag}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:ig}})]);gr={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{pk()}catch(a){console.error(a)}var ai=Zi.hls&&Oe.mp4,sg=()=>Object.keys(Be).filter(a=>Be[a]),ng=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Zi.mse&&(!r||!!window.MediaStreamTrack)||Zi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Oe.mp4&&ii;case"DASH_WEBM":return i&&Oe.webm&&Be.vp9&&Be.opus;case"DASH_WEBM_AV1":return i&&Oe.webm&&Be.av1&&Be.opus;case"DASH_STREAMS":return i&&(Oe.mp4&&ii||Oe.webm&&(Be.vp9||Be.av1)&&(Be.opus||Be.aac));case"DASH_LIVE":return i&&Oe.mp4&&ii;case"DASH_LIVE_CMAF":return i&&Oe.mp4&&ii&&Oe.cmaf;case"DASH_ONDEMAND":return i&&Oe.mp4&&ii;case"HLS":case"HLS_ONDEMAND":return ai||e&&i&&Oe.mp4&&ii;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ai;case"MPEG":return Oe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Zi.webrtc&&Zi.ws&&Be.h264&&(Oe.mp4||Oe.webm);default:return(0,vt.assertNever)(s)}})},Xs=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 gr?gr[t].smooth?[t,e]:gr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return gr?gr[t].powerEfficient?[t,e]:gr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,vt.assertNever)(a)}return[e,t]},og=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Xs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(vt.clientChecker.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",...Xs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Xs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Xs(a),...i,"HLS","HLS_ONDEMAND"];default:(0,vt.assertNever)(e)}return ai?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},ug=({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=vt.clientChecker.isMac&&vt.clientChecker.isSafari;if(vt.clientChecker.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:(0,vt.assertNever)(a)}else ai&&!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"]},Bu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],lg=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,sn.default)(t.value.split("."),0)}for(let t of a){let r=(0,sn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,sn.default)(e.value.split("."),0)};var Lg=G(Rg(),1),si=require("@vkontakte/videoplayer-shared/es2018"),$g=a=>{if(!a)return{id:"EmptyResponse",category:si.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:si.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,Lg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:si.ErrorCategory.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:si.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:si.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Xt=(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};var S=require("@vkontakte/videoplayer-shared/es2018");var nn=G(st(),1),ui=G(ei(),1),on=G(Ou(),1);var Rk=(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)},Lk=a=>window.clearTimeout(a),Mg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Dg=!Mg(window.requestIdleCallback)||!Mg(window.cancelIdleCallback),Uu=Dg?Rk:window.requestIdleCallback,ta=Dg?Lk:window.cancelIdleCallback;var Nv=G(_s(),1);var Xe=require("@vkontakte/videoplayer-shared/es2018"),$k=18,Cg=!1;try{Cg=Xe.clientChecker.isSafari&&!!Xe.clientChecker.macVersion&&Xe.clientChecker.macVersion<=$k}catch(a){console.error(a)}var Hu=class{constructor(e){this.bufferFull$=new Xe.Subject;this.error$=new Xe.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Xe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};Cg&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Xe.ErrorCategory.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:(0,Xe.assertNever)(t)}}},Vg=Hu;var ju=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var T=require("@vkontakte/videoplayer-shared/es2018");var te=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 ni=class extends te{};var ra=class extends te{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 ia=class extends te{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 aa=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var le=class extends te{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var sa=class extends le{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 na=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends te{constructor(e,t){super(e,t),this.data=this.content}};var vr=class extends le{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 ua=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var la=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ca=class extends le{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 da=class extends le{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var pa=class extends le{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ha=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends le{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 ma=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ba=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ga=class extends le{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var va=class extends te{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Sa=class extends le{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 ya=class extends le{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 Ta=class extends le{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 Dk={ftyp:ia,moov:aa,mvhd:sa,moof:na,mdat:oa,sidx:vr,trak:ua,mdia:ha,mfhd:ga,tkhd:fa,traf:va,tfhd:Sa,tfdt:ya,trun:Ta,minf:ma,sv3d:la,st3d:ca,prhd:da,proj:ba,equi:pa,uuid:ra,unknown:ni},Rt=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=Dk[e];return r?new r(t,new a):new ni(t,new a)}};var Jt=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 Vk=new TextDecoder("ascii"),Ok=a=>Vk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Bk=a=>{let e=new vr(a,new Rt),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})},_k=(a,e)=>{let r=new Rt().parse(a),i=new Jt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},Nk=a=>{let t=new Rt().parse(a),r=new Jt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},Fk=a=>{var i;let t=new Rt().parse(a);return(i=new Jt(t).find("sidx"))==null?void 0:i.timescale},qk=(a,e)=>{let r=new Rt().parse(a),s=new Jt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Uk=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 Rt().parse(a),i=new Jt(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},Og={validateData:Ok,parseInit:Uk,getIndexRange:()=>{},parseSegments:Bk,parseFeedableSegmentChunk:_k,getChunkEndTime:qk,getServerLatencyTimestamps:Nk,getTimescaleFromIndex:Fk};var Ea=G(st(),1),Lt=require("@vkontakte/videoplayer-shared/es2018");var _g=require("@vkontakte/videoplayer-shared/es2018");var Bg={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"}},Ng=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=Ia(a,t),i=r in Bg,s=i?Bg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Ia(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Ia=(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},ut=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ia(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:(0,_g.assertNever)(e)}},Sr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Ng(r);if(!e(i))return;i.type==="master"&&Sr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Fg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Ng(a);return Sr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=ut(o,n):s===17026?t=ut(o,n):s===17029&&(r=ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var qg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Hk=[231,22612,22743,167,171,163,160,175],jk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Sr(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let v=ut(m,h);l=Ia(v)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=ut(m,h):p===17545?i=ut(m,h):p===21420&&l===475249515?u=ut(m,h):p===374648427?Sr(m,({tag:v,type:I,value:E})=>v===30321?(c=ut(E,I)===1,!1):!0):s&&n&&(0,Ea.default)(qg,p)&&(o=!0),!o}),(0,Lt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Lt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Lt.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Qk=a=>{if((0,Lt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Gk=(a,e)=>{let t=!1,r=!1,i=o=>(0,Lt.isNonNullable)(o.time)&&(0,Lt.isNonNullable)(o.position),s=[],n;return Sr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=ut(l,u));break;case 183:break;case 241:n&&(n.position=ut(l,u));break;default:t&&(0,Ea.default)(qg,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Wk=a=>{let e=0,t=!1;try{Sr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Ea.default)(Hk,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Ea.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},Ug={validateData:Fg,parseInit:jk,getIndexRange:Qk,parseSegments:Gk,parseFeedableSegmentChunk:Wk};var xa=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Ug;case"mp4":return Og}}throw new ReferenceError(`Unsupported mime type ${a}`)};var il=G(uv(),1),Cv=G(Hr(),1),Vv=G(xv(),1),Ov=G(ei(),1),al=G(Zr(),1);var Pv=G(st(),1),Xu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,Pv.default)(["6E","7A","F4"],o)}}return!1};var wa=require("@vkontakte/videoplayer-shared/es2018");var wv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Av=a=>{var e;try{let t=UR(),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 UR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
64
64
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
65
65
  (-(?<script>[a-z]{4}))?
66
66
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
67
67
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
68
68
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
69
69
  (?:-(?<privateuse>(?:${e})))?
70
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Xu=W(Zr(),1);var Pv=require("@vkontakte/videoplayer-shared/es2018"),wv=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?zt(s):void 0)!=null?u:(0,Pv.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Av=({id:a,bitrate:e})=>({id:a,bitrate:e}),kv=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Rv=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Ju=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Xu.default)(r.split("."),0),isDefault:i}),Zu=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Xu.default)(i.split("."),0)}),el=a=>"url"in a,ke=a=>a.type==="template",Ea=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var $v=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Lt=(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,Lv.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,tl.default)(t,n,(o,u)=>(0,xa.isNullable)(s)?o:(0,xa.isNullable)(u)?s:(0,Mv.default)(s,parseInt(u,10),"0"))}return t},Cv=(a,e)=>{var w,j,Q,ee,Y,X,J,C,_,ie,pe,R,P,q,N,fe,je,Ot,xr,Z,Se,ye,Ge,Vt,Pr,Bt,rr,wr,ci,bl,gl,vl,Sl,yl,Tl,Il,El,xl,Pl,wl,Al,kl,Rl,$l,Ll,Ml,Dl,Cl,Ol,Vl,Bl,_l,Nl,Fl,ql,Ul,Hl,jl,Gl,Ql;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Ze=>{var se,ir;return(ir=(se=Ze.textContent)==null?void 0:se.trim())!=null?ir:""}),o=(w=(0,Dv.default)(n,0))!=null?w:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],f=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g=[...s.getElementsByTagName("Period")],v=g.reduce((Ze,se)=>({...Ze,[se.id]:se.children}),{}),T=g.reduce((Ze,se)=>({...Ze,[se.id]:se.getAttribute("duration")}),{});p?d=$v(p):(0,rl.default)(T).filter(Ze=>Ze).length&&!u?d=(0,rl.default)(T).reduce((Ze,se)=>{var ir;return Ze+((ir=$v(se))!=null?ir:0)},0):f&&(d=parseInt(f,10));let E=0,x=(Q=(j=s.getAttribute("profiles"))==null?void 0:j.split(","))!=null?Q:[];for(let Ze of g.map(se=>se.id))for(let se of v[Ze]){let ir=(ee=se.getAttribute("id"))!=null?ee:"id"+(E++).toString(10),di=(Y=se.getAttribute("mimeType"))!=null?Y:"",Tn=(X=se.getAttribute("codecs"))!=null?X:"",In=(J=se.getAttribute("contentType"))!=null?J:di==null?void 0:di.split("/")[0],mS=(_=(C=se.getAttribute("profiles"))==null?void 0:C.split(","))!=null?_:[],Wl=(pe=xv((ie=se.getAttribute("lang"))!=null?ie:""))!=null?pe:{},fS=(q=(P=(R=se.querySelector("Label"))==null?void 0:R.textContent)==null?void 0:P.trim())!=null?q:void 0,bS=se.querySelectorAll("Representation"),gS=se.querySelector("SegmentTemplate"),vS=(fe=(N=se.querySelector("Role"))==null?void 0:N.getAttribute("value"))!=null?fe:void 0,Ar=In,ce={id:ir,language:Wl.language,isDefault:vS==="main",label:fS,codecs:Tn,hdr:Ar==="video"&&zu(Tn),mime:di,representations:[]};for(let ae of bS){let _t=(je=ae.getAttribute("lang"))!=null?je:void 0,pi=(Ot=ae.getAttribute("label"))!=null?Ot:void 0,ja=(Se=(Z=(xr=ae.querySelector("BaseURL"))==null?void 0:xr.textContent)==null?void 0:Z.trim())!=null?Se:"",ar=new URL(ja||o,e).toString(),Nt=(ye=ae.getAttribute("mimeType"))!=null?ye:di,Ga=(Vt=(Ge=ae.getAttribute("codecs"))!=null?Ge:Tn)!=null?Vt:"",Qa;if(In==="text"){let Ft=ae.getAttribute("id")||"",Wa=((Pr=Wl.privateuse)==null?void 0:Pr.includes("x-auto"))||Ft.includes("_auto"),sr=ae.querySelector("SegmentTemplate");if(sr){let hi={representationId:(Bt=ae.getAttribute("id"))!=null?Bt:void 0,bandwidth:(rr=ae.getAttribute("bandwidth"))!=null?rr:void 0},Ya=parseInt((wr=ae.getAttribute("bandwidth"))!=null?wr:"",10)/1e3,za=(bl=parseInt((ci=sr.getAttribute("startNumber"))!=null?ci:"",10))!=null?bl:1,kr=parseInt((gl=sr.getAttribute("timescale"))!=null?gl:"",10),En=(vl=sr.querySelectorAll("SegmentTimeline S"))!=null?vl:[],Rr=sr.getAttribute("media");if(!Rr)continue;let Ka=[],Xa=0,Ja="",$r=0,mi=za,Pe=0;for(let et of En){let nr=parseInt((Sl=et.getAttribute("d"))!=null?Sl:"",10),Qe=parseInt((yl=et.getAttribute("r"))!=null?yl:"",10)||0,qt=parseInt((Tl=et.getAttribute("t"))!=null?Tl:"",10);Pe=Number.isFinite(qt)?qt:Pe;let or=nr/kr*1e3,Ut=Pe/kr*1e3;for(let ct=0;ct<Qe+1;ct++){let Ht=Lt(Rr,{...hi,segmentNumber:mi.toString(10),segmentTime:(Pe+ct*nr).toString(10)}),Lr=(Ut!=null?Ut:0)+ct*or,bi=Lr+or;mi++,Ka.push({time:{from:Lr,to:bi},url:Ht})}Pe+=(Qe+1)*nr,Xa+=(Qe+1)*or}$r=Pe/kr*1e3,Ja=Lt(Rr,{...hi,segmentNumber:mi.toString(10),segmentTime:Pe.toString(10)});let fi={time:{from:$r,to:1/0},url:Ja},yt={type:"template",baseUrl:ar,segmentTemplateUrl:Rr,initUrl:"",totalSegmentsDurationMs:Xa,segments:Ka,nextSegmentBeyondManifest:fi,timescale:kr};Qa={id:Ft,kind:"text",segmentReference:yt,profiles:[],duration:d,bitrate:Ya,mime:"",codecs:"",width:0,height:0,isAuto:Wa}}else Qa={id:Ft,isAuto:Wa,kind:"text",url:ar}}else{let Ft=(El=(Il=ae.getAttribute("contentType"))!=null?Il:Nt==null?void 0:Nt.split("/")[0])!=null?El:In,Wa=(Pl=(xl=se.getAttribute("profiles"))==null?void 0:xl.split(","))!=null?Pl:[],sr=parseInt((wl=ae.getAttribute("width"))!=null?wl:"",10),hi=parseInt((Al=ae.getAttribute("height"))!=null?Al:"",10),Ya=parseInt((kl=ae.getAttribute("bandwidth"))!=null?kl:"",10)/1e3,za=(Rl=ae.getAttribute("frameRate"))!=null?Rl:"",kr=($l=ae.getAttribute("quality"))!=null?$l:void 0,En=za?Ev(za):void 0,Rr=(Ll=ae.getAttribute("id"))!=null?Ll:"id"+(E++).toString(10),Ka=Ft==="video"?`${hi}p`:Ft==="audio"?`${Ya}Kbps`:Ga,Xa=`${Rr}@${Ka}`,Ja=[...x,...mS,...Wa],$r,mi=ae.querySelector("SegmentBase"),Pe=(Ml=ae.querySelector("SegmentTemplate"))!=null?Ml:gS;if(mi){let yt=(Cl=(Dl=ae.querySelector("SegmentBase Initialization"))==null?void 0:Dl.getAttribute("range"))!=null?Cl:"",[et,nr]=yt.split("-").map(Ht=>parseInt(Ht,10)),Qe={from:et,to:nr},qt=(Ol=ae.querySelector("SegmentBase"))==null?void 0:Ol.getAttribute("indexRange"),[or,Ut]=qt?qt.split("-").map(Ht=>parseInt(Ht,10)):[],ct=qt?{from:or,to:Ut}:void 0;$r={type:"byteRange",url:ar,initRange:Qe,indexRange:ct}}else if(Pe){let yt={representationId:(Vl=ae.getAttribute("id"))!=null?Vl:void 0,bandwidth:(Bl=ae.getAttribute("bandwidth"))!=null?Bl:void 0},et=parseInt((_l=Pe.getAttribute("timescale"))!=null?_l:"",10),nr=(Nl=Pe.getAttribute("initialization"))!=null?Nl:"",Qe=Pe.getAttribute("media"),qt=(ql=parseInt((Fl=Pe.getAttribute("startNumber"))!=null?Fl:"",10))!=null?ql:1,or=Lt(nr,yt);if(!Qe)throw new ReferenceError("No media attribute in SegmentTemplate");let Ut=(Ul=Pe.querySelectorAll("SegmentTimeline S"))!=null?Ul:[],ct=[],Ht=0,Lr="",bi=0;if(Ut.length){let Za=qt,tt=0;for(let Mr of Ut){let dt=parseInt((Hl=Mr.getAttribute("d"))!=null?Hl:"",10),ur=parseInt((jl=Mr.getAttribute("r"))!=null?jl:"",10)||0,es=parseInt((Gl=Mr.getAttribute("t"))!=null?Gl:"",10);tt=Number.isFinite(es)?es:tt;let xn=dt/et*1e3,Pn=tt/et*1e3;for(let ts=0;ts<ur+1;ts++){let yS=Lt(Qe,{...yt,segmentNumber:Za.toString(10),segmentTime:(tt+ts*dt).toString(10)}),Yl=(Pn!=null?Pn:0)+ts*xn,TS=Yl+xn;Za++,ct.push({time:{from:Yl,to:TS},url:yS})}tt+=(ur+1)*dt,Ht+=(ur+1)*xn}bi=tt/et*1e3,Lr=Lt(Qe,{...yt,segmentNumber:Za.toString(10),segmentTime:tt.toString(10)})}else if((0,xa.isNonNullable)(d)){let tt=parseInt((Ql=Pe.getAttribute("duration"))!=null?Ql:"",10)/et*1e3,Mr=Math.ceil(d/tt),dt=0;for(let ur=1;ur<Mr;ur++){let es=Lt(Qe,{...yt,segmentNumber:ur.toString(10),segmentTime:dt.toString(10)});ct.push({time:{from:dt,to:dt+tt},url:es}),dt+=tt}bi=dt,Lr=Lt(Qe,{...yt,segmentNumber:Mr.toString(10),segmentTime:dt.toString(10)})}let SS={time:{from:bi,to:1/0},url:Lr};$r={type:"template",baseUrl:ar,segmentTemplateUrl:Qe,initUrl:or,totalSegmentsDurationMs:Ht,segments:ct,nextSegmentBeyondManifest:SS,timescale:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ft||!Nt)continue;let fi={video:"video",audio:"audio",text:"text"}[Ft];if(!fi)continue;Ar||(Ar=fi),Qa={id:Xa,kind:fi,segmentReference:$r,profiles:Ja,duration:d,bitrate:Ya,mime:Nt,codecs:Ga,width:sr,height:hi,fps:En,quality:kr}}ce.language||(ce.language=_t),ce.label||(ce.label=pi),ce.mime||(ce.mime=Nt),ce.codecs||(ce.codecs=Ga),ce.hdr||(ce.hdr=Ar==="video"&&zu(Ga)),ce.representations.push(Qa)}if(Ar){let ae=i[Ar].find(_t=>_t.id===ce.id);if(ae&&ce.representations.every(_t=>ke(_t.segmentReference)))for(let _t of ae.representations){let pi=ce.representations.find(Nt=>Nt.id===_t.id),ja=pi==null?void 0:pi.segmentReference,ar=_t.segmentReference;ar.segments.push(...ja.segments),ar.nextSegmentBeyondManifest=ja.nextSegmentBeyondManifest}else i[Ar].push(ce)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var Ov=W(st(),1),al=require("@vkontakte/videoplayer-shared/es2018"),Ve=(a,e)=>(0,al.isNonNullable)(a)&&(0,al.isNonNullable)(e)&&a.readyState==="open"&&(0,Ov.default)([...a.activeSourceBuffers],e);var Pa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new I.ValueSubject(0);this.currentLowLatencySegmentLength$=new I.ValueSubject(0);this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new xe;this.switchAbortController=new xe;this.destroyAbortController=new xe;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=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,I.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Mg(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Ve(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Uu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=gt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,I.assertNonNullable)(r,"No init buffer for starting representation"),(0,I.assertNonNullable)(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=(0,I.abortable)(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);(0,I.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,I.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,I.isNonNullable)(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=(0,I.abortable)(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,sn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!ke(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);(0,I.assertNonNullable)(i);let s=this.segments.get(r);(0,I.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,I.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new xe,(0,I.abortable)(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,I.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,I.isNullable)(o)||(0,I.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,I.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,I.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,I.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new xe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||!Ve(this.mediaSource,this.sourceBuffer)||(0,I.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);(0,I.isNonNullable)(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=gt(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Uu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=gt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,an.default)(o,i))l="high";else{let c=(0,oi.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&gt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,oi.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;(0,I.isNonNullable)(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,sn.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,sn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!ke(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,oi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,I.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!ke(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=Lt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Zi&&Zi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Zi&&Zi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let g=p<=r&&h>=r,v=p>r||g||f===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&p<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&v&&E&&this.sourceBuffer&&Ve(this.mediaSource,this.sourceBuffer)&&!(Jt(this.sourceBuffer.buffered,p)&&Jt(this.sourceBuffer.buffered,h)))&&v&&E});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){ke(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(0,I.abortable)(o,async function*(){let c=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,I.now)(),!c)return;let d=new DataView(c),p=Ia(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,g)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ea(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ke(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(0,I.abortable)(n,async function*(){let u=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).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=(0,I.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ea(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ke(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,oi.default)(e,0).byte.from,to:(0,oi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ke(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,I.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,an.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Ia(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,f=d<=i;if(!h)continue;let g=Ia(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),T=u.loadedBytes===p?v:g.parseFeedableSegmentChunk(v);T!=null&&T.byteLength&&(l.status="partially_fed",u.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,s)&&!s.aborted?(u.fedBytes+=T.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var r;if(!((0,I.isNullable)(this.sourceBuffer)||!Ve(this.mediaSource,this.sourceBuffer))){!this.isLive&&I.clientChecker.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Jt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Jt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",el(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Fu(()=>(0,Vv.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?(0,I.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ia(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&ke(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:I.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,I.isNullable)(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=el(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,an.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,I.isNullable)(e)?0:gt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer)))for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer))){for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Fu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||!Ve(this.mediaSource,this.sourceBuffer)||(0,I.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var wa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Bv=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}};var z=require("@vkontakte/videoplayer-shared/es2018");var _v=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var nn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new z.ValueSubject(void 0);this.lastConnectionReused$=new z.ValueSubject(void 0);this.lastRequestFirstBytes$=new z.ValueSubject(void 0);this.abortAllController=new xe;this.subscription=new z.Subscription;this.fetchManifest=(0,z.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=wa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=_v(r));let i=yield ot(r,{signal:this.abortAllController.signal}).catch(Aa);return i?(t.log("success",(0,z.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,z.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,z.abortable)(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 J,C;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),l=_.toString();break}default:(0,z.assertNever)(t)}this.requestQuic&&(l=wa(l));let p=this.abortAllController.signal,h;if(n){let _=new xe;if(h=(0,z.merge)((0,z.fromEvent)(this.abortAllController.signal,"abort"),(0,z.fromEvent)(n,"abort")).subscribe(()=>{try{_.abort()}catch(ie){Aa(ie)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(ie){Aa(ie)}p=_.signal}let f=(0,z.now)();d.log("startRequest",(0,z.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let g=yield ot(l,{priority:s,headers:c,signal:p}).catch(Aa),v=(0,z.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((J=this.throughputEstimator)==null||J.addRawRtt(v-f),!g.ok||!g.body){h==null||h.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:_}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){h==null||h.unsubscribe();let _=(0,z.now)(),ie={requestStartedAt:f,requestEndedAt:_,duration:_-f};return d.log("endRequest",(0,z.flattenObject)(ie)),d.end(),g.arrayBuffer()}let[T,E]=g.body.tee(),x=T.getReader();o&&((C=this.throughputEstimator)==null||C.trackStream(E,u));let k=0,w=new Uint8Array(0),j=!1,Q=_=>{h==null||h.unsubscribe(),j=!0,Aa(_)},ee=(0,z.abortable)(p,async function*({done:_,value:ie}){if(k===0&&this.lastRequestFirstBytes$.next((0,z.now)()-f),p.aborted){h==null||h.unsubscribe();return}if(!_&&ie){let pe=new Uint8Array(w.length+ie.length);pe.set(w),pe.set(ie,w.length),w=pe,k+=ie.byteLength,i==null||i(new DataView(w.buffer),k),yield x==null?void 0:x.read().then(ee,Q)}}.bind(this));yield x==null?void 0:x.read().then(ee,Q),h==null||h.unsubscribe();let Y=(0,z.now)(),X={failed:j,requestStartedAt:f,requestEndedAt:Y,duration:Y-f};return j?(d.error("endRequest",(0,z.flattenObject)(X)),d.end(),null):(d.log("endRequest",(0,z.flattenObject)(X)),d.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,z.abortable)(this.abortAllController.signal,async function*(e,t,r){var T;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(T=e.indexRange)!=null?T:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,f.from-n,f.to-f.from+1);else{let E=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let v=t.parseSegments(g,h,f);return{init:h,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,z.abortable)(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}=Bv(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:(0,z.assertNever)(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Aa=a=>{if(!Ea(a))throw a};var Tr=(a,e,t)=>t*e+(1-t)*a,sl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Nv=(a,e,t,r)=>{let i=0,s=t,n=sl(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};var ka=require("@vkontakte/videoplayer-shared/es2018"),er=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 ka.ValueSubject(e.initial),this.debounced$=new ka.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ae(`raw_${t}`),this.smoothedSeries$=new Ae(`smoothed_${t}`),this.reportedSeries$=new Ae(`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)&&((0,ka.isNullable)(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 on=class extends er{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Tr(this.slow,e,this.params.emaAlphaSlow),this.fast=Tr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var un=class extends er{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=sl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Tr(this.emaSmoothed,e,this.params.emaAlpha);let r=Nv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var ln=class extends er{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?Tr(this.smoothed,t,this.params.emaAlpha):t}};var Ir=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new on({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new un({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 ln({initial:e,label:"liveEdgeDelay",...t})}};var nl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var cn=require("@vkontakte/videoplayer-shared/es2018");var Ra=class a{constructor(e,t){this.currentRepresentation$=new cn.ValueSubject(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(!(0,cn.isNullable)(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ke(t.segmentReference))}};var qR=["timeupdate","progress","play","seeked","stalled","waiting"],UR=["timeupdate","progress","loadeddata","playing","seeked"];var dn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new U("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.isLowLatency$=new S.ValueSubject(!1);this.isActiveLowLatency$=new S.ValueSubject(!1);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new xe;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ee(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:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(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:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Cv(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=kg(e))!=null?n:{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=kt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=ng(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(v=>v.hdr),g=i.video.some(v=>!v.hdr);S.clientChecker.isHDR&&h&&f?i.video=i.video.filter(v=>v.hdr):g&&(i.video=i.video.filter(v=>!v.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Hb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ys())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Pa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new Pa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ra.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ra(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((0,S.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=_s(this.manifestUrlString,2);this.manifestUrlString=Ee(this.manifestUrlString,f+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...UR.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?gt(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(h=>nl(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add((0,S.combine)({isActiveLowLatency:this.isActiveLowLatency$.pipe((0,S.filterChanged)()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe((0,S.filter)(({isActiveLowLatency:h,currentLowLatencySegmentLength:f})=>h&&!!f)).subscribe(({currentLowLatencySegmentLength:h})=>{let f=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(f,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:h})=>h),(0,S.map)(h=>({...h})),(0,S.filterChanged)((h,f)=>f.bufferLength<h.bufferLength),(0,S.map)(({rtt:h,bufferLength:f,segmentServerLatency:g})=>{let v=_s(this.manifestUrlString,2);return(h/2+f+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:f})=>{if(!f)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-g,x=1;Math.abs(E)>v&&(x=1+Math.sign(E)*T),nl(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,v;let f=0;if(h){let T=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;f=Math.min(...this.bufferManagers.map(x=>{var k,w;return(w=(k=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:k.to)!=null?w:T}))-T}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=_s(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,w=isFinite(h)?h:f,j=this.isActiveLowLatency$.getValue(),Q=T<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(j&&Q);let ee="none";if(j?ee="active_low_latency":this.isLowLatency$.getValue()&&Q?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Y=>Y.proceedLowLatencyLive()),ee="active_low_latency"):v!==0&&w<E?ee="live_forward_buffering":w<E+k&&(ee="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),ee==="live_forward_buffering"||ee==="live_with_target_offset"){let Y=p-(E+x),X=this.normolizeLiveOffset(Math.trunc(v+Y/g)),J=Math.abs(X-v),C;!h||J<=this.tuning.dashCmafLive.offsetCalculationError?C=v:X>0&&J>this.tuning.dashCmafLive.offsetCalculationError?C=X:C=0,this.manifestUrlString=Ee(this.manifestUrlString,C,2)}ee!=="none"&&ee!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,ol.default)((0,ol.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),ke(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,S.isNonNullable)(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=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.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 nn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Ir.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Ee(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(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...qR.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Jt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,g,v,T,E,x,k,w,j;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=(0,S.now)(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(E=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?E:0,c=(k=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?k:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let Q=this.element.currentTime*1e3;(w=this.videoBufferManager)==null||w.maintain(Q),(j=this.audioBufferManager)==null||j.maintain(Q),i.position=Q}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}async seek(e,t){var i,s,n,o,u;(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(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),Jt(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,S.getTraceSubscriptionMethod)(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",(0,S.flattenObject)(t)))}}};var pn=class{constructor(e,t){this.fov=e,this.orientation=t}};var hn=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 qv=`attribute vec2 a_vertex;
70
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Zu=G(ei(),1);var kv=require("@vkontakte/videoplayer-shared/es2018"),Rv=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Yt(s):void 0)!=null?u:(0,kv.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Lv=({id:a,bitrate:e})=>({id:a,bitrate:e}),$v=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Mv=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),el=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Zu.default)(r.split("."),0),isDefault:i}),tl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Zu.default)(i.split("."),0)}),rl=a=>"url"in a,Re=a=>a.type==="template",Pa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Dv=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},$t=(a,e)=>{let t=a;t=(0,il.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Cv.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,il.default)(t,n,(o,u)=>(0,wa.isNullable)(s)?o:(0,wa.isNullable)(u)?s:(0,Vv.default)(s,parseInt(u,10),"0"))}return t},Bv=(a,e)=>{var w,F,j,ee,W,K,X,C,_,ie,he,R,P,Q,ae,J,Ne,di,xr,Z,Se,xe,Pe,Vt,Pr,Ot,tr,wr,pi,vl,Sl,yl,Tl,Il,El,xl,Pl,wl,Al,kl,Rl,Ll,$l,Ml,Dl,Cl,Vl,Ol,Bl,_l,Nl,Fl,ql,Ul,Hl,jl,Ql,Gl,Wl,Yl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Ze=>{var ne,rr;return(rr=(ne=Ze.textContent)==null?void 0:ne.trim())!=null?rr:""}),o=(w=(0,Ov.default)(n,0))!=null?w:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],m=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g=[...s.getElementsByTagName("Period")],v=g.reduce((Ze,ne)=>({...Ze,[ne.id]:ne.children}),{}),I=g.reduce((Ze,ne)=>({...Ze,[ne.id]:ne.getAttribute("duration")}),{});p?d=Dv(p):(0,al.default)(I).filter(Ze=>Ze).length&&!u?d=(0,al.default)(I).reduce((Ze,ne)=>{var rr;return Ze+((rr=Dv(ne))!=null?rr:0)},0):m&&(d=parseInt(m,10));let E=0,x=(j=(F=s.getAttribute("profiles"))==null?void 0:F.split(","))!=null?j:[];for(let Ze of g.map(ne=>ne.id))for(let ne of v[Ze]){let rr=(ee=ne.getAttribute("id"))!=null?ee:"id"+(E++).toString(10),hi=(W=ne.getAttribute("mimeType"))!=null?W:"",En=(K=ne.getAttribute("codecs"))!=null?K:"",xn=(X=ne.getAttribute("contentType"))!=null?X:hi==null?void 0:hi.split("/")[0],gS=(_=(C=ne.getAttribute("profiles"))==null?void 0:C.split(","))!=null?_:[],zl=(he=Av((ie=ne.getAttribute("lang"))!=null?ie:""))!=null?he:{},vS=(Q=(P=(R=ne.querySelector("Label"))==null?void 0:R.textContent)==null?void 0:P.trim())!=null?Q:void 0,SS=ne.querySelectorAll("Representation"),yS=ne.querySelector("SegmentTemplate"),TS=(J=(ae=ne.querySelector("Role"))==null?void 0:ae.getAttribute("value"))!=null?J:void 0,Ar=xn,de={id:rr,language:zl.language,isDefault:TS==="main",label:vS,codecs:En,hdr:Ar==="video"&&Xu(En),mime:hi,representations:[]};for(let se of SS){let Bt=(Ne=se.getAttribute("lang"))!=null?Ne:void 0,fi=(di=se.getAttribute("label"))!=null?di:void 0,Qa=(Se=(Z=(xr=se.querySelector("BaseURL"))==null?void 0:xr.textContent)==null?void 0:Z.trim())!=null?Se:"",ir=new URL(Qa||o,e).toString(),_t=(xe=se.getAttribute("mimeType"))!=null?xe:hi,Ga=(Vt=(Pe=se.getAttribute("codecs"))!=null?Pe:En)!=null?Vt:"",Wa;if(xn==="text"){let Nt=se.getAttribute("id")||"",Ya=((Pr=zl.privateuse)==null?void 0:Pr.includes("x-auto"))||Nt.includes("_auto"),ar=se.querySelector("SegmentTemplate");if(ar){let mi={representationId:(Ot=se.getAttribute("id"))!=null?Ot:void 0,bandwidth:(tr=se.getAttribute("bandwidth"))!=null?tr:void 0},za=parseInt((wr=se.getAttribute("bandwidth"))!=null?wr:"",10)/1e3,Ka=(vl=parseInt((pi=ar.getAttribute("startNumber"))!=null?pi:"",10))!=null?vl:1,kr=parseInt((Sl=ar.getAttribute("timescale"))!=null?Sl:"",10),Pn=(yl=ar.querySelectorAll("SegmentTimeline S"))!=null?yl:[],Rr=ar.getAttribute("media");if(!Rr)continue;let Xa=[],Ja=0,Za="",Lr=0,bi=Ka,we=0;for(let et of Pn){let sr=parseInt((Tl=et.getAttribute("d"))!=null?Tl:"",10),Ge=parseInt((Il=et.getAttribute("r"))!=null?Il:"",10)||0,Ft=parseInt((El=et.getAttribute("t"))!=null?El:"",10);we=Number.isFinite(Ft)?Ft:we;let nr=sr/kr*1e3,qt=we/kr*1e3;for(let ct=0;ct<Ge+1;ct++){let Ut=$t(Rr,{...mi,segmentNumber:bi.toString(10),segmentTime:(we+ct*sr).toString(10)}),$r=(qt!=null?qt:0)+ct*nr,vi=$r+nr;bi++,Xa.push({time:{from:$r,to:vi},url:Ut})}we+=(Ge+1)*sr,Ja+=(Ge+1)*nr}Lr=we/kr*1e3,Za=$t(Rr,{...mi,segmentNumber:bi.toString(10),segmentTime:we.toString(10)});let gi={time:{from:Lr,to:1/0},url:Za},yt={type:"template",baseUrl:ir,segmentTemplateUrl:Rr,initUrl:"",totalSegmentsDurationMs:Ja,segments:Xa,nextSegmentBeyondManifest:gi,timescale:kr};Wa={id:Nt,kind:"text",segmentReference:yt,profiles:[],duration:d,bitrate:za,mime:"",codecs:"",width:0,height:0,isAuto:Ya}}else Wa={id:Nt,isAuto:Ya,kind:"text",url:ir}}else{let Nt=(Pl=(xl=se.getAttribute("contentType"))!=null?xl:_t==null?void 0:_t.split("/")[0])!=null?Pl:xn,Ya=(Al=(wl=ne.getAttribute("profiles"))==null?void 0:wl.split(","))!=null?Al:[],ar=parseInt((kl=se.getAttribute("width"))!=null?kl:"",10),mi=parseInt((Rl=se.getAttribute("height"))!=null?Rl:"",10),za=parseInt((Ll=se.getAttribute("bandwidth"))!=null?Ll:"",10)/1e3,Ka=($l=se.getAttribute("frameRate"))!=null?$l:"",kr=(Ml=se.getAttribute("quality"))!=null?Ml:void 0,Pn=Ka?wv(Ka):void 0,Rr=(Dl=se.getAttribute("id"))!=null?Dl:"id"+(E++).toString(10),Xa=Nt==="video"?`${mi}p`:Nt==="audio"?`${za}Kbps`:Ga,Ja=`${Rr}@${Xa}`,Za=[...x,...gS,...Ya],Lr,bi=se.querySelector("SegmentBase"),we=(Cl=se.querySelector("SegmentTemplate"))!=null?Cl:yS;if(bi){let yt=(Ol=(Vl=se.querySelector("SegmentBase Initialization"))==null?void 0:Vl.getAttribute("range"))!=null?Ol:"",[et,sr]=yt.split("-").map(Ut=>parseInt(Ut,10)),Ge={from:et,to:sr},Ft=(Bl=se.querySelector("SegmentBase"))==null?void 0:Bl.getAttribute("indexRange"),[nr,qt]=Ft?Ft.split("-").map(Ut=>parseInt(Ut,10)):[],ct=Ft?{from:nr,to:qt}:void 0;Lr={type:"byteRange",url:ir,initRange:Ge,indexRange:ct}}else if(we){let yt={representationId:(_l=se.getAttribute("id"))!=null?_l:void 0,bandwidth:(Nl=se.getAttribute("bandwidth"))!=null?Nl:void 0},et=parseInt((Fl=we.getAttribute("timescale"))!=null?Fl:"",10),sr=(ql=we.getAttribute("initialization"))!=null?ql:"",Ge=we.getAttribute("media"),Ft=(Hl=parseInt((Ul=we.getAttribute("startNumber"))!=null?Ul:"",10))!=null?Hl:1,nr=$t(sr,yt);if(!Ge)throw new ReferenceError("No media attribute in SegmentTemplate");let qt=(jl=we.querySelectorAll("SegmentTimeline S"))!=null?jl:[],ct=[],Ut=0,$r="",vi=0;if(qt.length){let es=Ft,tt=0;for(let Mr of qt){let dt=parseInt((Ql=Mr.getAttribute("d"))!=null?Ql:"",10),or=parseInt((Gl=Mr.getAttribute("r"))!=null?Gl:"",10)||0,ts=parseInt((Wl=Mr.getAttribute("t"))!=null?Wl:"",10);tt=Number.isFinite(ts)?ts:tt;let wn=dt/et*1e3,An=tt/et*1e3;for(let rs=0;rs<or+1;rs++){let ES=$t(Ge,{...yt,segmentNumber:es.toString(10),segmentTime:(tt+rs*dt).toString(10)}),Kl=(An!=null?An:0)+rs*wn,xS=Kl+wn;es++,ct.push({time:{from:Kl,to:xS},url:ES})}tt+=(or+1)*dt,Ut+=(or+1)*wn}vi=tt/et*1e3,$r=$t(Ge,{...yt,segmentNumber:es.toString(10),segmentTime:tt.toString(10)})}else if((0,wa.isNonNullable)(d)){let tt=parseInt((Yl=we.getAttribute("duration"))!=null?Yl:"",10)/et*1e3,Mr=Math.ceil(d/tt),dt=0;for(let or=1;or<Mr;or++){let ts=$t(Ge,{...yt,segmentNumber:or.toString(10),segmentTime:dt.toString(10)});ct.push({time:{from:dt,to:dt+tt},url:ts}),dt+=tt}vi=dt,$r=$t(Ge,{...yt,segmentNumber:Mr.toString(10),segmentTime:dt.toString(10)})}let IS={time:{from:vi,to:1/0},url:$r};Lr={type:"template",baseUrl:ir,segmentTemplateUrl:Ge,initUrl:nr,totalSegmentsDurationMs:Ut,segments:ct,nextSegmentBeyondManifest:IS,timescale:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!_t)continue;let gi={video:"video",audio:"audio",text:"text"}[Nt];if(!gi)continue;Ar||(Ar=gi),Wa={id:Ja,kind:gi,segmentReference:Lr,profiles:Za,duration:d,bitrate:za,mime:_t,codecs:Ga,width:ar,height:mi,fps:Pn,quality:kr}}de.language||(de.language=Bt),de.label||(de.label=fi),de.mime||(de.mime=_t),de.codecs||(de.codecs=Ga),de.hdr||(de.hdr=Ar==="video"&&Xu(Ga)),de.representations.push(Wa)}if(Ar){let se=i[Ar].find(Bt=>Bt.id===de.id);if(se&&de.representations.every(Bt=>Re(Bt.segmentReference)))for(let Bt of se.representations){let fi=de.representations.find(_t=>_t.id===Bt.id),Qa=fi==null?void 0:fi.segmentReference,ir=Bt.segmentReference;ir.segments.push(...Qa.segments),ir.nextSegmentBeyondManifest=Qa.nextSegmentBeyondManifest}else i[Ar].push(de)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var _v=G(st(),1),nl=require("@vkontakte/videoplayer-shared/es2018"),Le=(a,e)=>(0,nl.isNonNullable)(a)&&(0,nl.isNonNullable)(e)&&a.readyState==="open"&&(0,_v.default)([...a.activeSourceBuffers],e);var Aa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new T.ValueSubject(0);this.currentLowLatencySegmentLength$=new T.ValueSubject(0);this.currentSegmentLength$=new T.ValueSubject(0);this.onLastSegment$=new T.ValueSubject(!1);this.fullyBuffered$=new T.ValueSubject(!1);this.playingRepresentation$=new T.ValueSubject(void 0);this.playingRepresentationInit$=new T.ValueSubject(void 0);this.error$=new T.Subject;this.gaps=[];this.subscription=new T.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ee;this.switchAbortController=new Ee;this.destroyAbortController=new Ee;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=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,T.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Vg(this.sourceBuffer),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Le(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,ju(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=gt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,T.assertNonNullable)(r,"No init buffer for starting representation"),(0,T.assertNonNullable)(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.switchTo=(0,T.abortable)(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);(0,T.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,T.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Le(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,T.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=(0,T.abortable)(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);(0,T.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,T.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Le(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,T.isNonNullable)(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=(0,T.abortable)(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,on.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);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);(0,T.assertNonNullable)(i);let s=this.segments.get(r);(0,T.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,T.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ee,(0,T.abortable)(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,T.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,T.isNullable)(o)||(0,T.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,T.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Le(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,T.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,T.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ee,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,T.isNullable)(e)||(0,T.isNullable)(this.downloadingRepresentationId)||(0,T.isNullable)(this.playingRepresentationId)||(0,T.isNullable)(this.sourceBuffer)||!Le(this.mediaSource,this.sourceBuffer)||(0,T.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,T.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);(0,T.isNonNullable)(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=gt(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&ju(this.sourceBuffer.buffered)>=this.bufferLimit){let l=gt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,nn.default)(o,i))l="high";else{let c=(0,ui.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&gt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ui.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;(0,T.isNonNullable)(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,on.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,on.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Re(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ui.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,T.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Re(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=$t(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&ta&&ta(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ta&&ta(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let g=p<=r&&h>=r,v=p>r||g||m===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&p<=r+I||h<=r+I;return(d==="none"||d==="partially_ejected"&&v&&E&&this.sourceBuffer&&Le(this.mediaSource,this.sourceBuffer)&&!(Xt(this.sourceBuffer.buffered,p)&&Xt(this.sourceBuffer.buffered,h)))&&v&&E});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){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(0,T.abortable)(o,async function*(){let c=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,T.now)(),!c)return;let d=new DataView(c),p=xa(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,g)}u&&i.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Pa(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,T.abortable)(n,async function*(){let u=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,T.fromEvent)(window,"online").pipe((0,T.once)()).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=(0,T.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Pa(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,ui.default)(e,0).byte.from,to:(0,ui.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Re(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,nn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=xa(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,m=d<=i;if(!h)continue;let g=xa(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),I=u.loadedBytes===p?v:g.parseFeedableSegmentChunk(v);I!=null&&I.byteLength&&(l.status="partially_fed",u.feedingBytes+=I.byteLength,await this.sourceBufferTaskQueue.append(I,s)&&!s.aborted?(u.fedBytes+=I.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var r;if(!((0,T.isNullable)(this.sourceBuffer)||!Le(this.mediaSource,this.sourceBuffer))){!this.isLive&&T.clientChecker.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Xt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Xt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",rl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Uu(()=>(0,Nv.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?(0,T.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,xa(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&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.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!Le(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,T.isNullable)(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push({...u.time}),i=n(i);let l=rl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,nn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Le(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!Le(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!Le(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,T.isNullable)(e)?0:gt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Le(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)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)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Le(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Uu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:T.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,T.isNullable)(this.sourceBuffer)||!Le(this.mediaSource,this.sourceBuffer)||(0,T.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var ka=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Fv=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}};var Y=require("@vkontakte/videoplayer-shared/es2018");var qv=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var un=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Y.ValueSubject(void 0);this.lastConnectionReused$=new Y.ValueSubject(void 0);this.lastRequestFirstBytes$=new Y.ValueSubject(void 0);this.abortAllController=new Ee;this.subscription=new Y.Subscription;this.fetchManifest=(0,Y.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ka(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=qv(r));let i=yield ot(r,{signal:this.abortAllController.signal}).catch(Ra);return i?(t.log("success",(0,Y.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,Y.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,Y.abortable)(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 X,C;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(l,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),l=_.toString();break}default:(0,Y.assertNever)(t)}this.requestQuic&&(l=ka(l));let p=this.abortAllController.signal,h;if(n){let _=new Ee;if(h=(0,Y.merge)((0,Y.fromEvent)(this.abortAllController.signal,"abort"),(0,Y.fromEvent)(n,"abort")).subscribe(()=>{try{_.abort()}catch(ie){Ra(ie)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(ie){Ra(ie)}p=_.signal}let m=(0,Y.now)();d.log("startRequest",(0,Y.flattenObject)({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:m}));let g=yield ot(l,{priority:s,headers:c,signal:p}).catch(Ra),v=(0,Y.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((X=this.throughputEstimator)==null||X.addRawRtt(v-m),!g.ok||!g.body){h==null||h.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:_}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){h==null||h.unsubscribe();let _=(0,Y.now)(),ie={requestStartedAt:m,requestEndedAt:_,duration:_-m};return d.log("endRequest",(0,Y.flattenObject)(ie)),d.end(),g.arrayBuffer()}let[I,E]=g.body.tee(),x=I.getReader();o&&((C=this.throughputEstimator)==null||C.trackStream(E,u));let k=0,w=new Uint8Array(0),F=!1,j=_=>{h==null||h.unsubscribe(),F=!0,Ra(_)},ee=(0,Y.abortable)(p,async function*({done:_,value:ie}){if(k===0&&this.lastRequestFirstBytes$.next((0,Y.now)()-m),p.aborted){h==null||h.unsubscribe();return}if(!_&&ie){let he=new Uint8Array(w.length+ie.length);he.set(w),he.set(ie,w.length),w=he,k+=ie.byteLength,i==null||i(new DataView(w.buffer),k),yield x==null?void 0:x.read().then(ee,j)}}.bind(this));yield x==null?void 0:x.read().then(ee,j),h==null||h.unsubscribe();let W=(0,Y.now)(),K={failed:F,requestStartedAt:m,requestEndedAt:W,duration:W-m};return F?(d.error("endRequest",(0,Y.flattenObject)(K)),d.end(),null):(d.log("endRequest",(0,Y.flattenObject)(K)),d.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,Y.abortable)(this.abortAllController.signal,async function*(e,t,r){var I;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(I=e.indexRange)!=null?I:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let E=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,Y.abortable)(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}=Fv(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:(0,Y.assertNever)(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ra=a=>{if(!Pa(a))throw a};var yr=(a,e,t)=>t*e+(1-t)*a,ol=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Uv=(a,e,t,r)=>{let i=0,s=t,n=ol(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};var La=require("@vkontakte/videoplayer-shared/es2018"),Zt=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 La.ValueSubject(e.initial),this.debounced$=new La.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${t}`),this.smoothedSeries$=new ke(`smoothed_${t}`),this.reportedSeries$=new ke(`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)&&((0,La.isNullable)(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 ln=class extends Zt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=yr(this.slow,e,this.params.emaAlphaSlow),this.fast=yr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var cn=class extends Zt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ol(this.pastMeasures,this.takenMeasures);this.emaSmoothed=yr(this.emaSmoothed,e,this.params.emaAlpha);let r=Uv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var dn=class extends Zt{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?yr(this.smoothed,t,this.params.emaAlpha):t}};var Tr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ln({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new cn({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 dn({initial:e,label:"liveEdgeDelay",...t})}};var ul=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var pn=require("@vkontakte/videoplayer-shared/es2018");var $a=class a{constructor(e,t){this.currentRepresentation$=new pn.ValueSubject(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(!(0,pn.isNullable)(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Re(t.segmentReference))}};var QR=["timeupdate","progress","play","seeked","stalled","waiting"],GR=["timeupdate","progress","loadeddata","playing","seeked"];var hn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new q("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.isLowLatency$=new S.ValueSubject(!1);this.isActiveLowLatency$=new S.ValueSubject(!1);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new Ee;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ie(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:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(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:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Bv(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=$g(e))!=null?n:{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=kt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=lg(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(v=>v.hdr),g=i.video.some(v=>!v.hdr);S.clientChecker.isHDR&&h&&m?i.video=i.video.filter(v=>v.hdr):g&&(i.video=i.video.filter(v=>!v.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Gb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ks())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Aa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Aa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}$a.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new $a(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((0,S.interval)(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Ns(this.manifestUrlString,2);this.manifestUrlString=Ie(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...GR.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?gt(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ul(this.element,1)})),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add((0,S.combine)({isActiveLowLatency:this.isActiveLowLatency$.pipe((0,S.filterChanged)()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe((0,S.filter)(({isActiveLowLatency:h,currentLowLatencySegmentLength:m})=>h&&!!m)).subscribe(({currentLowLatencySegmentLength:h})=>{let m=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:h})=>h),(0,S.map)(h=>({...h})),(0,S.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,S.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let v=Ns(this.manifestUrlString,2);return(h/2+m+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:m})=>{if(!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=h-g;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(E)>v&&(x=1+Math.sign(E)*I),ul(this.element,x)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,v;let m=0;if(h){let I=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;m=Math.min(...this.bufferManagers.map(x=>{var k,w;return(w=(k=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:k.to)!=null?w:I}))-I}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Ns(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,k=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,w=isFinite(h)?h:m,F=this.isActiveLowLatency$.getValue(),j=I<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(F&&j);let ee="none";if(F?ee="active_low_latency":this.isLowLatency$.getValue()&&j?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(W=>W.proceedLowLatencyLive()),ee="active_low_latency"):v!==0&&w<E?ee="live_forward_buffering":w<E+k&&(ee="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),ee==="live_forward_buffering"||ee==="live_with_target_offset"){let W=p-(E+x),K=this.normolizeLiveOffset(Math.trunc(v+W/g)),X=Math.abs(K-v),C;!h||X<=this.tuning.dashCmafLive.offsetCalculationError?C=v:K>0&&X>this.tuning.dashCmafLive.offsetCalculationError?C=K:C=0,this.manifestUrlString=Ie(this.manifestUrlString,C,2)}ee!=="none"&&ee!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,ll.default)((0,ll.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Re(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,S.isNonNullable)(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=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.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 un({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Tr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;(0,S.assertNonNullable)(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=Ie(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(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...QR.map(e=>(0,S.fromEvent)(this.element,e)),(0,S.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,S.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Xt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,g,v,I,E,x,k,w,F;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=(0,S.now)(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(E=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,c=(k=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?k:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let j=this.element.currentTime*1e3;(w=this.videoBufferManager)==null||w.maintain(j),(F=this.audioBufferManager)==null||F.maintain(j),i.position=j}this.tracer.log("stallIntervalCallback",(0,S.flattenObject)(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.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 this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)}async seek(e,t){var i,s,n,o,u;(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(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),Xt(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,S.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){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",(0,S.flattenObject)(t)))}}};var fn=class{constructor(e,t){this.fov=e,this.orientation=t}};var mn=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 jv=`attribute vec2 a_vertex;
71
71
  attribute vec2 a_texel;
72
72
 
73
73
  varying vec2 v_texel;
@@ -78,7 +78,7 @@ void main(void) {
78
78
  // save texel vector to pass to fragment shader
79
79
  v_texel = a_texel;
80
80
  }
81
- `;var Uv=`#ifdef GL_ES
81
+ `;var Qv=`#ifdef GL_ES
82
82
  precision highp float;
83
83
  precision highp int;
84
84
  #else
@@ -121,6 +121,6 @@ void main(void) {
121
121
  // sample using new coordinates
122
122
  gl_FragColor = texture2D(u_texture, tc);
123
123
  }
124
- `;var mn=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 pn(this.params.fov,this.params.orientation),this.cameraRotationManager=new hn(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(qv,this.gl.VERTEX_SHADER),r=this.createShader(Uv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var me=require("@vkontakte/videoplayer-shared/es2018"),ul=class{constructor(){this.isSeeked$=new me.ValueSubject(!1);this.isBuffering$=new me.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new me.Subscription;this.severeStallOccurred$=new me.ValueSubject(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,me.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,me.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,me.combine)({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if((0,me.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=(0,me.now)(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,me.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,me.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Hv=ul;var Be=require("@vkontakte/videoplayer-shared/es2018"),fn=class{constructor(){this.subscription=new Be.Subscription;this.pipSize$=new Be.ValueSubject(void 0);this.videoSize$=new Be.ValueSubject(void 0);this.elementSize$=new Be.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Be.noop}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Be.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,Be.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Be.map)(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Er=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new U("stopped");this.droppedFramesManager=new js;this.stallsManager=new Hv;this.elementSizeManager=new fn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Hi;this.audioTrackSwitchHistory=new Hi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&A(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"&&A(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"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,B.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new mn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Re(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(ge(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 dn({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=Me(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:B.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,B.filter)(c=>!!c.length),(0,B.once)()).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((0,B.map)(c=>c.to.state!=="none"),(0,B.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,B.filterChanged)()),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((0,B.filter)(B.isNonNullable),(0,B.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,B.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ft(this.video,t.isLooped,i)),this.subscription.add(Le(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(ze(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,B.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Ju(f));let g=[];for(let v of f.representations){let T=Av(v);g.push(T),this.audioTracksMap.set(T,{stream:f,representation:v})}this.audioStreamsMap.set(f,g)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Zu(h));let f=[];for(let g of h.representations){let v=wv({...g,streamId:h.id});v&&(f.push(v),this.videoTracksMap.set(v,{stream:h,representation:g}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let f of h.representations){let g=kv(h,f);this.textTracksMap.set(g,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:B.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,B.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,jv.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,g=[...this.videoTracksMap.keys()].find(T=>{var E;return((E=this.videoTracksMap.get(T))==null?void 0:E.representation.id)===h.id});(0,B.isNonNullable)(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(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let T=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,T).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,B.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Zu(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,B.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Ju(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,B.map)(({to:c})=>c==="ready"),(0,B.filterChanged)());this.subscription.add((0,B.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,B.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,B.merge)(u,this.player.state$.stateChangeEnded$,(0,B.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,B.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var j,Q,ee,Y,X,J,C,_,ie,pe,R,P,q;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(j=e.videoTrack.getState())==null?void 0:j.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===i),o=t.currentVideoTrack$.getValue(),u=((Y=(ee=e.videoStream.getState())!=null?ee:n&&((Q=this.videoTracksMap.get(n))==null?void 0:Q.stream))!=null?Y:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=gt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(X=e.audioStream.getState())!=null?X:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(J=[...this.audioStreamsMap.keys()].find(({id:N})=>N===(f==null?void 0:f.id)))!=null?J:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let N=Us(n,c,(C=this.audioStreamsMap.get(g))!=null?C:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(_=N==null?void 0:N.bitrate)!=null?_:-1/0)}if(o){let N=Us(o,c,(ie=this.audioStreamsMap.get(g))!=null?ie:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(pe=N==null?void 0:N.bitrate)!=null?pe:-1/0)}}let T=Xt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,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}),E=r?T!=null?T:n:n!=null?n:T,x=g&&pb(E,c,(R=this.audioStreamsMap.get(g))!=null?R:[],{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}),k=(P=this.videoTracksMap.get(E))==null?void 0:P.representation,w=x&&((q=this.audioTracksMap.get(x))==null?void 0:q.representation);if(k&&w)return[k,w];if(k&&!w&&this.audioTracksMap.size===0)return[k,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:B.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),$e(this.video),this.tracer.end()}};var La=class extends Er{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)}};var tr=require("@vkontakte/videoplayer-shared/es2018");var Ma=class extends Er{constructor(e){super(e),this.liveOffset=new Pt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((0,tr.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,tr.combine)({interval:(0,tr.interval)(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((0,tr.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,tr.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Rv(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 Gv=W(Bs(),1);var G=require("@vkontakte/videoplayer-shared/es2018"),lt={};var ui=(a,e)=>new G.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Da=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new U("initializing");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:(0,G.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,G.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,G.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,G.assertNever)(e)}break;default:(0,G.assertNever)(t)}};this.textTracksManager=new Ye(e.source.url),this.video=Re(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(ge(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),$e(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:G.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Gv.default)(import("hls.js").then(i=>{e||(lt.Hls=i.default,lt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,G.assertNonNullable)(lt.Hls,"hls.js not loaded"),this.hls=new lt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,G.assertNonNullable)(lt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:G.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Me(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ft(this.video,e.isLooped,r)),this.subscription.add(Le(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(We(this.video,e.playbackRate,i.playbackRateState$,r)),s(ze(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,G.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ui(this.hls,lt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:G.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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(ui(this.hls,lt.Events.MANIFEST_PARSED).pipe((0,G.map)(({levels:l})=>l.reduce((c,d)=>{var E,x;let p=d.name||d.height.toString(10),{width:h,height:f}=d,g=(x=zt((E=d.attrs.QUALITY)!=null?E:""))!=null?x:(0,G.videoSizeToQuality)({width:h,height:f});if(!g)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:v};return this.trackLevels.set(p,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(ui(this.hls,lt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ui(this.hls,lt.Events.LEVEL_LOADING).pipe((0,G.map)(({url:l})=>ge(l))),t.hostname$),s(ui(this.hls,lt.Events.FRAG_CHANGED),l=>{var p,h,f,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Yt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ui(this.hls,lt.Events.LEVEL_SWITCHED).pipe((0,G.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,G.filter)(G.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Yt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if((0,G.isNullable)(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,G.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(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 De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),A(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"),A(this.params.desiredState.playbackState,"stopped",!0)}};var Qv="X-Playback-Duration",ll=async a=>{var i;let e=await ot(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(Qv)?parseInt(e.headers.get(Qv),10):void 0};var H=require("@vkontakte/videoplayer-shared/es2018");var dl=W(Lo(),1);var bn=require("@vkontakte/videoplayer-shared/es2018");var WR=a=>{let e=null;if(a.QUALITY&&(e=zt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,bn.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},YR=(a,e)=>{var s,n;let t=a.split(`
125
- `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,dl.default)(l[1].split(",").map(E=>E.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=WR(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[E,x]=d.RESOLUTION.split("x").map(k=>parseInt(k,10));E&&x&&(v={width:E,height:x})}let T=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:T,bandwidth:f,size:v,fps:g})}if(c){let d=(0,dl.default)(c[1].split(",").map(g=>{let v=g.indexOf("=");return[g.substring(0,v),g.substring(v+1)]}).map(([g,v])=>[g,v.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},zR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),cl=0,Wv=async(a,e=a,t,r)=>{let s=await(await ot(a,r)).text();cl+=1;try{let{qualityManifests:n,textTracks:o}=YR(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(cl<=t.manifestRetryMaxCount)return await zR((0,bn.getExponentialDelay)(cl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Wv(a,e,t)}return{qualityManifests:[],textTracks:[]}},gn=Wv;var He=require("@vkontakte/videoplayer-shared/es2018");var vn=class{constructor(e,t,r,i,s){this.subscription=new He.Subscription;this.abortControllers={destroy:new xe,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new He.ValueSubject(null);this.getCurrentTime$=new He.ValueSubject(null);this.error$=new He.Subject;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe((0,He.throttle)(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=await this.fetchManifestData();await this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let r=await this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}}async parseTextTracks(e,t){for(let r of e){let i=new URL(r.url,t).toString(),n=await(await ot(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
126
- `),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.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);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,He.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new xe;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:He.ErrorCategory.WTF,thrown:t,message:e})}};var Ca=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new U("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new H.ValueSubject([]);this.liveOffset=new Pt;this.manifestStartTime$=new H.ValueSubject(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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,H.assertNever)(t)}};var r;this.params=e,this.video=Re(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:H.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,s)=>gn(i,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 vn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:H.ErrorCategory.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,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:H.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new H.ValueSubject((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:H.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Me(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(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),s(ze(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(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,H.filterChanged)(),(0,H.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,H.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ge(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,H.combine)({startTime:this.manifestStartTime$.pipe((0,H.filter)(H.isNonNullable)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,H.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,H.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}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),$e(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,H.isNullable)(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:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ee(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),ll(n).then(c=>{var d;if(!(0,H.isNullable)(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,H.isNullable)(p)||!isFinite(p))&&ot(n).then(h=>h.text()).then(h=>{var g;let f=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:g[1];if(f){let v=new URL(f,n).toString();ll(v).then(T=>{(0,H.isNullable)(T)||this.maxSeekBackTime$.next(T)})}}).catch(()=>{})}})}playIfAllowed(){De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.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()}generateLiveUrl(){let e=Ee(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}};var K=require("@vkontakte/videoplayer-shared/es2018");var Oa=class{constructor(e){this.subscription=new K.Subscription;this.videoState=new U("stopped");this.manifests$=new K.ValueSubject([]);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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,K.assertNever)(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=Re(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:K.VideoQuality.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(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),gn(Ee(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:K.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:K.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Me(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((0,K.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ft(this.video,t.isLooped,r)),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,K.isNonNullable)(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(v=>v.id===f);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(ge(g.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,K.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!K.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,K.merge)((0,K.fromEvent)(o,"addtrack"),(0,K.fromEvent)(o,"removetrack"),(0,K.fromEvent)(o,"change"),(0,K.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,K.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,K.observableFrom)(["init"])).pipe((0,K.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),$e(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,K.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:K.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Yv=W(Ur(),1),Va=W(Jr(),1);var re=require("@vkontakte/videoplayer-shared/es2018");var Ba=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new U("stopped");this.trackUrls={};this.textTracksManager=new Ye;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}};this.params=e,this.video=Re(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Yv.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Va.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:re.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Me(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((0,re.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ft(this.video,t.isLooped,r)),this.subscription.add(Le(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),s(ze(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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&&(0,re.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,re.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(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),$e(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,re.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,re.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=wa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ge(t))}playIfAllowed(){De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Va.default)(this.trackUrls).find(d=>!(0,re.isInvariantQuality)(d.track.quality)&&(0,re.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,re.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=(0,Va.default)(this.trackUrls).filter(h=>!(0,re.isInvariantQuality)(h.track.quality)&&(0,re.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Va.default)(this.trackUrls).map(l=>l.track);t=Xt(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})}};var ne=require("@vkontakte/videoplayer-shared/es2018");var Kv=require("@vkontakte/videoplayer-shared/es2018"),zv=["stun:videostun.mycdn.me:80"],KR=1e3,XR=3,pl=()=>null,Sn=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=pl;this.externalStopCallback=pl;this.externalErrorCallback=pl;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:zv}]};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:Kv.ErrorCategory.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),KR)}normalizeOptions(e={}){let t={stunServerList:zv,maxRetryNumber:XR,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 U("stopped");this.maxSeekBackTime$=new ne.ValueSubject(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,ne.assertNever)(e)}};this.subscription=new ne.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Re(e.container,e.tuning),this.liveStreamClient=new Sn(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),$e(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:ne.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,ne.merge)(this.videoState.stateChangeStarted$.pipe((0,ne.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,ne.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Me(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(ze(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(Le(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(0,ne.assertNever)(n.to)}},r)).add((0,ne.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ne.observableFrom)(["init"])).pipe((0,ne.debounce)(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(ge(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:ne.VideoQuality.INVARIANT}),this.video.srcObject=e,A(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:ne.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){De(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ne.ErrorCategory.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}};var y=require("@vkontakte/videoplayer-shared/es2018");var Mt=require("@vkontakte/videoplayer-shared/es2018"),Xv=a=>new Mt.Observable(e=>{let t=new Mt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Mt.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Mt.map)(({type:l})=>l!==void 0)),n=new Mt.Subject,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()}});var Je=require("@vkontakte/videoplayer-shared/es2018");function Jv(){return new(window.AudioContext||window.webkitAudioContext)}var Zv=require("@vkontakte/videoplayer-shared/es2018");var Fa=class Fa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new xe;this.subscriptions=new Je.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Je.filter)(s=>!!s.type),(0,Je.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){Zv.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Je.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Je.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,Je.once)()).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=Jv();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:Je.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Fa.errorId} exception`,thrown:e})}};Fa.errorId="VolumeMultiplierManager";var li=Fa;var JR={chunkDuration:5e3,maxParallelRequests:5},qa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),liveLatency$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject(""),getCurrentTime$:new y.ValueSubject(null)};this.subscription=new y.Subscription;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=ig([...sg(this.params.tuning),...ag(this.params.tuning)],this.params.tuning).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,hl.default)(i,l)),...t.filter(l=>(0,hl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new Na(s);let n=[...Ou(!0),...Ou(!1)];this.chromecastFormatsIterator=new Na(n.filter(l=>(0,y.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&li.isSupported()&&(this.volumeMultiplierManager=new li(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,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.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(0,y.assertNever)(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(0,y.assertNonNullable)(o),new La({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ma({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ii||!this.params.tuning.useHlsJs?new Oa({...n,source:o}):new Da({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ca({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ba({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Tb({...n,source:o,config:{...JR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(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(0,y.assertNever)(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(0,y.assertNonNullable)(o),new qi({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(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(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(0,y.assertNever)(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,tS.default)((0,eS.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$.pipe((0,y.filter)(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),Xv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(i=>({id:`ProviderHangup:${i}`,category:y.ErrorCategory.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((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).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===y.ErrorCategory.NETWORK,u=i.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var V=require("@vkontakte/videoplayer-shared/es2018");var ZR=5e3,rS="one_video_throughput",iS="one_video_rtt",Dt=window.navigator.connection,aS=()=>{let a=Dt==null?void 0:Dt.downlink;if((0,V.isNonNullable)(a)&&a!==10)return a*1e3},sS=()=>{let a=Dt==null?void 0:Dt.rtt;if((0,V.isNonNullable)(a)&&a!==3e3)return a},nS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},ml=class a{constructor(e){this.subscription=new V.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(rS)||(e.useBrowserEstimation?aS():void 0)||ZR,r=(s=(i=a.load(iS))!=null?i:e.useBrowserEstimation?sS():void 0)!=null?s:0;if(this.throughput$=new V.ValueSubject(t),this.rtt$=new V.ValueSubject(r),this.rttAdjustedThroughput$=new V.ValueSubject(nS(t,r,e.rttPenaltyRequestSize)),this.throughput=Ir.getSmoothedValue(t,-1,e),this.rtt=Ir.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=aS();u&&this.throughput.next(u);let l=sS();(0,V.isNonNullable)(l)&&this.rtt.next(l)};Dt&&"onchange"in Dt&&this.subscription.add((0,V.fromEvent)(Dt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{V.safeStorage.set(rS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{V.safeStorage.set(iS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,V.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,V.map)(({throughput:n,rtt:o})=>nS(n,o,e.rttPenaltyRequestSize)),(0,V.filter)(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=(0,V.now)(),i=new V.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,V.fromEvent)(e,"progress").pipe((0,V.once)()).subscribe(s=>{t=s.loaded,r=(0,V.now)()}));break;case 1:case 0:i.add((0,V.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,V.now)()}));break}i.add((0,V.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,V.now)(),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=(0,V.now)(),n=0,o=(0,V.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,(0,V.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,V.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=(0,V.now)()}else n+=d.byteLength;o=(0,V.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,V.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,V.now)()-o,this.concurrentDownloads.size),n=0,o=(0,V.now)());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=V.safeStorage.get(e);if((0,V.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},oS=ml;var Ua=require("@vkontakte/videoplayer-shared/es2018"),uS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ua.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ua.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},lS=a=>{var e;return{...(0,Ua.fillWithDefault)(a,uS),configName:[...(e=a.configName)!=null?e:[],...uS.configName]}};var m=require("@vkontakte/videoplayer-shared/es2018");var Ct=require("@vkontakte/videoplayer-shared/es2018"),fl=({seekState:a,position$:e})=>(0,Ct.merge)(a.stateChangeEnded$.pipe((0,Ct.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Ct.filter)(Ct.isNonNullable)),e.pipe((0,Ct.filter)(()=>a.getState().state==="none")));var cS=require("@vkontakte/videoplayer-shared/es2018"),dS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,cS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var yn=require("@vkontakte/videoplayer-shared/es2018"),pS=(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((0,yn.filter)(i=>i.length>0),(0,yn.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ha=class{constructor(e={configName:[]},t=m.Tracer.createRootTracer(!1)){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new U("stopped"),seekState:new U({state:"none"}),volume:new U({volume:1,muted:!1}),videoTrack:new U(void 0),videoStream:new U(void 0),audioStream:new U(void 0),autoVideoTrackSwitching:new U(!0),autoVideoTrackLimits:new U({}),isLooped:new U(!1),isLowLatency:new U(!1),playbackRate:new U(1),externalTextTracks:new U([]),internalTextTracks:new U([]),currentTextTrack:new U(void 0),textTrackCuesSettings:new U({}),cameraOrientation:new U({x:0,y:0})};this.info={playbackState$:new m.ValueSubject("stopped"),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),liveLatency$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,autoplaySoundProhibited$:new m.Subject,firstBytes$:new m.Subject,loadedMetadata$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:nb,getCurrentTime$:new m.ValueSubject(null)};if(this.initLogs(),this.tuning=lS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ls({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new oS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new m.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let g=typeof f;return(0,hS.default)(["number","string","boolean"],g)?f:f===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:m.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",(0,m.flattenObject)(r)),this.domContainer=dS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new qa({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(o=this.internalsExposure)==null||o.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Wi()?(this.tracer.log("request play from hidden tab"),(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.once)()).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){(0,m.assertNonNullable)(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((0,m.filter)(r=>r.length>0),(0,m.once)()).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",(0,m.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;(0,m.assertNonNullable)(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",(0,m.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return pS(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((0,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,m.isNonNullable)(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((0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.now)(),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",(0,m.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:m.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,m.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,m.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,m.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(n=>n.destination),(0,m.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,m.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,m.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,m.isInvariantQuality)(u)?1:(0,m.isInvariantQuality)(l)?-1:(0,m.isHigher)(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((0,m.filterChanged)()).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((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.filterChanged)()).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((0,m.map)(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((0,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(n=>n.to),(0,m.filterChanged)(),(0,m.map)(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((0,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:fl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(fl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.filterChanged)()).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((0,m.map)(n=>({id:n?`No${n}`:"NoProviders",category:m.ErrorCategory.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((0,m.once)(),(0,m.map)(n=>n!=null?n:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-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 m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:n})=>n==="playing"),(0,m.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,m.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,m.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,m.filterChanged)());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((0,m.merge)(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((0,m.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.map)(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 m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(r=>r.length>0),(0,m.once)()).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=Xt(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((0,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.map)(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;(0,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),sb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>ab(r)),this.providerContainer.current$.subscribe(({type:r})=>Ui("provider",r)),e.duration$.subscribe(r=>Ui("duration",r)),e.availableVideoTracks$.pipe((0,m.filter)(r=>!!r.length),(0,m.once)()).subscribe(r=>Ui("tracks",r)),this.events.fatalError$.subscribe(new Ae("fatalError")),this.events.managedError$.subscribe(new Ae("managedError")),e.position$.subscribe(new Ae("position")),e.currentVideoTrack$.pipe((0,m.map)(r=>r==null?void 0:r.quality)).subscribe(new Ae("quality")),this.info.currentBuffer$.subscribe(new Ae("buffer")),e.isBuffering$.subscribe(new Ae("isBuffering"))].forEach(r=>this.subscription.add(r)),Ui("codecs",rg())}initTracerSubscription(){let e=(0,m.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,m.getTraceSubscriptionMethod)(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((0,m.filterChanged)()).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((0,m.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,m.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,m.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,m.filter)(r=>r>0),(0,m.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,m.filter)(r=>r>0),(0,m.filterChanged)()).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((0,m.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,m.filter)(r=>r.end>0),(0,m.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,m.filterChanged)())}).pipe((0,m.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,m.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,m.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,m.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,m.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,m.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,m.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,m.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,m.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,m.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,m.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,m.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,m.filterChanged)(),(0,m.filter)(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:m.ErrorCategory.DOM,message:String(i)})})};this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(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",(0,m.flattenObject)({quality:t,availableTracks:(0,m.flattenObject)(e),track:(0,m.flattenObject)(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}};var St=require("@vkontakte/videoplayer-shared/es2018"),e$=`@vkontakte/videoplayer-core@${wn}`;
124
+ `;var bn=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 fn(this.params.fov,this.params.orientation),this.cameraRotationManager=new mn(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(jv,this.gl.VERTEX_SHADER),r=this.createShader(Qv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var me=require("@vkontakte/videoplayer-shared/es2018"),cl=class{constructor(){this.isSeeked$=new me.ValueSubject(!1);this.isBuffering$=new me.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new me.Subscription;this.severeStallOccurred$=new me.ValueSubject(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,me.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,me.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,me.combine)({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if((0,me.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=(0,me.now)(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,me.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,me.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Gv=cl;var _e=require("@vkontakte/videoplayer-shared/es2018"),gn=class{constructor(){this.subscription=new _e.Subscription;this.pipSize$=new _e.ValueSubject(void 0);this.videoSize$=new _e.ValueSubject(void 0);this.elementSize$=new _e.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=_e.noop}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,_e.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,_e.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,_e.map)(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ir=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new q("stopped");this.droppedFramesManager=new Gs;this.stallsManager=new Gv;this.elementSizeManager=new gn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qi;this.audioTrackSwitchHistory=new Qi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(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"),A(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&A(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"&&A(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"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,B.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new bn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=$e(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(ge(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 hn({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=Ce(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:B.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,B.filter)(c=>!!c.length),(0,B.once)()).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((0,B.map)(c=>c.to.state!=="none"),(0,B.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,B.filterChanged)()),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((0,B.filter)(B.isNonNullable),(0,B.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,B.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(De(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(ze(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,B.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of d.audio){h.push(el(m));let g=[];for(let v of m.representations){let I=Lv(v);g.push(I),this.audioTracksMap.set(I,{stream:m,representation:v})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(tl(h));let m=[];for(let g of h.representations){let v=Rv({...g,streamId:h.id});v&&(m.push(v),this.videoTracksMap.set(v,{stream:h,representation:g}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let m of h.representations){let g=$v(h,m);this.textTracksMap.set(g,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:B.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,B.merge)(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Wv.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,g=[...this.videoTracksMap.keys()].find(I=>{var E;return((E=this.videoTracksMap.get(I))==null?void 0:E.representation.id)===h.id});(0,B.isNonNullable)(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(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let I=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,I).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,B.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(tl(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,B.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(el(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,B.map)(({to:c})=>c==="ready"),(0,B.filterChanged)());this.subscription.add((0,B.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,B.observableFrom)(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,B.merge)(u,this.player.state$.stateChangeEnded$,(0,B.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,B.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var j,ee,W,K,X,C,_,ie,he,R,P,Q,ae;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(j=e.videoTrack.getState())==null?void 0:j.id,n=[...this.videoTracksMap.keys()].find(({id:J})=>J===i),o=t.currentVideoTrack$.getValue(),u=((K=(W=e.videoStream.getState())!=null?W:n&&((ee=this.videoTracksMap.get(n))==null?void 0:ee.stream))!=null?K:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:J})=>J===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=gt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(p,h||1/0),1),g=(X=e.audioStream.getState())!=null?X:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(C=[...this.audioStreamsMap.keys()].find(({id:J})=>J===(g==null?void 0:g.id)))!=null?C:this.audioStreamsMap.keys().next().value,I=0;if(v){if(n&&!r){let J=js(n,c,(_=this.audioStreamsMap.get(v))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(ie=J==null?void 0:J.bitrate)!=null?ie:-1/0)}if(o){let J=js(o,c,(he=this.audioStreamsMap.get(v))!=null?he:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(R=J==null?void 0:J.bitrate)!=null?R:-1/0)}}let E=Kt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),x=r?E!=null?E:n:n!=null?n:E,k=v&&fb(x,c,(P=this.audioStreamsMap.get(v))!=null?P:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),w=(Q=this.videoTracksMap.get(x))==null?void 0:Q.representation,F=k&&((ae=this.audioTracksMap.get(k))==null?void 0:ae.representation);if(w&&F)return[w,F];if(w&&!F&&this.audioTracksMap.size===0)return[w,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:B.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Me(this.video),this.tracer.end()}};var Da=class extends Ir{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)}};var er=require("@vkontakte/videoplayer-shared/es2018");var Ca=class extends Ir{constructor(e){super(e),this.liveOffset=new Pt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((0,er.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,er.combine)({interval:(0,er.interval)(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((0,er.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,er.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Mv(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 Yv=G(_s(),1);var H=require("@vkontakte/videoplayer-shared/es2018"),lt={};var li=(a,e)=>new H.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Va=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new q("initializing");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:(0,H.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,H.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,H.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,H.assertNever)(e)}break;default:(0,H.assertNever)(t)}};this.textTracksManager=new Ye(e.source.url),this.video=$e(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(ge(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),Me(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:H.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Yv.default)(import("hls.js").then(i=>{e||(lt.Hls=i.default,lt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,H.assertNonNullable)(lt.Hls,"hls.js not loaded"),this.hls=new lt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,H.assertNonNullable)(lt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:H.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ce(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(mt(this.video,e.isLooped,r)),this.subscription.add(De(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(We(this.video,e.playbackRate,i.playbackRateState$,r)),s(ze(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,H.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(li(this.hls,lt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:H.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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(li(this.hls,lt.Events.MANIFEST_PARSED).pipe((0,H.map)(({levels:l})=>l.reduce((c,d)=>{var E,x;let p=d.name||d.height.toString(10),{width:h,height:m}=d,g=(x=Yt((E=d.attrs.QUALITY)!=null?E:""))!=null?x:(0,H.videoSizeToQuality)({width:h,height:m});if(!g)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:v};return this.trackLevels.set(p,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(li(this.hls,lt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(li(this.hls,lt.Events.LEVEL_LOADING).pipe((0,H.map)(({url:l})=>ge(l))),t.hostname$),s(li(this.hls,lt.Events.FRAG_CHANGED),l=>{var p,h,m,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Wt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=li(this.hls,lt.Events.LEVEL_SWITCHED).pipe((0,H.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,H.filter)(H.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Wt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,H.isNullable)(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,H.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(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 Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState("paused"),A(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"),A(this.params.desiredState.playbackState,"stopped",!0)}};var zv="X-Playback-Duration",dl=async a=>{var i;let e=await ot(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(zv)?parseInt(e.headers.get(zv),10):void 0};var U=require("@vkontakte/videoplayer-shared/es2018");var hl=G(Do(),1);var vn=require("@vkontakte/videoplayer-shared/es2018");var XR=a=>{let e=null;if(a.QUALITY&&(e=Yt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,vn.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},JR=(a,e)=>{var s,n;let t=a.split(`
125
+ `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,hl.default)(l[1].split(",").map(E=>E.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=XR(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[E,x]=d.RESOLUTION.split("x").map(k=>parseInt(k,10));E&&x&&(v={width:E,height:x})}let I=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:I,bandwidth:m,size:v,fps:g})}if(c){let d=(0,hl.default)(c[1].split(",").map(g=>{let v=g.indexOf("=");return[g.substring(0,v),g.substring(v+1)]}).map(([g,v])=>[g,v.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},ZR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),pl=0,Kv=async(a,e=a,t,r)=>{let s=await(await ot(a,r)).text();pl+=1;try{let{qualityManifests:n,textTracks:o}=JR(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(pl<=t.manifestRetryMaxCount)return await ZR((0,vn.getExponentialDelay)(pl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Kv(a,e,t)}return{qualityManifests:[],textTracks:[]}},Sn=Kv;var Qe=require("@vkontakte/videoplayer-shared/es2018");var yn=class{constructor(e,t,r,i,s){this.subscription=new Qe.Subscription;this.abortControllers={destroy:new Ee,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Qe.ValueSubject(null);this.getCurrentTime$=new Qe.ValueSubject(null);this.error$=new Qe.Subject;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe((0,Qe.throttle)(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=await this.fetchManifestData();await this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let r=await this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}}async parseTextTracks(e,t){for(let r of e){let i=new URL(r.url,t).toString(),n=await(await ot(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
126
+ `),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.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);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,Qe.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Ee;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:Qe.ErrorCategory.WTF,thrown:t,message:e})}};var Oa=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new q("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new U.ValueSubject([]);this.liveOffset=new Pt;this.manifestStartTime$=new U.ValueSubject(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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(A(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,U.assertNever)(t)}};var r;this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:U.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,s)=>Sn(i,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 yn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ye(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:U.ErrorCategory.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,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:U.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ge(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new U.ValueSubject((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:U.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ce(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(De(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),s(ze(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(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,U.filterChanged)(),(0,U.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,U.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ge(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,U.combine)({startTime:this.manifestStartTime$.pipe((0,U.filter)(U.isNonNullable)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe((0,U.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,U.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}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),Me(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,U.isNullable)(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:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ie(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),dl(n).then(c=>{var d;if(!(0,U.isNullable)(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,U.isNullable)(p)||!isFinite(p))&&ot(n).then(h=>h.text()).then(h=>{var g;let m=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:g[1];if(m){let v=new URL(m,n).toString();dl(v).then(I=>{(0,U.isNullable)(I)||this.maxSeekBackTime$.next(I)})}}).catch(()=>{})}})}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.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()}generateLiveUrl(){let e=Ie(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}};var z=require("@vkontakte/videoplayer-shared/es2018");var Ba=class{constructor(e){this.subscription=new z.Subscription;this.videoState=new q("stopped");this.manifests$=new z.ValueSubject([]);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"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?A(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,z.assertNever)(t)}};this.textTracksManager=new Ye(e.source.url),this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:z.VideoQuality.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(ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Sn(Ie(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:z.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:z.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ce(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((0,z.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(De(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,z.isNonNullable)(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(v=>v.id===m);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(ge(g.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,z.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!z.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,z.merge)((0,z.fromEvent)(o,"addtrack"),(0,z.fromEvent)(o,"removetrack"),(0,z.fromEvent)(o,"change"),(0,z.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,z.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,z.observableFrom)(["init"])).pipe((0,z.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Me(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,z.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:z.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Xv=G(Hr(),1),_a=G(Zr(),1);var re=require("@vkontakte/videoplayer-shared/es2018");var Na=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new q("stopped");this.trackUrls={};this.textTracksManager=new Ye;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),A(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?A(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,re.assertNever)(e)}};this.params=e,this.video=$e(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Xv.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,_a.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:re.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ce(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((0,re.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(De(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),s(ze(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),A(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),A(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&&(0,re.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,re.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(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),Me(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,re.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,re.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ka(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ge(t))}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.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,_a.default)(this.trackUrls).find(d=>!(0,re.isInvariantQuality)(d.track.quality)&&(0,re.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,re.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=(0,_a.default)(this.trackUrls).filter(h=>!(0,re.isInvariantQuality)(h.track.quality)&&(0,re.isHigher)(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,_a.default)(this.trackUrls).map(l=>l.track);t=Kt(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})}};var oe=require("@vkontakte/videoplayer-shared/es2018");var Zv=require("@vkontakte/videoplayer-shared/es2018"),Jv=["stun:videostun.mycdn.me:80"],eL=1e3,tL=3,fl=()=>null,Tn=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=fl;this.externalStopCallback=fl;this.externalErrorCallback=fl;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:Jv}]};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:Zv.ErrorCategory.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),eL)}normalizeOptions(e={}){let t={stunServerList:Jv,maxRetryNumber:tL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Fa=class{constructor(e){this.videoState=new q("stopped");this.maxSeekBackTime$=new oe.ValueSubject(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"),A(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"),A(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"&&A(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&A(this.params.desiredState.playbackState,"paused");return;default:return(0,oe.assertNever)(e)}};this.subscription=new oe.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=$e(e.container,e.tuning),this.liveStreamClient=new Tn(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),Me(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:oe.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,oe.merge)(this.videoState.stateChangeStarted$.pipe((0,oe.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,oe.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ce(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(ze(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(De(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(0,oe.assertNever)(n.to)}},r)).add((0,oe.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,oe.observableFrom)(["init"])).pipe((0,oe.debounce)(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(ge(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:oe.VideoQuality.INVARIANT}),this.video.srcObject=e,A(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:oe.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),A(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:oe.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var qa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared/es2018");var Mt=require("@vkontakte/videoplayer-shared/es2018"),eS=a=>new Mt.Observable(e=>{let t=new Mt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Mt.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Mt.map)(({type:l})=>l!==void 0)),n=new Mt.Subject,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()}});var Je=require("@vkontakte/videoplayer-shared/es2018");function tS(){return new(window.AudioContext||window.webkitAudioContext)}var rS=require("@vkontakte/videoplayer-shared/es2018");var Ua=class Ua{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new Ee;this.subscriptions=new Je.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Je.filter)(s=>!!s.type),(0,Je.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){rS.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Je.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Je.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,Je.once)()).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=tS();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:Ua.errorId,category:Je.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ua.errorId} exception`,thrown:e})}};Ua.errorId="VolumeMultiplierManager";var ci=Ua;var rL={chunkDuration:5e3,maxParallelRequests:5},Ha=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),liveLatency$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject(""),getCurrentTime$:new y.ValueSubject(null)};this.subscription=new y.Subscription;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=ng([...ug(this.params.tuning),...og(this.params.tuning)],this.params.tuning).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,ml.default)(i,l)),...t.filter(l=>(0,ml.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new qa(s);let n=[...Bu(!0),...Bu(!1)];this.chromecastFormatsIterator=new qa(n.filter(l=>(0,y.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ci.isSupported()&&(this.volumeMultiplierManager=new ci(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,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.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(0,y.assertNever)(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(0,y.assertNonNullable)(o),new Da({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ca({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ai||!this.params.tuning.useHlsJs?new Ba({...n,source:o}):new Va({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Oa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Na({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new xb({...n,source:o,config:{...rL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Fa({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(0,y.assertNever)(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(0,y.assertNonNullable)(o),new Hi({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(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(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(0,y.assertNever)(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,aS.default)((0,iS.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$.pipe((0,y.filter)(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),eS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(i=>({id:`ProviderHangup:${i}`,category:y.ErrorCategory.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((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).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===y.ErrorCategory.NETWORK,u=i.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var O=require("@vkontakte/videoplayer-shared/es2018");var iL=5e3,sS="one_video_throughput",nS="one_video_rtt",Dt=window.navigator.connection,oS=()=>{let a=Dt==null?void 0:Dt.downlink;if((0,O.isNonNullable)(a)&&a!==10)return a*1e3},uS=()=>{let a=Dt==null?void 0:Dt.rtt;if((0,O.isNonNullable)(a)&&a!==3e3)return a},lS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},bl=class a{constructor(e){this.subscription=new O.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(sS)||(e.useBrowserEstimation?oS():void 0)||iL,r=(s=(i=a.load(nS))!=null?i:e.useBrowserEstimation?uS():void 0)!=null?s:0;if(this.throughput$=new O.ValueSubject(t),this.rtt$=new O.ValueSubject(r),this.rttAdjustedThroughput$=new O.ValueSubject(lS(t,r,e.rttPenaltyRequestSize)),this.throughput=Tr.getSmoothedValue(t,-1,e),this.rtt=Tr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=oS();u&&this.throughput.next(u);let l=uS();(0,O.isNonNullable)(l)&&this.rtt.next(l)};Dt&&"onchange"in Dt&&this.subscription.add((0,O.fromEvent)(Dt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{O.safeStorage.set(sS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{O.safeStorage.set(nS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,O.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,O.map)(({throughput:n,rtt:o})=>lS(n,o,e.rttPenaltyRequestSize)),(0,O.filter)(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=(0,O.now)(),i=new O.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,O.fromEvent)(e,"progress").pipe((0,O.once)()).subscribe(s=>{t=s.loaded,r=(0,O.now)()}));break;case 1:case 0:i.add((0,O.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,O.now)()}));break}i.add((0,O.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,O.now)(),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=(0,O.now)(),n=0,o=(0,O.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,(0,O.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,O.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=(0,O.now)()}else n+=d.byteLength;o=(0,O.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,O.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,O.now)()-o,this.concurrentDownloads.size),n=0,o=(0,O.now)());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=O.safeStorage.get(e);if((0,O.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},cS=bl;var Er=require("@vkontakte/videoplayer-shared/es2018"),dS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Er.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Er.VideoQuality.Q_720P,trafficSavingLimit:Er.VideoQuality.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Er.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},pS=a=>{var e;return{...(0,Er.fillWithDefault)(a,dS),configName:[...(e=a.configName)!=null?e:[],...dS.configName]}};var f=require("@vkontakte/videoplayer-shared/es2018");var Ct=require("@vkontakte/videoplayer-shared/es2018"),gl=({seekState:a,position$:e})=>(0,Ct.merge)(a.stateChangeEnded$.pipe((0,Ct.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Ct.filter)(Ct.isNonNullable)),e.pipe((0,Ct.filter)(()=>a.getState().state==="none")));var hS=require("@vkontakte/videoplayer-shared/es2018"),fS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,hS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var In=require("@vkontakte/videoplayer-shared/es2018"),mS=(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((0,In.filter)(i=>i.length>0),(0,In.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var ja=class{constructor(e={configName:[]},t=f.Tracer.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new q("stopped"),seekState:new q({state:"none"}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),videoStream:new q(void 0),audioStream:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),isLowLatency:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};this.info={playbackState$:new f.ValueSubject("stopped"),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),predefinedQualityLimitType$:new f.ValueSubject("unknown"),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:ub,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=pS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new cs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new cS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return(0,bS.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",(0,f.flattenObject)(r)),this.domContainer=fS(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new Ha({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(o=this.internalsExposure)==null||o.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!zi()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).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-.2),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){(0,f.assertNonNullable)(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((0,f.filter)(r=>r.length>0),(0,f.once)()).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",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.desiredState.autoVideoTrackLimits.startTransitionTo(i),this}setPlaybackRate(e){var r;(0,f.assertNonNullable)(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",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return mS(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((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(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((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Us({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),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",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,f.isInvariantQuality)(u)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.isHigher)(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((0,f.filterChanged)()).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((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).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((0,f.map)(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((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(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((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:gl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(gl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).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((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.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((0,f.once)(),(0,f.map)(n=>n!=null?n:(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-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 f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,f.filterChanged)());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((0,f.merge)(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((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(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 f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).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=Kt(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((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(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;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),ob(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>nb(r)),this.providerContainer.current$.subscribe(({type:r})=>ji("provider",r)),e.duration$.subscribe(r=>ji("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>ji("tracks",r)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),e.position$.subscribe(new ke("position")),e.currentVideoTrack$.pipe((0,f.map)(r=>r==null?void 0:r.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),e.isBuffering$.subscribe(new ke("isBuffering"))].forEach(r=>this.subscription.add(r)),ji("codecs",sg())}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(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((0,f.filterChanged)()).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((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,f.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(r=>r>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(r=>r>0),(0,f.filterChanged)()).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((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(r=>r.end>0),(0,f.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(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:f.ErrorCategory.DOM,message:String(i)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(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",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(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}};var St=require("@vkontakte/videoplayer-shared/es2018"),aL=`@vkontakte/videoplayer-core@${kn}`;