@vkontakte/videoplayer-core 2.0.118 → 2.0.119-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.cjs.js CHANGED
@@ -1,19 +1,19 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.118
3
- * Fri, 29 Nov 2024 12:48:50 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-118/doc/
2
+ * @vkontakte/videoplayer-core v2.0.119-beta.0
3
+ * Wed, 04 Dec 2024 14:54:55 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-119/doc/
5
5
  */
6
- "use strict";var xS=Object.create;var fi=Object.defineProperty,PS=Object.defineProperties,AS=Object.getOwnPropertyDescriptor,wS=Object.getOwnPropertyDescriptors,kS=Object.getOwnPropertyNames,ts=Object.getOwnPropertySymbols,RS=Object.getPrototypeOf,En=Object.prototype.hasOwnProperty,Wl=Object.prototype.propertyIsEnumerable;var $S=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var ct=Math.pow,Ql=(a,e,t)=>e in a?fi(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,R=(a,e)=>{for(var t in e||(e={}))En.call(e,t)&&Ql(a,t,e[t]);if(ts)for(var t of ts(e))Wl.call(e,t)&&Ql(a,t,e[t]);return a},H=(a,e)=>PS(a,wS(e));var Yl=(a,e)=>{var t={};for(var r in a)En.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&ts)for(var r of ts(a))e.indexOf(r)<0&&Wl.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),LS=(a,e)=>{for(var t in e)fi(a,t,{get:e[t],enumerable:!0})},zl=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of kS(e))!En.call(a,i)&&i!==t&&fi(a,i,{get:()=>e[i],enumerable:!(r=AS(e,i))||r.enumerable});return a};var X=(a,e,t)=>(t=a!=null?xS(RS(a)):{},zl(e||!a||!a.__esModule?fi(t,"default",{value:a,enumerable:!0}):t,a)),MS=a=>zl(fi({},"__esModule",{value:!0}),a);var O=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),xn=function(a,e){this[0]=a,this[1]=e},me=(a,e,t)=>{var r=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof xn,p=d.done;Promise.resolve(c?o[0]:o).then(h=>c?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[$S("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var he=b((An,Kl)=>{"use strict";var bi=function(a){return a&&a.Math===Math&&a};Kl.exports=bi(typeof globalThis=="object"&&globalThis)||bi(typeof window=="object"&&window)||bi(typeof self=="object"&&self)||bi(typeof global=="object"&&global)||bi(typeof An=="object"&&An)||function(){return this}()||Function("return this")()});var Pe=b((l$,Jl)=>{"use strict";Jl.exports=function(a){try{return!!a()}catch(e){return!0}}});var gi=b((c$,Xl)=>{"use strict";var CS=Pe();Xl.exports=!CS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var wn=b((d$,rc)=>{"use strict";var DS=gi(),tc=Function.prototype,Zl=tc.apply,ec=tc.call;rc.exports=typeof Reflect=="object"&&Reflect.apply||(DS?ec.bind(Zl):function(){return ec.apply(Zl,arguments)})});var ve=b((p$,sc)=>{"use strict";var ic=gi(),ac=Function.prototype,kn=ac.call,OS=ic&&ac.bind.bind(kn,kn);sc.exports=ic?OS:function(a){return function(){return kn.apply(a,arguments)}}});var or=b((h$,oc)=>{"use strict";var nc=ve(),BS=nc({}.toString),VS=nc("".slice);oc.exports=function(a){return VS(BS(a),8,-1)}});var Rn=b((f$,uc)=>{"use strict";var _S=or(),NS=ve();uc.exports=function(a){if(_S(a)==="Function")return NS(a)}});var pe=b((m$,lc)=>{"use strict";var $n=typeof document=="object"&&document.all;lc.exports=typeof $n=="undefined"&&$n!==void 0?function(a){return typeof a=="function"||a===$n}:function(a){return typeof a=="function"}});var _e=b((b$,cc)=>{"use strict";var FS=Pe();cc.exports=!FS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ne=b((g$,dc)=>{"use strict";var qS=gi(),as=Function.prototype.call;dc.exports=qS?as.bind(as):function(){return as.apply(as,arguments)}});var Ln=b(fc=>{"use strict";var pc={}.propertyIsEnumerable,hc=Object.getOwnPropertyDescriptor,US=hc&&!pc.call({1:2},1);fc.f=US?function(e){var t=hc(this,e);return!!t&&t.enumerable}:pc});var vi=b((S$,mc)=>{"use strict";mc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var gc=b((y$,bc)=>{"use strict";var HS=ve(),jS=Pe(),GS=or(),Mn=Object,QS=HS("".split);bc.exports=jS(function(){return!Mn("z").propertyIsEnumerable(0)})?function(a){return GS(a)==="String"?QS(a,""):Mn(a)}:Mn});var Lr=b((T$,vc)=>{"use strict";vc.exports=function(a){return a==null}});var jt=b((I$,Sc)=>{"use strict";var WS=Lr(),YS=TypeError;Sc.exports=function(a){if(WS(a))throw new YS("Can't call method on "+a);return a}});var ur=b((E$,yc)=>{"use strict";var zS=gc(),KS=jt();yc.exports=function(a){return zS(KS(a))}});var Fe=b((x$,Tc)=>{"use strict";var JS=pe();Tc.exports=function(a){return typeof a=="object"?a!==null:JS(a)}});var Mr=b((P$,Ic)=>{"use strict";Ic.exports={}});var It=b((A$,xc)=>{"use strict";var Cn=Mr(),Dn=he(),XS=pe(),Ec=function(a){return XS(a)?a:void 0};xc.exports=function(a,e){return arguments.length<2?Ec(Cn[a])||Ec(Dn[a]):Cn[a]&&Cn[a][e]||Dn[a]&&Dn[a][e]}});var Si=b((w$,Pc)=>{"use strict";var ZS=ve();Pc.exports=ZS({}.isPrototypeOf)});var lr=b((k$,kc)=>{"use strict";var ey=he(),Ac=ey.navigator,wc=Ac&&Ac.userAgent;kc.exports=wc?String(wc):""});var Bn=b((R$,Dc)=>{"use strict";var Cc=he(),On=lr(),Rc=Cc.process,$c=Cc.Deno,Lc=Rc&&Rc.versions||$c&&$c.version,Mc=Lc&&Lc.v8,rt,ss;Mc&&(rt=Mc.split("."),ss=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!ss&&On&&(rt=On.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=On.match(/Chrome\/(\d+)/),rt&&(ss=+rt[1])));Dc.exports=ss});var Vn=b(($$,Bc)=>{"use strict";var Oc=Bn(),ty=Pe(),ry=he(),iy=ry.String;Bc.exports=!!Object.getOwnPropertySymbols&&!ty(function(){var a=Symbol("symbol detection");return!iy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Oc&&Oc<41})});var _n=b((L$,Vc)=>{"use strict";var ay=Vn();Vc.exports=ay&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Nn=b((M$,_c)=>{"use strict";var sy=It(),ny=pe(),oy=Si(),uy=_n(),ly=Object;_c.exports=uy?function(a){return typeof a=="symbol"}:function(a){var e=sy("Symbol");return ny(e)&&oy(e.prototype,ly(a))}});var yi=b((C$,Nc)=>{"use strict";var cy=String;Nc.exports=function(a){try{return cy(a)}catch(e){return"Object"}}});var dt=b((D$,Fc)=>{"use strict";var dy=pe(),py=yi(),hy=TypeError;Fc.exports=function(a){if(dy(a))return a;throw new hy(py(a)+" is not a function")}});var Ti=b((O$,qc)=>{"use strict";var fy=dt(),my=Lr();qc.exports=function(a,e){var t=a[e];return my(t)?void 0:fy(t)}});var Hc=b((B$,Uc)=>{"use strict";var Fn=Ne(),qn=pe(),Un=Fe(),by=TypeError;Uc.exports=function(a,e){var t,r;if(e==="string"&&qn(t=a.toString)&&!Un(r=Fn(t,a))||qn(t=a.valueOf)&&!Un(r=Fn(t,a))||e!=="string"&&qn(t=a.toString)&&!Un(r=Fn(t,a)))return r;throw new by("Can't convert object to primitive value")}});var it=b((V$,jc)=>{"use strict";jc.exports=!0});var Wc=b((_$,Qc)=>{"use strict";var Gc=he(),gy=Object.defineProperty;Qc.exports=function(a,e){try{gy(Gc,a,{value:e,configurable:!0,writable:!0})}catch(t){Gc[a]=e}return e}});var Ii=b((N$,Kc)=>{"use strict";var vy=it(),Sy=he(),yy=Wc(),Yc="__core-js_shared__",zc=Kc.exports=Sy[Yc]||yy(Yc,{});(zc.versions||(zc.versions=[])).push({version:"3.38.0",mode:vy?"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 Hn=b((F$,Xc)=>{"use strict";var Jc=Ii();Xc.exports=function(a,e){return Jc[a]||(Jc[a]=e||{})}});var Cr=b((q$,Zc)=>{"use strict";var Ty=jt(),Iy=Object;Zc.exports=function(a){return Iy(Ty(a))}});var at=b((U$,ed)=>{"use strict";var Ey=ve(),xy=Cr(),Py=Ey({}.hasOwnProperty);ed.exports=Object.hasOwn||function(e,t){return Py(xy(e),t)}});var jn=b((H$,td)=>{"use strict";var Ay=ve(),wy=0,ky=Math.random(),Ry=Ay(1 .toString);td.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Ry(++wy+ky,36)}});var Ae=b((j$,id)=>{"use strict";var $y=he(),Ly=Hn(),rd=at(),My=jn(),Cy=Vn(),Dy=_n(),Dr=$y.Symbol,Gn=Ly("wks"),Oy=Dy?Dr.for||Dr:Dr&&Dr.withoutSetter||My;id.exports=function(a){return rd(Gn,a)||(Gn[a]=Cy&&rd(Dr,a)?Dr[a]:Oy("Symbol."+a)),Gn[a]}});var od=b((G$,nd)=>{"use strict";var By=Ne(),ad=Fe(),sd=Nn(),Vy=Ti(),_y=Hc(),Ny=Ae(),Fy=TypeError,qy=Ny("toPrimitive");nd.exports=function(a,e){if(!ad(a)||sd(a))return a;var t=Vy(a,qy),r;if(t){if(e===void 0&&(e="default"),r=By(t,a,e),!ad(r)||sd(r))return r;throw new Fy("Can't convert object to primitive value")}return e===void 0&&(e="number"),_y(a,e)}});var Qn=b((Q$,ud)=>{"use strict";var Uy=od(),Hy=Nn();ud.exports=function(a){var e=Uy(a,"string");return Hy(e)?e:e+""}});var ns=b((W$,cd)=>{"use strict";var jy=he(),ld=Fe(),Wn=jy.document,Gy=ld(Wn)&&ld(Wn.createElement);cd.exports=function(a){return Gy?Wn.createElement(a):{}}});var Yn=b((Y$,dd)=>{"use strict";var Qy=_e(),Wy=Pe(),Yy=ns();dd.exports=!Qy&&!Wy(function(){return Object.defineProperty(Yy("div"),"a",{get:function(){return 7}}).a!==7})});var fd=b(hd=>{"use strict";var zy=_e(),Ky=Ne(),Jy=Ln(),Xy=vi(),Zy=ur(),eT=Qn(),tT=at(),rT=Yn(),pd=Object.getOwnPropertyDescriptor;hd.f=zy?pd:function(e,t){if(e=Zy(e),t=eT(t),rT)try{return pd(e,t)}catch(r){}if(tT(e,t))return Xy(!Ky(Jy.f,e,t),e[t])}});var zn=b((K$,md)=>{"use strict";var iT=Pe(),aT=pe(),sT=/#|\.prototype\./,Ei=function(a,e){var t=oT[nT(a)];return t===lT?!0:t===uT?!1:aT(e)?iT(e):!!e},nT=Ei.normalize=function(a){return String(a).replace(sT,".").toLowerCase()},oT=Ei.data={},uT=Ei.NATIVE="N",lT=Ei.POLYFILL="P";md.exports=Ei});var Or=b((J$,gd)=>{"use strict";var bd=Rn(),cT=dt(),dT=gi(),pT=bd(bd.bind);gd.exports=function(a,e){return cT(a),e===void 0?a:dT?pT(a,e):function(){return a.apply(e,arguments)}}});var Kn=b((X$,vd)=>{"use strict";var hT=_e(),fT=Pe();vd.exports=hT&&fT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var pt=b((Z$,Sd)=>{"use strict";var mT=Fe(),bT=String,gT=TypeError;Sd.exports=function(a){if(mT(a))return a;throw new gT(bT(a)+" is not an object")}});var cr=b(Td=>{"use strict";var vT=_e(),ST=Yn(),yT=Kn(),os=pt(),yd=Qn(),TT=TypeError,Jn=Object.defineProperty,IT=Object.getOwnPropertyDescriptor,Xn="enumerable",Zn="configurable",eo="writable";Td.f=vT?yT?function(e,t,r){if(os(e),t=yd(t),os(r),typeof e=="function"&&t==="prototype"&&"value"in r&&eo in r&&!r[eo]){var i=IT(e,t);i&&i[eo]&&(e[t]=r.value,r={configurable:Zn in r?r[Zn]:i[Zn],enumerable:Xn in r?r[Xn]:i[Xn],writable:!1})}return Jn(e,t,r)}:Jn:function(e,t,r){if(os(e),t=yd(t),os(r),ST)try{return Jn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new TT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Br=b((tL,Id)=>{"use strict";var ET=_e(),xT=cr(),PT=vi();Id.exports=ET?function(a,e,t){return xT.f(a,e,PT(1,t))}:function(a,e,t){return a[e]=t,a}});var fe=b((rL,xd)=>{"use strict";var xi=he(),AT=wn(),wT=Rn(),kT=pe(),RT=fd().f,$T=zn(),Vr=Mr(),LT=Or(),_r=Br(),Ed=at();Ii();var MT=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 AT(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?xi:i?xi[t]:xi[t]&&xi[t].prototype,o=r?Vr:Vr[t]||_r(Vr,t,{})[t],u=o.prototype,l,d,c,p,h,m,g,v,I;for(p in e)l=$T(r?p:t+(i?".":"#")+p,a.forced),d=!l&&n&&Ed(n,p),m=o[p],d&&(a.dontCallGetSet?(I=RT(n,p),g=I&&I.value):g=n[p]),h=d&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&d?v=LT(h,xi):a.wrap&&d?v=MT(h):s&&kT(h)?v=wT(h):v=h,(a.sham||h&&h.sham||m&&m.sham)&&_r(v,"sham",!0),_r(o,p,v),s&&(c=t+"Prototype",Ed(Vr,c)||_r(Vr,c,{}),_r(Vr[c],p,h),a.real&&u&&(l||!u[p])&&_r(u,p,h)))}});var Ad=b((iL,Pd)=>{"use strict";var CT=Math.ceil,DT=Math.floor;Pd.exports=Math.trunc||function(e){var t=+e;return(t>0?DT:CT)(t)}});var Pi=b((aL,wd)=>{"use strict";var OT=Ad();wd.exports=function(a){var e=+a;return e!==e||e===0?0:OT(e)}});var Rd=b((sL,kd)=>{"use strict";var BT=Pi(),VT=Math.max,_T=Math.min;kd.exports=function(a,e){var t=BT(a);return t<0?VT(t+e,0):_T(t,e)}});var to=b((nL,$d)=>{"use strict";var NT=Pi(),FT=Math.min;$d.exports=function(a){var e=NT(a);return e>0?FT(e,9007199254740991):0}});var Nr=b((oL,Ld)=>{"use strict";var qT=to();Ld.exports=function(a){return qT(a.length)}});var ro=b((uL,Cd)=>{"use strict";var UT=ur(),HT=Rd(),jT=Nr(),Md=function(a){return function(e,t,r){var i=UT(e),s=jT(i);if(s===0)return!a&&-1;var n=HT(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}};Cd.exports={includes:Md(!0),indexOf:Md(!1)}});var Ai=b((lL,Dd)=>{"use strict";Dd.exports=function(){}});var Od=b(()=>{"use strict";var GT=fe(),QT=ro().includes,WT=Pe(),YT=Ai(),zT=WT(function(){return!Array(1).includes()});GT({target:"Array",proto:!0,forced:zT},{includes:function(e){return QT(this,e,arguments.length>1?arguments[1]:void 0)}});YT("includes")});var Gt=b((pL,Bd)=>{"use strict";var KT=It();Bd.exports=KT});var _d=b((hL,Vd)=>{"use strict";Od();var JT=Gt();Vd.exports=JT("Array","includes")});var Fd=b((fL,Nd)=>{"use strict";var XT=_d();Nd.exports=XT});var ht=b((mL,qd)=>{"use strict";var ZT=Fd();qd.exports=ZT});var ls=b((AL,jd)=>{"use strict";var tI=Hn(),rI=jn(),Hd=tI("keys");jd.exports=function(a){return Hd[a]||(Hd[a]=rI(a))}});var Qd=b((wL,Gd)=>{"use strict";var iI=Pe();Gd.exports=!iI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var cs=b((kL,Yd)=>{"use strict";var aI=at(),sI=pe(),nI=Cr(),oI=ls(),uI=Qd(),Wd=oI("IE_PROTO"),io=Object,lI=io.prototype;Yd.exports=uI?io.getPrototypeOf:function(a){var e=nI(a);if(aI(e,Wd))return e[Wd];var t=e.constructor;return sI(t)&&e instanceof t?t.prototype:e instanceof io?lI:null}});var ds=b((RL,zd)=>{"use strict";zd.exports={}});var Xd=b(($L,Jd)=>{"use strict";var cI=ve(),ao=at(),dI=ur(),pI=ro().indexOf,hI=ds(),Kd=cI([].push);Jd.exports=function(a,e){var t=dI(a),r=0,i=[],s;for(s in t)!ao(hI,s)&&ao(t,s)&&Kd(i,s);for(;e.length>r;)ao(t,s=e[r++])&&(~pI(i,s)||Kd(i,s));return i}});var so=b((LL,Zd)=>{"use strict";Zd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var no=b((ML,ep)=>{"use strict";var fI=Xd(),mI=so();ep.exports=Object.keys||function(e){return fI(e,mI)}});var oo=b((CL,sp)=>{"use strict";var rp=_e(),bI=Pe(),ip=ve(),gI=cs(),vI=no(),SI=ur(),yI=Ln().f,ap=ip(yI),TI=ip([].push),II=rp&&bI(function(){var a=Object.create(null);return a[2]=2,!ap(a,2)}),tp=function(a){return function(e){for(var t=SI(e),r=vI(t),i=II&&gI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!rp||(i?u in t:ap(t,u)))&&TI(o,a?[u,t[u]]:t[u]);return o}};sp.exports={entries:tp(!0),values:tp(!1)}});var np=b(()=>{"use strict";var EI=fe(),xI=oo().entries;EI({target:"Object",stat:!0},{entries:function(e){return xI(e)}})});var up=b((BL,op)=>{"use strict";np();var PI=Mr();op.exports=PI.Object.entries});var cp=b((VL,lp)=>{"use strict";var AI=up();lp.exports=AI});var Fr=b((_L,dp)=>{"use strict";var wI=cp();dp.exports=wI});var dr=b((NL,pp)=>{"use strict";pp.exports={}});var mp=b((FL,fp)=>{"use strict";var kI=he(),RI=pe(),hp=kI.WeakMap;fp.exports=RI(hp)&&/native code/.test(String(hp))});var po=b((qL,vp)=>{"use strict";var $I=mp(),gp=he(),LI=Fe(),MI=Br(),uo=at(),lo=Ii(),CI=ls(),DI=ds(),bp="Object already initialized",co=gp.TypeError,OI=gp.WeakMap,ps,wi,hs,BI=function(a){return hs(a)?wi(a):ps(a,{})},VI=function(a){return function(e){var t;if(!LI(e)||(t=wi(e)).type!==a)throw new co("Incompatible receiver, "+a+" required");return t}};$I||lo.state?(st=lo.state||(lo.state=new OI),st.get=st.get,st.has=st.has,st.set=st.set,ps=function(a,e){if(st.has(a))throw new co(bp);return e.facade=a,st.set(a,e),e},wi=function(a){return st.get(a)||{}},hs=function(a){return st.has(a)}):(pr=CI("state"),DI[pr]=!0,ps=function(a,e){if(uo(a,pr))throw new co(bp);return e.facade=a,MI(a,pr,e),e},wi=function(a){return uo(a,pr)?a[pr]:{}},hs=function(a){return uo(a,pr)});var st,pr;vp.exports={set:ps,get:wi,has:hs,enforce:BI,getterFor:VI}});var mo=b((UL,yp)=>{"use strict";var ho=_e(),_I=at(),Sp=Function.prototype,NI=ho&&Object.getOwnPropertyDescriptor,fo=_I(Sp,"name"),FI=fo&&function(){}.name==="something",qI=fo&&(!ho||ho&&NI(Sp,"name").configurable);yp.exports={EXISTS:fo,PROPER:FI,CONFIGURABLE:qI}});var Ip=b(Tp=>{"use strict";var UI=_e(),HI=Kn(),jI=cr(),GI=pt(),QI=ur(),WI=no();Tp.f=UI&&!HI?Object.defineProperties:function(e,t){GI(e);for(var r=QI(t),i=WI(t),s=i.length,n=0,o;s>n;)jI.f(e,o=i[n++],r[o]);return e}});var bo=b((jL,Ep)=>{"use strict";var YI=It();Ep.exports=YI("document","documentElement")});var yo=b((GL,$p)=>{"use strict";var zI=pt(),KI=Ip(),xp=so(),JI=ds(),XI=bo(),ZI=ns(),eE=ls(),Pp=">",Ap="<",vo="prototype",So="script",kp=eE("IE_PROTO"),go=function(){},Rp=function(a){return Ap+So+Pp+a+Ap+"/"+So+Pp},wp=function(a){a.write(Rp("")),a.close();var e=a.parentWindow.Object;return a=null,e},tE=function(){var a=ZI("iframe"),e="java"+So+":",t;return a.style.display="none",XI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Rp("document.F=Object")),t.close(),t.F},fs,ms=function(){try{fs=new ActiveXObject("htmlfile")}catch(e){}ms=typeof document!="undefined"?document.domain&&fs?wp(fs):tE():wp(fs);for(var a=xp.length;a--;)delete ms[vo][xp[a]];return ms()};JI[kp]=!0;$p.exports=Object.create||function(e,t){var r;return e!==null?(go[vo]=zI(e),r=new go,go[vo]=null,r[kp]=e):r=ms(),t===void 0?r:KI.f(r,t)}});var qr=b((QL,Lp)=>{"use strict";var rE=Br();Lp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:rE(a,e,t),a}});var xo=b((WL,Dp)=>{"use strict";var iE=Pe(),aE=pe(),sE=Fe(),nE=yo(),Mp=cs(),oE=qr(),uE=Ae(),lE=it(),Eo=uE("iterator"),Cp=!1,Et,To,Io;[].keys&&(Io=[].keys(),"next"in Io?(To=Mp(Mp(Io)),To!==Object.prototype&&(Et=To)):Cp=!0);var cE=!sE(Et)||iE(function(){var a={};return Et[Eo].call(a)!==a});cE?Et={}:lE&&(Et=nE(Et));aE(Et[Eo])||oE(Et,Eo,function(){return this});Dp.exports={IteratorPrototype:Et,BUGGY_SAFARI_ITERATORS:Cp}});var bs=b((YL,Bp)=>{"use strict";var dE=Ae(),pE=dE("toStringTag"),Op={};Op[pE]="z";Bp.exports=String(Op)==="[object z]"});var ki=b((zL,Vp)=>{"use strict";var hE=bs(),fE=pe(),gs=or(),mE=Ae(),bE=mE("toStringTag"),gE=Object,vE=gs(function(){return arguments}())==="Arguments",SE=function(a,e){try{return a[e]}catch(t){}};Vp.exports=hE?gs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=SE(e=gE(a),bE))=="string"?t:vE?gs(e):(r=gs(e))==="Object"&&fE(e.callee)?"Arguments":r}});var Np=b((KL,_p)=>{"use strict";var yE=bs(),TE=ki();_p.exports=yE?{}.toString:function(){return"[object "+TE(this)+"]"}});var Ri=b((JL,qp)=>{"use strict";var IE=bs(),EE=cr().f,xE=Br(),PE=at(),AE=Np(),wE=Ae(),Fp=wE("toStringTag");qp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(PE(i,Fp)||EE(i,Fp,{configurable:!0,value:e}),r&&!IE&&xE(i,"toString",AE))}});var Hp=b((XL,Up)=>{"use strict";var kE=xo().IteratorPrototype,RE=yo(),$E=vi(),LE=Ri(),ME=dr(),CE=function(){return this};Up.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=RE(kE,{next:$E(+!r,t)}),LE(a,i,!1,!0),ME[i]=CE,a}});var Gp=b((ZL,jp)=>{"use strict";var DE=ve(),OE=dt();jp.exports=function(a,e,t){try{return DE(OE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Wp=b((eM,Qp)=>{"use strict";var BE=Fe();Qp.exports=function(a){return BE(a)||a===null}});var zp=b((tM,Yp)=>{"use strict";var VE=Wp(),_E=String,NE=TypeError;Yp.exports=function(a){if(VE(a))return a;throw new NE("Can't set "+_E(a)+" as a prototype")}});var Po=b((rM,Kp)=>{"use strict";var FE=Gp(),qE=Fe(),UE=jt(),HE=zp();Kp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=FE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return UE(i),HE(s),qE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var oh=b((iM,nh)=>{"use strict";var jE=fe(),GE=Ne(),vs=it(),ah=mo(),QE=pe(),WE=Hp(),Jp=cs(),Xp=Po(),YE=Ri(),zE=Br(),Ao=qr(),KE=Ae(),Zp=dr(),sh=xo(),JE=ah.PROPER,XE=ah.CONFIGURABLE,eh=sh.IteratorPrototype,Ss=sh.BUGGY_SAFARI_ITERATORS,$i=KE("iterator"),th="keys",Li="values",rh="entries",ih=function(){return this};nh.exports=function(a,e,t,r,i,s,n){WE(t,e,r);var o=function(I){if(I===i&&p)return p;if(!Ss&&I&&I in d)return d[I];switch(I){case th:return function(){return new t(this,I)};case Li:return function(){return new t(this,I)};case rh:return function(){return new t(this,I)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[$i]||d["@@iterator"]||i&&d[i],p=!Ss&&c||o(i),h=e==="Array"&&d.entries||c,m,g,v;if(h&&(m=Jp(h.call(new a)),m!==Object.prototype&&m.next&&(!vs&&Jp(m)!==eh&&(Xp?Xp(m,eh):QE(m[$i])||Ao(m,$i,ih)),YE(m,u,!0,!0),vs&&(Zp[u]=ih))),JE&&i===Li&&c&&c.name!==Li&&(!vs&&XE?zE(d,"name",Li):(l=!0,p=function(){return GE(c,this)})),i)if(g={values:o(Li),keys:s?p:o(th),entries:o(rh)},n)for(v in g)(Ss||l||!(v in d))&&Ao(d,v,g[v]);else jE({target:e,proto:!0,forced:Ss||l},g);return(!vs||n)&&d[$i]!==p&&Ao(d,$i,p,{name:i}),Zp[e]=p,g}});var lh=b((aM,uh)=>{"use strict";uh.exports=function(a,e){return{value:a,done:e}}});var ko=b((sM,fh)=>{"use strict";var ZE=ur(),wo=Ai(),ch=dr(),ph=po(),ex=cr().f,tx=oh(),ys=lh(),rx=it(),ix=_e(),hh="Array Iterator",ax=ph.set,sx=ph.getterFor(hh);fh.exports=tx(Array,"Array",function(a,e){ax(this,{type:hh,target:ZE(a),index:0,kind:e})},function(){var a=sx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ys(void 0,!0);switch(a.kind){case"keys":return ys(t,!1);case"values":return ys(e[t],!1)}return ys([t,e[t]],!1)},"values");var dh=ch.Arguments=ch.Array;wo("keys");wo("values");wo("entries");if(!rx&&ix&&dh.name!=="values")try{ex(dh,"name",{value:"values"})}catch(a){}});var bh=b((nM,mh)=>{"use strict";var nx=Ae(),ox=dr(),ux=nx("iterator"),lx=Array.prototype;mh.exports=function(a){return a!==void 0&&(ox.Array===a||lx[ux]===a)}});var Ro=b((oM,vh)=>{"use strict";var cx=ki(),gh=Ti(),dx=Lr(),px=dr(),hx=Ae(),fx=hx("iterator");vh.exports=function(a){if(!dx(a))return gh(a,fx)||gh(a,"@@iterator")||px[cx(a)]}});var yh=b((uM,Sh)=>{"use strict";var mx=Ne(),bx=dt(),gx=pt(),vx=yi(),Sx=Ro(),yx=TypeError;Sh.exports=function(a,e){var t=arguments.length<2?Sx(a):e;if(bx(t))return gx(mx(t,a));throw new yx(vx(a)+" is not iterable")}});var Eh=b((lM,Ih)=>{"use strict";var Tx=Ne(),Th=pt(),Ix=Ti();Ih.exports=function(a,e,t){var r,i;Th(a);try{if(r=Ix(a,"return"),!r){if(e==="throw")throw t;return t}r=Tx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Th(r),t}});var Is=b((cM,wh)=>{"use strict";var Ex=Or(),xx=Ne(),Px=pt(),Ax=yi(),wx=bh(),kx=Nr(),xh=Si(),Rx=yh(),$x=Ro(),Ph=Eh(),Lx=TypeError,Ts=function(a,e){this.stopped=a,this.result=e},Ah=Ts.prototype;wh.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=Ex(e,r),l,d,c,p,h,m,g,v=function(T){return l&&Ph(l,"normal",T),new Ts(!0,T)},I=function(T){return i?(Px(T),o?u(T[0],T[1],v):u(T[0],T[1])):o?u(T,v):u(T)};if(s)l=a.iterator;else if(n)l=a;else{if(d=$x(a),!d)throw new Lx(Ax(a)+" is not iterable");if(wx(d)){for(c=0,p=kx(a);p>c;c++)if(h=I(a[c]),h&&xh(Ah,h))return h;return new Ts(!1)}l=Rx(a,d)}for(m=s?a.next:l.next;!(g=xx(m,l)).done;){try{h=I(g.value)}catch(T){Ph(l,"throw",T)}if(typeof h=="object"&&h&&xh(Ah,h))return h}return new Ts(!1)}});var Rh=b((dM,kh)=>{"use strict";var Mx=_e(),Cx=cr(),Dx=vi();kh.exports=function(a,e,t){Mx?Cx.f(a,e,Dx(0,t)):a[e]=t}});var $h=b(()=>{"use strict";var Ox=fe(),Bx=Is(),Vx=Rh();Ox({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Bx(e,function(r,i){Vx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Mh=b((fM,Lh)=>{"use strict";ko();$h();var _x=Mr();Lh.exports=_x.Object.fromEntries});var Dh=b((mM,Ch)=>{"use strict";Ch.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 Bh=b(()=>{"use strict";ko();var Nx=Dh(),Fx=he(),qx=Ri(),Oh=dr();for(Es in Nx)qx(Fx[Es],Es),Oh[Es]=Oh.Array;var Es});var _h=b((vM,Vh)=>{"use strict";var Ux=Mh();Bh();Vh.exports=Ux});var $o=b((SM,Nh)=>{"use strict";var Hx=_h();Nh.exports=Hx});var Fh=b(()=>{"use strict"});var Lo=b((IM,qh)=>{"use strict";var Mi=he(),jx=lr(),Gx=or(),xs=function(a){return jx.slice(0,a.length)===a};qh.exports=function(){return xs("Bun/")?"BUN":xs("Cloudflare-Workers")?"CLOUDFLARE":xs("Deno/")?"DENO":xs("Node.js/")?"NODE":Mi.Bun&&typeof Bun.version=="string"?"BUN":Mi.Deno&&typeof Deno.version=="object"?"DENO":Gx(Mi.process)==="process"?"NODE":Mi.window&&Mi.document?"BROWSER":"REST"}()});var Ps=b((EM,Uh)=>{"use strict";var Qx=Lo();Uh.exports=Qx==="NODE"});var jh=b((xM,Hh)=>{"use strict";var Wx=cr();Hh.exports=function(a,e,t){return Wx.f(a,e,t)}});var Wh=b((PM,Qh)=>{"use strict";var Yx=It(),zx=jh(),Kx=Ae(),Jx=_e(),Gh=Kx("species");Qh.exports=function(a){var e=Yx(a);Jx&&e&&!e[Gh]&&zx(e,Gh,{configurable:!0,get:function(){return this}})}});var zh=b((AM,Yh)=>{"use strict";var Xx=Si(),Zx=TypeError;Yh.exports=function(a,e){if(Xx(e,a))return a;throw new Zx("Incorrect invocation")}});var Co=b((wM,Kh)=>{"use strict";var eP=ve(),tP=pe(),Mo=Ii(),rP=eP(Function.toString);tP(Mo.inspectSource)||(Mo.inspectSource=function(a){return rP(a)});Kh.exports=Mo.inspectSource});var Oo=b((kM,tf)=>{"use strict";var iP=ve(),aP=Pe(),Jh=pe(),sP=ki(),nP=It(),oP=Co(),Xh=function(){},Zh=nP("Reflect","construct"),Do=/^\s*(?:class|function)\b/,uP=iP(Do.exec),lP=!Do.test(Xh),Ci=function(e){if(!Jh(e))return!1;try{return Zh(Xh,[],e),!0}catch(t){return!1}},ef=function(e){if(!Jh(e))return!1;switch(sP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return lP||!!uP(Do,oP(e))}catch(t){return!0}};ef.sham=!0;tf.exports=!Zh||aP(function(){var a;return Ci(Ci.call)||!Ci(Object)||!Ci(function(){a=!0})||a})?ef:Ci});var af=b((RM,rf)=>{"use strict";var cP=Oo(),dP=yi(),pP=TypeError;rf.exports=function(a){if(cP(a))return a;throw new pP(dP(a)+" is not a constructor")}});var Bo=b(($M,nf)=>{"use strict";var sf=pt(),hP=af(),fP=Lr(),mP=Ae(),bP=mP("species");nf.exports=function(a,e){var t=sf(a).constructor,r;return t===void 0||fP(r=sf(t)[bP])?e:hP(r)}});var uf=b((LM,of)=>{"use strict";var gP=ve();of.exports=gP([].slice)});var cf=b((MM,lf)=>{"use strict";var vP=TypeError;lf.exports=function(a,e){if(a<e)throw new vP("Not enough arguments");return a}});var Vo=b((CM,df)=>{"use strict";var SP=lr();df.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(SP)});var Qo=b((DM,yf)=>{"use strict";var qe=he(),yP=wn(),TP=Or(),pf=pe(),IP=at(),Sf=Pe(),hf=bo(),EP=uf(),ff=ns(),xP=cf(),PP=Vo(),AP=Ps(),Ho=qe.setImmediate,jo=qe.clearImmediate,wP=qe.process,_o=qe.Dispatch,kP=qe.Function,mf=qe.MessageChannel,RP=qe.String,No=0,Di={},bf="onreadystatechange",Oi,hr,Fo,qo;Sf(function(){Oi=qe.location});var Go=function(a){if(IP(Di,a)){var e=Di[a];delete Di[a],e()}},Uo=function(a){return function(){Go(a)}},gf=function(a){Go(a.data)},vf=function(a){qe.postMessage(RP(a),Oi.protocol+"//"+Oi.host)};(!Ho||!jo)&&(Ho=function(e){xP(arguments.length,1);var t=pf(e)?e:kP(e),r=EP(arguments,1);return Di[++No]=function(){yP(t,void 0,r)},hr(No),No},jo=function(e){delete Di[e]},AP?hr=function(a){wP.nextTick(Uo(a))}:_o&&_o.now?hr=function(a){_o.now(Uo(a))}:mf&&!PP?(Fo=new mf,qo=Fo.port2,Fo.port1.onmessage=gf,hr=TP(qo.postMessage,qo)):qe.addEventListener&&pf(qe.postMessage)&&!qe.importScripts&&Oi&&Oi.protocol!=="file:"&&!Sf(vf)?(hr=vf,qe.addEventListener("message",gf,!1)):bf in ff("script")?hr=function(a){hf.appendChild(ff("script"))[bf]=function(){hf.removeChild(this),Go(a)}}:hr=function(a){setTimeout(Uo(a),0)});yf.exports={set:Ho,clear:jo}});var Ef=b((OM,If)=>{"use strict";var Tf=he(),$P=_e(),LP=Object.getOwnPropertyDescriptor;If.exports=function(a){if(!$P)return Tf[a];var e=LP(Tf,a);return e&&e.value}});var Wo=b((BM,Pf)=>{"use strict";var xf=function(){this.head=null,this.tail=null};xf.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}}};Pf.exports=xf});var wf=b((VM,Af)=>{"use strict";var MP=lr();Af.exports=/ipad|iphone|ipod/i.test(MP)&&typeof Pebble!="undefined"});var Rf=b((_M,kf)=>{"use strict";var CP=lr();kf.exports=/web0s(?!.*chrome)/i.test(CP)});var Bf=b((NM,Of)=>{"use strict";var Hr=he(),DP=Ef(),$f=Or(),Yo=Qo().set,OP=Wo(),BP=Vo(),VP=wf(),_P=Rf(),zo=Ps(),Lf=Hr.MutationObserver||Hr.WebKitMutationObserver,Mf=Hr.document,Cf=Hr.process,As=Hr.Promise,Xo=DP("queueMicrotask"),Ur,Ko,Jo,ws,Df;Xo||(Bi=new OP,Vi=function(){var a,e;for(zo&&(a=Cf.domain)&&a.exit();e=Bi.get();)try{e()}catch(t){throw Bi.head&&Ur(),t}a&&a.enter()},!BP&&!zo&&!_P&&Lf&&Mf?(Ko=!0,Jo=Mf.createTextNode(""),new Lf(Vi).observe(Jo,{characterData:!0}),Ur=function(){Jo.data=Ko=!Ko}):!VP&&As&&As.resolve?(ws=As.resolve(void 0),ws.constructor=As,Df=$f(ws.then,ws),Ur=function(){Df(Vi)}):zo?Ur=function(){Cf.nextTick(Vi)}:(Yo=$f(Yo,Hr),Ur=function(){Yo(Vi)}),Xo=function(a){Bi.head||Ur(),Bi.add(a)});var Bi,Vi;Of.exports=Xo});var _f=b((FM,Vf)=>{"use strict";Vf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ks=b((qM,Nf)=>{"use strict";Nf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var fr=b((UM,Ff)=>{"use strict";var NP=he();Ff.exports=NP.Promise});var jr=b((HM,jf)=>{"use strict";var FP=he(),_i=fr(),qP=pe(),UP=zn(),HP=Co(),jP=Ae(),qf=Lo(),GP=it(),Zo=Bn(),Uf=_i&&_i.prototype,QP=jP("species"),eu=!1,Hf=qP(FP.PromiseRejectionEvent),WP=UP("Promise",function(){var a=HP(_i),e=a!==String(_i);if(!e&&Zo===66||GP&&!(Uf.catch&&Uf.finally))return!0;if(!Zo||Zo<51||!/native code/.test(a)){var t=new _i(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[QP]=r,eu=t.then(function(){})instanceof r,!eu)return!0}return!e&&(qf==="BROWSER"||qf==="DENO")&&!Hf});jf.exports={CONSTRUCTOR:WP,REJECTION_EVENT:Hf,SUBCLASSING:eu}});var Gr=b((jM,Qf)=>{"use strict";var Gf=dt(),YP=TypeError,zP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new YP("Bad Promise constructor");e=r,t=i}),this.resolve=Gf(e),this.reject=Gf(t)};Qf.exports.f=function(a){return new zP(a)}});var dm=b(()=>{"use strict";var KP=fe(),JP=it(),Ms=Ps(),Qt=he(),zr=Ne(),Wf=qr(),Yf=Po(),XP=Ri(),ZP=Wh(),eA=dt(),Ls=pe(),tA=Fe(),rA=zh(),iA=Bo(),Zf=Qo().set,su=Bf(),aA=_f(),sA=ks(),nA=Wo(),em=po(),Cs=fr(),nu=jr(),tm=Gr(),Ds="Promise",rm=nu.CONSTRUCTOR,oA=nu.REJECTION_EVENT,uA=nu.SUBCLASSING,tu=em.getterFor(Ds),lA=em.set,Qr=Cs&&Cs.prototype,mr=Cs,Rs=Qr,im=Qt.TypeError,ru=Qt.document,ou=Qt.process,iu=tm.f,cA=iu,dA=!!(ru&&ru.createEvent&&Qt.dispatchEvent),am="unhandledrejection",pA="rejectionhandled",zf=0,sm=1,hA=2,uu=1,nm=2,$s,Kf,fA,Jf,om=function(a){var e;return tA(a)&&Ls(e=a.then)?e:!1},um=function(a,e){var t=e.value,r=e.state===sm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{i?(r||(e.rejection===nm&&bA(e),e.rejection=uu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),d=!0)),u===a.promise?n(new im("Promise-chain cycle")):(l=om(u))?zr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},lm=function(a,e){a.notified||(a.notified=!0,su(function(){for(var t=a.reactions,r;r=t.get();)um(r,a);a.notified=!1,e&&!a.rejection&&mA(a)}))},cm=function(a,e,t){var r,i;dA?(r=ru.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Qt.dispatchEvent(r)):r={promise:e,reason:t},!oA&&(i=Qt["on"+a])?i(r):a===am&&aA("Unhandled promise rejection",t)},mA=function(a){zr(Zf,Qt,function(){var e=a.facade,t=a.value,r=Xf(a),i;if(r&&(i=sA(function(){Ms?ou.emit("unhandledRejection",t,e):cm(am,e,t)}),a.rejection=Ms||Xf(a)?nm:uu,i.error))throw i.value})},Xf=function(a){return a.rejection!==uu&&!a.parent},bA=function(a){zr(Zf,Qt,function(){var e=a.facade;Ms?ou.emit("rejectionHandled",e):cm(pA,e,a.value)})},Wr=function(a,e,t){return function(r){a(e,r,t)}},Yr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=hA,lm(a,!0))},au=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new im("Promise can't be resolved itself");var r=om(e);r?su(function(){var i={done:!1};try{zr(r,e,Wr(au,i,a),Wr(Yr,i,a))}catch(s){Yr(i,s,a)}}):(a.value=e,a.state=sm,lm(a,!1))}catch(i){Yr({done:!1},i,a)}}};if(rm&&(mr=function(e){rA(this,Rs),eA(e),zr($s,this);var t=tu(this);try{e(Wr(au,t),Wr(Yr,t))}catch(r){Yr(t,r)}},Rs=mr.prototype,$s=function(e){lA(this,{type:Ds,done:!1,notified:!1,parent:!1,reactions:new nA,rejection:!1,state:zf,value:void 0})},$s.prototype=Wf(Rs,"then",function(e,t){var r=tu(this),i=iu(iA(this,mr));return r.parent=!0,i.ok=Ls(e)?e:!0,i.fail=Ls(t)&&t,i.domain=Ms?ou.domain:void 0,r.state===zf?r.reactions.add(i):su(function(){um(i,r)}),i.promise}),Kf=function(){var a=new $s,e=tu(a);this.promise=a,this.resolve=Wr(au,e),this.reject=Wr(Yr,e)},tm.f=iu=function(a){return a===mr||a===fA?new Kf(a):cA(a)},!JP&&Ls(Cs)&&Qr!==Object.prototype)){Jf=Qr.then,uA||Wf(Qr,"then",function(e,t){var r=this;return new mr(function(i,s){zr(Jf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Qr.constructor}catch(a){}Yf&&Yf(Qr,Rs)}KP({global:!0,constructor:!0,wrap:!0,forced:rm},{Promise:mr});XP(mr,Ds,!1,!0);ZP(Ds)});var bm=b((WM,mm)=>{"use strict";var gA=Ae(),hm=gA("iterator"),fm=!1;try{pm=0,lu={next:function(){return{done:!!pm++}},return:function(){fm=!0}},lu[hm]=function(){return this},Array.from(lu,function(){throw 2})}catch(a){}var pm,lu;mm.exports=function(a,e){try{if(!e&&!fm)return!1}catch(i){return!1}var t=!1;try{var r={};r[hm]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var cu=b((YM,gm)=>{"use strict";var vA=fr(),SA=bm(),yA=jr().CONSTRUCTOR;gm.exports=yA||!SA(function(a){vA.all(a).then(void 0,function(){})})});var vm=b(()=>{"use strict";var TA=fe(),IA=Ne(),EA=dt(),xA=Gr(),PA=ks(),AA=Is(),wA=cu();TA({target:"Promise",stat:!0,forced:wA},{all:function(e){var t=this,r=xA.f(t),i=r.resolve,s=r.reject,n=PA(function(){var o=EA(t.resolve),u=[],l=0,d=1;AA(e,function(c){var p=l++,h=!1;d++,IA(o,t,c).then(function(m){h||(h=!0,u[p]=m,--d||i(u))},s)}),--d||i(u)});return n.error&&s(n.value),r.promise}})});var ym=b(()=>{"use strict";var kA=fe(),RA=it(),$A=jr().CONSTRUCTOR,pu=fr(),LA=It(),MA=pe(),CA=qr(),Sm=pu&&pu.prototype;kA({target:"Promise",proto:!0,forced:$A,real:!0},{catch:function(a){return this.then(void 0,a)}});!RA&&MA(pu)&&(du=LA("Promise").prototype.catch,Sm.catch!==du&&CA(Sm,"catch",du,{unsafe:!0}));var du});var Tm=b(()=>{"use strict";var DA=fe(),OA=Ne(),BA=dt(),VA=Gr(),_A=ks(),NA=Is(),FA=cu();DA({target:"Promise",stat:!0,forced:FA},{race:function(e){var t=this,r=VA.f(t),i=r.reject,s=_A(function(){var n=BA(t.resolve);NA(e,function(o){OA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Im=b(()=>{"use strict";var qA=fe(),UA=Gr(),HA=jr().CONSTRUCTOR;qA({target:"Promise",stat:!0,forced:HA},{reject:function(e){var t=UA.f(this),r=t.reject;return r(e),t.promise}})});var hu=b((iC,Em)=>{"use strict";var jA=pt(),GA=Fe(),QA=Gr();Em.exports=function(a,e){if(jA(a),GA(e)&&e.constructor===a)return e;var t=QA.f(a),r=t.resolve;return r(e),t.promise}});var Am=b(()=>{"use strict";var WA=fe(),YA=It(),xm=it(),zA=fr(),Pm=jr().CONSTRUCTOR,KA=hu(),JA=YA("Promise"),XA=xm&&!Pm;WA({target:"Promise",stat:!0,forced:xm||Pm},{resolve:function(e){return KA(XA&&this===JA?zA:this,e)}})});var wm=b(()=>{"use strict";dm();vm();ym();Tm();Im();Am()});var Lm=b(()=>{"use strict";var ZA=fe(),ew=it(),Os=fr(),tw=Pe(),Rm=It(),$m=pe(),rw=Bo(),km=hu(),iw=qr(),mu=Os&&Os.prototype,aw=!!Os&&tw(function(){mu.finally.call({then:function(){}},function(){})});ZA({target:"Promise",proto:!0,real:!0,forced:aw},{finally:function(a){var e=rw(this,Rm("Promise")),t=$m(a);return this.then(t?function(r){return km(e,a()).then(function(){return r})}:a,t?function(r){return km(e,a()).then(function(){throw r})}:a)}});!ew&&$m(Os)&&(fu=Rm("Promise").prototype.finally,mu.finally!==fu&&iw(mu,"finally",fu,{unsafe:!0}));var fu});var Cm=b((cC,Mm)=>{"use strict";Fh();wm();Lm();var sw=Gt();Mm.exports=sw("Promise","finally")});var Om=b((dC,Dm)=>{"use strict";var nw=Cm();Dm.exports=nw});var Bs=b((pC,Bm)=>{"use strict";var ow=Om();Bm.exports=ow});var Hm=b(()=>{"use strict";var pw=fe(),hw=oo().values;pw({target:"Object",stat:!0},{values:function(e){return hw(e)}})});var Gm=b((HC,jm)=>{"use strict";Hm();var fw=Mr();jm.exports=fw.Object.values});var Wm=b((jC,Qm)=>{"use strict";var mw=Gm();Qm.exports=mw});var Fi=b((GC,Ym)=>{"use strict";var bw=Wm();Ym.exports=bw});var Xm=b(()=>{"use strict";var yw=fe(),Tw=Cr(),Iw=Nr(),Ew=Pi(),xw=Ai();yw({target:"Array",proto:!0},{at:function(e){var t=Tw(this),r=Iw(t),i=Ew(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});xw("at")});var eb=b((m0,Zm)=>{"use strict";Xm();var Pw=Gt();Zm.exports=Pw("Array","at")});var rb=b((b0,tb)=>{"use strict";var Aw=eb();tb.exports=Aw});var Kr=b((g0,ib)=>{"use strict";var ww=rb();ib.exports=ww});var Mu=b((_D,Eb)=>{"use strict";var _w=or();Eb.exports=Array.isArray||function(e){return _w(e)==="Array"}});var Pb=b((ND,xb)=>{"use strict";var Nw=TypeError,Fw=9007199254740991;xb.exports=function(a){if(a>Fw)throw Nw("Maximum allowed index exceeded");return a}});var kb=b((FD,wb)=>{"use strict";var qw=Mu(),Uw=Nr(),Hw=Pb(),jw=Or(),Ab=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,d=n?jw(n,o):!1,c,p;l<r;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&qw(c)?(p=Uw(c),u=Ab(a,e,c,p,u,s-1)-1):(Hw(u+1),a[u]=c),u++),l++;return u};wb.exports=Ab});var Mb=b((qD,Lb)=>{"use strict";var Rb=Mu(),Gw=Oo(),Qw=Fe(),Ww=Ae(),Yw=Ww("species"),$b=Array;Lb.exports=function(a){var e;return Rb(a)&&(e=a.constructor,Gw(e)&&(e===$b||Rb(e.prototype))?e=void 0:Qw(e)&&(e=e[Yw],e===null&&(e=void 0))),e===void 0?$b:e}});var Db=b((UD,Cb)=>{"use strict";var zw=Mb();Cb.exports=function(a,e){return new(zw(a))(e===0?0:e)}});var Ob=b(()=>{"use strict";var Kw=fe(),Jw=kb(),Xw=dt(),Zw=Cr(),ek=Nr(),tk=Db();Kw({target:"Array",proto:!0},{flatMap:function(e){var t=Zw(this),r=ek(t),i;return Xw(e),i=tk(t,0),i.length=Jw(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Bb=b(()=>{"use strict";var rk=Ai();rk("flatMap")});var _b=b((WD,Vb)=>{"use strict";Ob();Bb();var ik=Gt();Vb.exports=ik("Array","flatMap")});var Fb=b((YD,Nb)=>{"use strict";var ak=_b();Nb.exports=ak});var Cu=b((zD,qb)=>{"use strict";var sk=Fb();qb.exports=sk});var Ji=b((sO,og)=>{"use strict";var hk=ki(),fk=String;og.exports=function(a){if(hk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return fk(a)}});var Ou=b((nO,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((oO,cg)=>{"use strict";var mk=ve(),bk=jt(),gk=Ji(),Vu=Ou(),lg=mk("".replace),vk=RegExp("^["+Vu+"]+"),Sk=RegExp("(^|[^"+Vu+"])["+Vu+"]+$"),Bu=function(a){return function(e){var t=gk(bk(e));return a&1&&(t=lg(t,vk,"")),a&2&&(t=lg(t,Sk,"$1")),t}};cg.exports={start:Bu(1),end:Bu(2),trim:Bu(3)}});var mg=b((uO,fg)=>{"use strict";var yk=mo().PROPER,Tk=Pe(),pg=Ou(),hg="\u200B\x85\u180E";fg.exports=function(a){return Tk(function(){return!!pg[a]()||hg[a]()!==hg||yk&&pg[a].name!==a})}});var _u=b((lO,bg)=>{"use strict";var Ik=dg().start,Ek=mg();bg.exports=Ek("trimStart")?function(){return Ik(this)}:"".trimStart});var vg=b(()=>{"use strict";var xk=fe(),gg=_u();xk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==gg},{trimLeft:gg})});var yg=b(()=>{"use strict";vg();var Pk=fe(),Sg=_u();Pk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Sg},{trimStart:Sg})});var Ig=b((fO,Tg)=>{"use strict";yg();var Ak=Gt();Tg.exports=Ak("String","trimLeft")});var xg=b((mO,Eg)=>{"use strict";var wk=Ig();Eg.exports=wk});var Ag=b((bO,Pg)=>{"use strict";var kk=xg();Pg.exports=kk});var Fg=b(()=>{"use strict"});var qg=b(()=>{"use strict"});var Hg=b((NV,Ug)=>{"use strict";var Yk=Fe(),zk=or(),Kk=Ae(),Jk=Kk("match");Ug.exports=function(a){var e;return Yk(a)&&((e=a[Jk])!==void 0?!!e:zk(a)==="RegExp")}});var Gg=b((FV,jg)=>{"use strict";var Xk=pt();jg.exports=function(){var a=Xk(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((qV,Wg)=>{"use strict";var Zk=Ne(),eR=at(),tR=Si(),rR=Gg(),Qg=RegExp.prototype;Wg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Qg)&&!eR(a,"flags")&&tR(Qg,a)?Zk(rR,a):e}});var Kg=b((UV,zg)=>{"use strict";var Gu=ve(),iR=Cr(),aR=Math.floor,Hu=Gu("".charAt),sR=Gu("".replace),ju=Gu("".slice),nR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,oR=/\$([$&'`]|\d{1,2})/g;zg.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,d){var c;switch(Hu(d,0)){case"$":return"$";case"&":return a;case"`":return ju(e,0,t);case"'":return ju(e,n);case"<":c=i[ju(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=aR(p/10);return h===0?l:h<=o?r[h-1]===void 0?Hu(d,1):r[h-1]+Hu(d,1):l}c=r[p-1]}return c===void 0?"":c})}});var Zg=b(()=>{"use strict";var uR=fe(),lR=Ne(),Wu=ve(),Jg=jt(),cR=pe(),dR=Lr(),pR=Hg(),ii=Ji(),hR=Ti(),fR=Yg(),mR=Kg(),bR=Ae(),gR=it(),vR=bR("replace"),SR=TypeError,Qu=Wu("".indexOf),yR=Wu("".replace),Xg=Wu("".slice),TR=Math.max;uR({target:"String",proto:!0},{replaceAll:function(e,t){var r=Jg(this),i,s,n,o,u,l,d,c,p,h,m=0,g="";if(!dR(e)){if(i=pR(e),i&&(s=ii(Jg(fR(e))),!~Qu(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(ii(r),e,t)}for(o=ii(r),u=ii(e),l=cR(t),l||(t=ii(t)),d=u.length,c=TR(1,d),p=Qu(o,u);p!==-1;)h=l?ii(t(u,p,o)):mR(u,o,p,[],void 0,t),g+=Xg(o,m,p)+h,m=p+d,p=p+c>o.length?-1:Qu(o,u,p+c);return m<o.length&&(g+=Xg(o,m)),g}})});var tv=b((GV,ev)=>{"use strict";Fg();qg();Zg();var IR=Gt();ev.exports=IR("String","replaceAll")});var iv=b((QV,rv)=>{"use strict";var ER=tv();rv.exports=ER});var sv=b((WV,av)=>{"use strict";var xR=iv();av.exports=xR});var ov=b((YV,nv)=>{"use strict";var PR=Pi(),AR=Ji(),wR=jt(),kR=RangeError;nv.exports=function(e){var t=AR(wR(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 pv=b((zV,dv)=>{"use strict";var cv=ve(),RR=to(),uv=Ji(),$R=ov(),LR=jt(),MR=cv($R),CR=cv("".slice),DR=Math.ceil,lv=function(a){return function(e,t,r){var i=uv(LR(e)),s=RR(t),n=i.length,o=r===void 0?" ":uv(r),u,l;return s<=n||o===""?i:(u=s-n,l=MR(o,DR(u/o.length)),l.length>u&&(l=CR(l,0,u)),a?i+l:l+i)}};dv.exports={start:lv(!1),end:lv(!0)}});var fv=b((KV,hv)=>{"use strict";var OR=lr();hv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(OR)});var mv=b(()=>{"use strict";var BR=fe(),VR=pv().start,_R=fv();BR({target:"String",proto:!0,forced:_R},{padStart:function(e){return VR(this,e,arguments.length>1?arguments[1]:void 0)}})});var gv=b((ZV,bv)=>{"use strict";mv();var NR=Gt();bv.exports=NR("String","padStart")});var Sv=b((e_,vv)=>{"use strict";var FR=gv();vv.exports=FR});var Tv=b((t_,yv)=>{"use strict";var qR=Sv();yv.exports=qR});var s$={};LS(s$,{ChromecastState:()=>mi,HttpConnectionType:()=>rs,Observable:()=>St.Observable,PlaybackState:()=>Re,Player:()=>qa,SDK_VERSION:()=>a$,Subject:()=>St.Subject,Subscription:()=>St.Subscription,Surface:()=>is,VERSION:()=>Pn,ValueSubject:()=>St.ValueSubject,VideoFormat:()=>Tt,VideoQuality:()=>St.VideoQuality});module.exports=MS(s$);var Pn="2.0.118";var Re=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Re||{}),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 mi=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(mi||{}),rs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(rs||{});var is=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(is||{});var pS=X(ht(),1);var q=require("@vkontakte/videoplayer-shared/es2015");var Ud=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var us=class{constructor(e){this.connection$=new q.ValueSubject(void 0);this.castState$=new q.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new q.Subject;this.realCastState$=new q.ValueSubject("NOT_AVAILABLE");this.subscription=new q.Subscription;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,q.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Ud("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:q.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,q.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,q.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,q.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,q.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,q.assertNever)(i.sessionState)}})).add((0,q.merge)((0,q.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,q.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,q.map)(i=>i.castState)),(0,q.observableFrom)([r.getCastState()])).pipe((0,q.filterChanged)(),(0,q.map)(eI),(0,q.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,q.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,q.assertNonNullable)(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,q.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,q.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:q.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},eI=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,q.assertNever)(a)}};var cl=X(ht(),1),Zv=X(Fr(),1),eS=X($o(),1);var Fm=X(Bs(),1);var bu=require("@vkontakte/videoplayer-shared/es2015");var we=(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,bu.assertNever)(t)}return a},Vs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,bu.assertNever)(e)}};var k=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var ft=require("@vkontakte/videoplayer-shared/es2015"),j=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 Vm=require("@vkontakte/videoplayer-shared/es2015"),_m=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,Vm.assertNever)(a)}};var L=require("@vkontakte/videoplayer-shared/es2015");var uw=5,lw=5,cw=500,Nm=7e3,Ni=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new j("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(_m(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)(cw)).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)>uw)&&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<lw&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let d=t[e];(0,L.assertNonNullable)(d);let c=(0,L.getHighestQuality)(Object.keys(d));(0,L.assertNonNullable)(c);let p=d[c];(0,L.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];(0,L.assertNonNullable)(d),r=d.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];(0,L.assertNonNullable)(d),r=d.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];(0,L.assertNonNullable)(d),r=d.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];(0,L.assertNonNullable)(d),r=we(d.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:c}),c}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)(Nm).subscribe(()=>s(`timeout(${Nm})`)))});(0,Fm.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 $u=X(ht(),1);var yu=require("@vkontakte/videoplayer-shared/es2015");var qm=require("@vkontakte/videoplayer-shared/es2015"),Um=a=>{try{a.pause(),a.playbackRate=0,(0,qm.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var _s=require("@vkontakte/videoplayer-shared/es2015"),gu=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)}},vu=window.WeakMap?new WeakMap:new gu,Su=window.WeakMap?new WeakMap:new Map,dw=(a,e=20)=>{let t=0;return(0,_s.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Le=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,yu.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),vu.set(t,r);let i=new _s.Subscription;return i.add(dw(t,e)),Su.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Me=a=>{let e=Su.get(a);e==null||e.unsubscribe(),Su.delete(a);let t=vu.get(a);vu.delete(a),t?(0,yu.clearVideoElement)(a):Um(a)};var Tu=X(Fi(),1),M=require("@vkontakte/videoplayer-shared/es2015");var Wt=require("@vkontakte/videoplayer-shared/es2015"),Ns=(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(d=>{let c=a.getState();r(d,c)&&a.setState(d)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},mt=(a,e,t)=>Ns(e,()=>a.loop,r=>{(0,Wt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Ce=(a,e,t,r)=>Ns(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}),Ye=(a,e,t,r)=>Ns(e,()=>a.playbackRate,i=>{(0,Wt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Yt=Ns;var gw=a=>["__",a.language,a.label].join("|"),vw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Iu=class a{constructor(){this.available$=new M.Subject;this.current$=new M.ValueSubject(void 0);this.error$=new M.Subject;this.subscription=new M.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:M.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,Tu.default)(this.internalTracks),s=>{(0,M.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,M.isNonNullable)(s)&&(0,M.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,M.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Yt(t.externalTextTracks,()=>(0,Tu.default)(this.externalTracks),s=>{(0,M.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,M.isNonNullable)(s)&&(0,M.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,M.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,M.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,M.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,M.merge)((0,M.fromEvent)(e,"addtrack"),(0,M.fromEvent)(e,"removetrack"),(0,M.observableFrom)(["init"])).pipe((0,M.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,M.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,M.merge)((0,M.fromEvent)(e,"change"),(0,M.observableFrom)(["init"])).pipe((0,M.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,M.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,M.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,M.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,d,c,p,h;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,M.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,M.isNonNullable)(t.align)&&(i.align=t.align),(0,M.isNonNullable)(t.position)&&(i.position=t.position),(0,M.isNonNullable)(t.size)&&(i.size=t.size),(0,M.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,M.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:r}=e,i=e.id?e.id:gw(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(d=this.externalTracks.get(i))==null?void 0:d.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(c=this.internalTracks.get(i))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,M.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,M.isNullable)(e)||!vw(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,M.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,M.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)}},ze=Iu;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 zm=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},Eu=a=>{let e=zm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Km=a=>{let e=zm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared/es2015");var Sw=3,Jm=(a,e,t=Sw)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var De=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)(()=>Jm(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 A;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:(A=a.error)!=null?A:void 0}})),l=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(()=>a.currentTime)),d=new D.Subject,c=.3,p;l.subscribe(x=>{a.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(x)&&p>=a.duration-c&&x<=c&&d.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(Km(a));m.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let I=new D.ValueSubject(Eu(a));return(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.map)(()=>Eu(a))).subscribe(I),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,D.fromEvent)(a,"durationchange").pipe((0,D.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:I}};var At=require("@vkontakte/videoplayer-shared/es2015"),zt=a=>{switch(a){case"mobile":return At.VideoQuality.Q_144P;case"lowest":return At.VideoQuality.Q_240P;case"low":return At.VideoQuality.Q_360P;case"sd":case"medium":return At.VideoQuality.Q_480P;case"hd":case"high":return At.VideoQuality.Q_720P;case"fullhd":case"full":return At.VideoQuality.Q_1080P;case"quadhd":case"quad":return At.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return At.VideoQuality.Q_2160P}};var Kt=X(Kr(),1),ub=X(ht(),1),Fs=X(Fr(),1),C=require("@vkontakte/videoplayer-shared/es2015");var xu=!1,wt={},ab=a=>{xu=a},sb=()=>{wt={}},nb=a=>{a(wt)},qi=(a,e)=>{var t;xu&&(wt.meta=(t=wt.meta)!=null?t:{},wt.meta[a]=e)},$e=class{constructor(e){this.name=e}next(e){var r,i;if(!xu)return;wt.series=(r=wt.series)!=null?r:{};let t=(i=wt.series[this.name])!=null?i:[];t.push([Date.now(),e]),wt.series[this.name]=t}};var kw=new $e("best_bitrate"),lb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Pu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ui=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,C.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},cb='Assertion "ABR Tracks is empty array" failed',qs=(a,e,t,r)=>{var u;let i=[...e].sort(Pu(1)),s=[...t].sort(Pu(1)),n=s.filter(l=>(0,C.isNonNullable)(l.bitrate)&&(0,C.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,C.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,C.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,C.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 AS=Object.create;var mi=Object.defineProperty,wS=Object.defineProperties,kS=Object.getOwnPropertyDescriptor,RS=Object.getOwnPropertyDescriptors,$S=Object.getOwnPropertyNames,rs=Object.getOwnPropertySymbols,LS=Object.getPrototypeOf,Pn=Object.prototype.hasOwnProperty,zl=Object.prototype.propertyIsEnumerable;var MS=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var dt=Math.pow,Yl=(a,e,t)=>e in a?mi(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,R=(a,e)=>{for(var t in e||(e={}))Pn.call(e,t)&&Yl(a,t,e[t]);if(rs)for(var t of rs(e))zl.call(e,t)&&Yl(a,t,e[t]);return a},H=(a,e)=>wS(a,RS(e));var Kl=(a,e)=>{var t={};for(var r in a)Pn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&rs)for(var r of rs(a))e.indexOf(r)<0&&zl.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),CS=(a,e)=>{for(var t in e)mi(a,t,{get:e[t],enumerable:!0})},Jl=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of $S(e))!Pn.call(a,i)&&i!==t&&mi(a,i,{get:()=>e[i],enumerable:!(r=kS(e,i))||r.enumerable});return a};var X=(a,e,t)=>(t=a!=null?AS(LS(a)):{},Jl(e||!a||!a.__esModule?mi(t,"default",{value:a,enumerable:!0}):t,a)),DS=a=>Jl(mi({},"__esModule",{value:!0}),a);var O=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),An=function(a,e){this[0]=a,this[1]=e},me=(a,e,t)=>{var r=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof An,p=d.done;Promise.resolve(c?o[0]:o).then(h=>c?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[MS("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var he=b((kn,Xl)=>{"use strict";var gi=function(a){return a&&a.Math===Math&&a};Xl.exports=gi(typeof globalThis=="object"&&globalThis)||gi(typeof window=="object"&&window)||gi(typeof self=="object"&&self)||gi(typeof global=="object"&&global)||gi(typeof kn=="object"&&kn)||function(){return this}()||Function("return this")()});var Pe=b((d$,Zl)=>{"use strict";Zl.exports=function(a){try{return!!a()}catch(e){return!0}}});var vi=b((p$,ec)=>{"use strict";var OS=Pe();ec.exports=!OS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Rn=b((h$,ac)=>{"use strict";var VS=vi(),ic=Function.prototype,tc=ic.apply,rc=ic.call;ac.exports=typeof Reflect=="object"&&Reflect.apply||(VS?rc.bind(tc):function(){return rc.apply(tc,arguments)})});var ve=b((f$,oc)=>{"use strict";var sc=vi(),nc=Function.prototype,$n=nc.call,BS=sc&&nc.bind.bind($n,$n);oc.exports=sc?BS:function(a){return function(){return $n.apply(a,arguments)}}});var ur=b((m$,lc)=>{"use strict";var uc=ve(),_S=uc({}.toString),NS=uc("".slice);lc.exports=function(a){return NS(_S(a),8,-1)}});var Ln=b((b$,cc)=>{"use strict";var FS=ur(),qS=ve();cc.exports=function(a){if(FS(a)==="Function")return qS(a)}});var pe=b((g$,dc)=>{"use strict";var Mn=typeof document=="object"&&document.all;dc.exports=typeof Mn=="undefined"&&Mn!==void 0?function(a){return typeof a=="function"||a===Mn}:function(a){return typeof a=="function"}});var Ne=b((v$,pc)=>{"use strict";var US=Pe();pc.exports=!US(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Fe=b((S$,hc)=>{"use strict";var HS=vi(),ss=Function.prototype.call;hc.exports=HS?ss.bind(ss):function(){return ss.apply(ss,arguments)}});var Cn=b(bc=>{"use strict";var fc={}.propertyIsEnumerable,mc=Object.getOwnPropertyDescriptor,jS=mc&&!fc.call({1:2},1);bc.f=jS?function(e){var t=mc(this,e);return!!t&&t.enumerable}:fc});var Si=b((T$,gc)=>{"use strict";gc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Sc=b((I$,vc)=>{"use strict";var GS=ve(),QS=Pe(),WS=ur(),Dn=Object,YS=GS("".split);vc.exports=QS(function(){return!Dn("z").propertyIsEnumerable(0)})?function(a){return WS(a)==="String"?YS(a,""):Dn(a)}:Dn});var Mr=b((E$,yc)=>{"use strict";yc.exports=function(a){return a==null}});var Gt=b((x$,Tc)=>{"use strict";var zS=Mr(),KS=TypeError;Tc.exports=function(a){if(zS(a))throw new KS("Can't call method on "+a);return a}});var lr=b((P$,Ic)=>{"use strict";var JS=Sc(),XS=Gt();Ic.exports=function(a){return JS(XS(a))}});var qe=b((A$,Ec)=>{"use strict";var ZS=pe();Ec.exports=function(a){return typeof a=="object"?a!==null:ZS(a)}});var Cr=b((w$,xc)=>{"use strict";xc.exports={}});var Et=b((k$,Ac)=>{"use strict";var On=Cr(),Vn=he(),ey=pe(),Pc=function(a){return ey(a)?a:void 0};Ac.exports=function(a,e){return arguments.length<2?Pc(On[a])||Pc(Vn[a]):On[a]&&On[a][e]||Vn[a]&&Vn[a][e]}});var yi=b((R$,wc)=>{"use strict";var ty=ve();wc.exports=ty({}.isPrototypeOf)});var cr=b(($$,$c)=>{"use strict";var ry=he(),kc=ry.navigator,Rc=kc&&kc.userAgent;$c.exports=Rc?String(Rc):""});var _n=b((L$,Vc)=>{"use strict";var Oc=he(),Bn=cr(),Lc=Oc.process,Mc=Oc.Deno,Cc=Lc&&Lc.versions||Mc&&Mc.version,Dc=Cc&&Cc.v8,it,ns;Dc&&(it=Dc.split("."),ns=it[0]>0&&it[0]<4?1:+(it[0]+it[1]));!ns&&Bn&&(it=Bn.match(/Edge\/(\d+)/),(!it||it[1]>=74)&&(it=Bn.match(/Chrome\/(\d+)/),it&&(ns=+it[1])));Vc.exports=ns});var Nn=b((M$,_c)=>{"use strict";var Bc=_n(),iy=Pe(),ay=he(),sy=ay.String;_c.exports=!!Object.getOwnPropertySymbols&&!iy(function(){var a=Symbol("symbol detection");return!sy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Bc&&Bc<41})});var Fn=b((C$,Nc)=>{"use strict";var ny=Nn();Nc.exports=ny&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var qn=b((D$,Fc)=>{"use strict";var oy=Et(),uy=pe(),ly=yi(),cy=Fn(),dy=Object;Fc.exports=cy?function(a){return typeof a=="symbol"}:function(a){var e=oy("Symbol");return uy(e)&&ly(e.prototype,dy(a))}});var Ti=b((O$,qc)=>{"use strict";var py=String;qc.exports=function(a){try{return py(a)}catch(e){return"Object"}}});var pt=b((V$,Uc)=>{"use strict";var hy=pe(),fy=Ti(),my=TypeError;Uc.exports=function(a){if(hy(a))return a;throw new my(fy(a)+" is not a function")}});var Ii=b((B$,Hc)=>{"use strict";var by=pt(),gy=Mr();Hc.exports=function(a,e){var t=a[e];return gy(t)?void 0:by(t)}});var Gc=b((_$,jc)=>{"use strict";var Un=Fe(),Hn=pe(),jn=qe(),vy=TypeError;jc.exports=function(a,e){var t,r;if(e==="string"&&Hn(t=a.toString)&&!jn(r=Un(t,a))||Hn(t=a.valueOf)&&!jn(r=Un(t,a))||e!=="string"&&Hn(t=a.toString)&&!jn(r=Un(t,a)))return r;throw new vy("Can't convert object to primitive value")}});var at=b((N$,Qc)=>{"use strict";Qc.exports=!0});var zc=b((F$,Yc)=>{"use strict";var Wc=he(),Sy=Object.defineProperty;Yc.exports=function(a,e){try{Sy(Wc,a,{value:e,configurable:!0,writable:!0})}catch(t){Wc[a]=e}return e}});var Ei=b((q$,Xc)=>{"use strict";var yy=at(),Ty=he(),Iy=zc(),Kc="__core-js_shared__",Jc=Xc.exports=Ty[Kc]||Iy(Kc,{});(Jc.versions||(Jc.versions=[])).push({version:"3.38.0",mode:yy?"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((U$,ed)=>{"use strict";var Zc=Ei();ed.exports=function(a,e){return Zc[a]||(Zc[a]=e||{})}});var Dr=b((H$,td)=>{"use strict";var Ey=Gt(),xy=Object;td.exports=function(a){return xy(Ey(a))}});var st=b((j$,rd)=>{"use strict";var Py=ve(),Ay=Dr(),wy=Py({}.hasOwnProperty);rd.exports=Object.hasOwn||function(e,t){return wy(Ay(e),t)}});var Qn=b((G$,id)=>{"use strict";var ky=ve(),Ry=0,$y=Math.random(),Ly=ky(1 .toString);id.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Ly(++Ry+$y,36)}});var Ae=b((Q$,sd)=>{"use strict";var My=he(),Cy=Gn(),ad=st(),Dy=Qn(),Oy=Nn(),Vy=Fn(),Or=My.Symbol,Wn=Cy("wks"),By=Vy?Or.for||Or:Or&&Or.withoutSetter||Dy;sd.exports=function(a){return ad(Wn,a)||(Wn[a]=Oy&&ad(Or,a)?Or[a]:By("Symbol."+a)),Wn[a]}});var ld=b((W$,ud)=>{"use strict";var _y=Fe(),nd=qe(),od=qn(),Ny=Ii(),Fy=Gc(),qy=Ae(),Uy=TypeError,Hy=qy("toPrimitive");ud.exports=function(a,e){if(!nd(a)||od(a))return a;var t=Ny(a,Hy),r;if(t){if(e===void 0&&(e="default"),r=_y(t,a,e),!nd(r)||od(r))return r;throw new Uy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Fy(a,e)}});var Yn=b((Y$,cd)=>{"use strict";var jy=ld(),Gy=qn();cd.exports=function(a){var e=jy(a,"string");return Gy(e)?e:e+""}});var os=b((z$,pd)=>{"use strict";var Qy=he(),dd=qe(),zn=Qy.document,Wy=dd(zn)&&dd(zn.createElement);pd.exports=function(a){return Wy?zn.createElement(a):{}}});var Kn=b((K$,hd)=>{"use strict";var Yy=Ne(),zy=Pe(),Ky=os();hd.exports=!Yy&&!zy(function(){return Object.defineProperty(Ky("div"),"a",{get:function(){return 7}}).a!==7})});var bd=b(md=>{"use strict";var Jy=Ne(),Xy=Fe(),Zy=Cn(),eT=Si(),tT=lr(),rT=Yn(),iT=st(),aT=Kn(),fd=Object.getOwnPropertyDescriptor;md.f=Jy?fd:function(e,t){if(e=tT(e),t=rT(t),aT)try{return fd(e,t)}catch(r){}if(iT(e,t))return eT(!Xy(Zy.f,e,t),e[t])}});var Jn=b((X$,gd)=>{"use strict";var sT=Pe(),nT=pe(),oT=/#|\.prototype\./,xi=function(a,e){var t=lT[uT(a)];return t===dT?!0:t===cT?!1:nT(e)?sT(e):!!e},uT=xi.normalize=function(a){return String(a).replace(oT,".").toLowerCase()},lT=xi.data={},cT=xi.NATIVE="N",dT=xi.POLYFILL="P";gd.exports=xi});var Vr=b((Z$,Sd)=>{"use strict";var vd=Ln(),pT=pt(),hT=vi(),fT=vd(vd.bind);Sd.exports=function(a,e){return pT(a),e===void 0?a:hT?fT(a,e):function(){return a.apply(e,arguments)}}});var Xn=b((eL,yd)=>{"use strict";var mT=Ne(),bT=Pe();yd.exports=mT&&bT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ht=b((tL,Td)=>{"use strict";var gT=qe(),vT=String,ST=TypeError;Td.exports=function(a){if(gT(a))return a;throw new ST(vT(a)+" is not an object")}});var dr=b(Ed=>{"use strict";var yT=Ne(),TT=Kn(),IT=Xn(),us=ht(),Id=Yn(),ET=TypeError,Zn=Object.defineProperty,xT=Object.getOwnPropertyDescriptor,eo="enumerable",to="configurable",ro="writable";Ed.f=yT?IT?function(e,t,r){if(us(e),t=Id(t),us(r),typeof e=="function"&&t==="prototype"&&"value"in r&&ro in r&&!r[ro]){var i=xT(e,t);i&&i[ro]&&(e[t]=r.value,r={configurable:to in r?r[to]:i[to],enumerable:eo in r?r[eo]:i[eo],writable:!1})}return Zn(e,t,r)}:Zn:function(e,t,r){if(us(e),t=Id(t),us(r),TT)try{return Zn(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new ET("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Br=b((iL,xd)=>{"use strict";var PT=Ne(),AT=dr(),wT=Si();xd.exports=PT?function(a,e,t){return AT.f(a,e,wT(1,t))}:function(a,e,t){return a[e]=t,a}});var fe=b((aL,Ad)=>{"use strict";var Pi=he(),kT=Rn(),RT=Ln(),$T=pe(),LT=bd().f,MT=Jn(),_r=Cr(),CT=Vr(),Nr=Br(),Pd=st();Ei();var DT=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 kT(a,this,arguments)};return e.prototype=a.prototype,e};Ad.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Pi:i?Pi[t]:Pi[t]&&Pi[t].prototype,o=r?_r:_r[t]||Nr(_r,t,{})[t],u=o.prototype,l,d,c,p,h,m,g,v,I;for(p in e)l=MT(r?p:t+(i?".":"#")+p,a.forced),d=!l&&n&&Pd(n,p),m=o[p],d&&(a.dontCallGetSet?(I=LT(n,p),g=I&&I.value):g=n[p]),h=d&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&d?v=CT(h,Pi):a.wrap&&d?v=DT(h):s&&$T(h)?v=RT(h):v=h,(a.sham||h&&h.sham||m&&m.sham)&&Nr(v,"sham",!0),Nr(o,p,v),s&&(c=t+"Prototype",Pd(_r,c)||Nr(_r,c,{}),Nr(_r[c],p,h),a.real&&u&&(l||!u[p])&&Nr(u,p,h)))}});var kd=b((sL,wd)=>{"use strict";var OT=Math.ceil,VT=Math.floor;wd.exports=Math.trunc||function(e){var t=+e;return(t>0?VT:OT)(t)}});var Ai=b((nL,Rd)=>{"use strict";var BT=kd();Rd.exports=function(a){var e=+a;return e!==e||e===0?0:BT(e)}});var Ld=b((oL,$d)=>{"use strict";var _T=Ai(),NT=Math.max,FT=Math.min;$d.exports=function(a,e){var t=_T(a);return t<0?NT(t+e,0):FT(t,e)}});var io=b((uL,Md)=>{"use strict";var qT=Ai(),UT=Math.min;Md.exports=function(a){var e=qT(a);return e>0?UT(e,9007199254740991):0}});var Fr=b((lL,Cd)=>{"use strict";var HT=io();Cd.exports=function(a){return HT(a.length)}});var ao=b((cL,Od)=>{"use strict";var jT=lr(),GT=Ld(),QT=Fr(),Dd=function(a){return function(e,t,r){var i=jT(e),s=QT(i);if(s===0)return!a&&-1;var n=GT(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}};Od.exports={includes:Dd(!0),indexOf:Dd(!1)}});var wi=b((dL,Vd)=>{"use strict";Vd.exports=function(){}});var Bd=b(()=>{"use strict";var WT=fe(),YT=ao().includes,zT=Pe(),KT=wi(),JT=zT(function(){return!Array(1).includes()});WT({target:"Array",proto:!0,forced:JT},{includes:function(e){return YT(this,e,arguments.length>1?arguments[1]:void 0)}});KT("includes")});var Qt=b((fL,_d)=>{"use strict";var XT=Et();_d.exports=XT});var Fd=b((mL,Nd)=>{"use strict";Bd();var ZT=Qt();Nd.exports=ZT("Array","includes")});var Ud=b((bL,qd)=>{"use strict";var eI=Fd();qd.exports=eI});var ft=b((gL,Hd)=>{"use strict";var tI=Ud();Hd.exports=tI});var cs=b((kL,Qd)=>{"use strict";var iI=Gn(),aI=Qn(),Gd=iI("keys");Qd.exports=function(a){return Gd[a]||(Gd[a]=aI(a))}});var Yd=b((RL,Wd)=>{"use strict";var sI=Pe();Wd.exports=!sI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ds=b(($L,Kd)=>{"use strict";var nI=st(),oI=pe(),uI=Dr(),lI=cs(),cI=Yd(),zd=lI("IE_PROTO"),so=Object,dI=so.prototype;Kd.exports=cI?so.getPrototypeOf:function(a){var e=uI(a);if(nI(e,zd))return e[zd];var t=e.constructor;return oI(t)&&e instanceof t?t.prototype:e instanceof so?dI:null}});var ps=b((LL,Jd)=>{"use strict";Jd.exports={}});var ep=b((ML,Zd)=>{"use strict";var pI=ve(),no=st(),hI=lr(),fI=ao().indexOf,mI=ps(),Xd=pI([].push);Zd.exports=function(a,e){var t=hI(a),r=0,i=[],s;for(s in t)!no(mI,s)&&no(t,s)&&Xd(i,s);for(;e.length>r;)no(t,s=e[r++])&&(~fI(i,s)||Xd(i,s));return i}});var oo=b((CL,tp)=>{"use strict";tp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var uo=b((DL,rp)=>{"use strict";var bI=ep(),gI=oo();rp.exports=Object.keys||function(e){return bI(e,gI)}});var lo=b((OL,op)=>{"use strict";var ap=Ne(),vI=Pe(),sp=ve(),SI=ds(),yI=uo(),TI=lr(),II=Cn().f,np=sp(II),EI=sp([].push),xI=ap&&vI(function(){var a=Object.create(null);return a[2]=2,!np(a,2)}),ip=function(a){return function(e){for(var t=TI(e),r=yI(t),i=xI&&SI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!ap||(i?u in t:np(t,u)))&&EI(o,a?[u,t[u]]:t[u]);return o}};op.exports={entries:ip(!0),values:ip(!1)}});var up=b(()=>{"use strict";var PI=fe(),AI=lo().entries;PI({target:"Object",stat:!0},{entries:function(e){return AI(e)}})});var cp=b((_L,lp)=>{"use strict";up();var wI=Cr();lp.exports=wI.Object.entries});var pp=b((NL,dp)=>{"use strict";var kI=cp();dp.exports=kI});var qr=b((FL,hp)=>{"use strict";var RI=pp();hp.exports=RI});var pr=b((qL,fp)=>{"use strict";fp.exports={}});var gp=b((UL,bp)=>{"use strict";var $I=he(),LI=pe(),mp=$I.WeakMap;bp.exports=LI(mp)&&/native code/.test(String(mp))});var fo=b((HL,yp)=>{"use strict";var MI=gp(),Sp=he(),CI=qe(),DI=Br(),co=st(),po=Ei(),OI=cs(),VI=ps(),vp="Object already initialized",ho=Sp.TypeError,BI=Sp.WeakMap,hs,ki,fs,_I=function(a){return fs(a)?ki(a):hs(a,{})},NI=function(a){return function(e){var t;if(!CI(e)||(t=ki(e)).type!==a)throw new ho("Incompatible receiver, "+a+" required");return t}};MI||po.state?(nt=po.state||(po.state=new BI),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,hs=function(a,e){if(nt.has(a))throw new ho(vp);return e.facade=a,nt.set(a,e),e},ki=function(a){return nt.get(a)||{}},fs=function(a){return nt.has(a)}):(hr=OI("state"),VI[hr]=!0,hs=function(a,e){if(co(a,hr))throw new ho(vp);return e.facade=a,DI(a,hr,e),e},ki=function(a){return co(a,hr)?a[hr]:{}},fs=function(a){return co(a,hr)});var nt,hr;yp.exports={set:hs,get:ki,has:fs,enforce:_I,getterFor:NI}});var go=b((jL,Ip)=>{"use strict";var mo=Ne(),FI=st(),Tp=Function.prototype,qI=mo&&Object.getOwnPropertyDescriptor,bo=FI(Tp,"name"),UI=bo&&function(){}.name==="something",HI=bo&&(!mo||mo&&qI(Tp,"name").configurable);Ip.exports={EXISTS:bo,PROPER:UI,CONFIGURABLE:HI}});var xp=b(Ep=>{"use strict";var jI=Ne(),GI=Xn(),QI=dr(),WI=ht(),YI=lr(),zI=uo();Ep.f=jI&&!GI?Object.defineProperties:function(e,t){WI(e);for(var r=YI(t),i=zI(t),s=i.length,n=0,o;s>n;)QI.f(e,o=i[n++],r[o]);return e}});var vo=b((QL,Pp)=>{"use strict";var KI=Et();Pp.exports=KI("document","documentElement")});var Io=b((WL,Mp)=>{"use strict";var JI=ht(),XI=xp(),Ap=oo(),ZI=ps(),eE=vo(),tE=os(),rE=cs(),wp=">",kp="<",yo="prototype",To="script",$p=rE("IE_PROTO"),So=function(){},Lp=function(a){return kp+To+wp+a+kp+"/"+To+wp},Rp=function(a){a.write(Lp("")),a.close();var e=a.parentWindow.Object;return a=null,e},iE=function(){var a=tE("iframe"),e="java"+To+":",t;return a.style.display="none",eE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Lp("document.F=Object")),t.close(),t.F},ms,bs=function(){try{ms=new ActiveXObject("htmlfile")}catch(e){}bs=typeof document!="undefined"?document.domain&&ms?Rp(ms):iE():Rp(ms);for(var a=Ap.length;a--;)delete bs[yo][Ap[a]];return bs()};ZI[$p]=!0;Mp.exports=Object.create||function(e,t){var r;return e!==null?(So[yo]=JI(e),r=new So,So[yo]=null,r[$p]=e):r=bs(),t===void 0?r:XI.f(r,t)}});var Ur=b((YL,Cp)=>{"use strict";var aE=Br();Cp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:aE(a,e,t),a}});var Ao=b((zL,Vp)=>{"use strict";var sE=Pe(),nE=pe(),oE=qe(),uE=Io(),Dp=ds(),lE=Ur(),cE=Ae(),dE=at(),Po=cE("iterator"),Op=!1,xt,Eo,xo;[].keys&&(xo=[].keys(),"next"in xo?(Eo=Dp(Dp(xo)),Eo!==Object.prototype&&(xt=Eo)):Op=!0);var pE=!oE(xt)||sE(function(){var a={};return xt[Po].call(a)!==a});pE?xt={}:dE&&(xt=uE(xt));nE(xt[Po])||lE(xt,Po,function(){return this});Vp.exports={IteratorPrototype:xt,BUGGY_SAFARI_ITERATORS:Op}});var gs=b((KL,_p)=>{"use strict";var hE=Ae(),fE=hE("toStringTag"),Bp={};Bp[fE]="z";_p.exports=String(Bp)==="[object z]"});var Ri=b((JL,Np)=>{"use strict";var mE=gs(),bE=pe(),vs=ur(),gE=Ae(),vE=gE("toStringTag"),SE=Object,yE=vs(function(){return arguments}())==="Arguments",TE=function(a,e){try{return a[e]}catch(t){}};Np.exports=mE?vs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=TE(e=SE(a),vE))=="string"?t:yE?vs(e):(r=vs(e))==="Object"&&bE(e.callee)?"Arguments":r}});var qp=b((XL,Fp)=>{"use strict";var IE=gs(),EE=Ri();Fp.exports=IE?{}.toString:function(){return"[object "+EE(this)+"]"}});var $i=b((ZL,Hp)=>{"use strict";var xE=gs(),PE=dr().f,AE=Br(),wE=st(),kE=qp(),RE=Ae(),Up=RE("toStringTag");Hp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(wE(i,Up)||PE(i,Up,{configurable:!0,value:e}),r&&!xE&&AE(i,"toString",kE))}});var Gp=b((eM,jp)=>{"use strict";var $E=Ao().IteratorPrototype,LE=Io(),ME=Si(),CE=$i(),DE=pr(),OE=function(){return this};jp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=LE($E,{next:ME(+!r,t)}),CE(a,i,!1,!0),DE[i]=OE,a}});var Wp=b((tM,Qp)=>{"use strict";var VE=ve(),BE=pt();Qp.exports=function(a,e,t){try{return VE(BE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var zp=b((rM,Yp)=>{"use strict";var _E=qe();Yp.exports=function(a){return _E(a)||a===null}});var Jp=b((iM,Kp)=>{"use strict";var NE=zp(),FE=String,qE=TypeError;Kp.exports=function(a){if(NE(a))return a;throw new qE("Can't set "+FE(a)+" as a prototype")}});var wo=b((aM,Xp)=>{"use strict";var UE=Wp(),HE=qe(),jE=Gt(),GE=Jp();Xp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=UE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return jE(i),GE(s),HE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var lh=b((sM,uh)=>{"use strict";var QE=fe(),WE=Fe(),Ss=at(),nh=go(),YE=pe(),zE=Gp(),Zp=ds(),eh=wo(),KE=$i(),JE=Br(),ko=Ur(),XE=Ae(),th=pr(),oh=Ao(),ZE=nh.PROPER,ex=nh.CONFIGURABLE,rh=oh.IteratorPrototype,ys=oh.BUGGY_SAFARI_ITERATORS,Li=XE("iterator"),ih="keys",Mi="values",ah="entries",sh=function(){return this};uh.exports=function(a,e,t,r,i,s,n){zE(t,e,r);var o=function(I){if(I===i&&p)return p;if(!ys&&I&&I in d)return d[I];switch(I){case ih:return function(){return new t(this,I)};case Mi: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,d=a.prototype,c=d[Li]||d["@@iterator"]||i&&d[i],p=!ys&&c||o(i),h=e==="Array"&&d.entries||c,m,g,v;if(h&&(m=Zp(h.call(new a)),m!==Object.prototype&&m.next&&(!Ss&&Zp(m)!==rh&&(eh?eh(m,rh):YE(m[Li])||ko(m,Li,sh)),KE(m,u,!0,!0),Ss&&(th[u]=sh))),ZE&&i===Mi&&c&&c.name!==Mi&&(!Ss&&ex?JE(d,"name",Mi):(l=!0,p=function(){return WE(c,this)})),i)if(g={values:o(Mi),keys:s?p:o(ih),entries:o(ah)},n)for(v in g)(ys||l||!(v in d))&&ko(d,v,g[v]);else QE({target:e,proto:!0,forced:ys||l},g);return(!Ss||n)&&d[Li]!==p&&ko(d,Li,p,{name:i}),th[e]=p,g}});var dh=b((nM,ch)=>{"use strict";ch.exports=function(a,e){return{value:a,done:e}}});var $o=b((oM,bh)=>{"use strict";var tx=lr(),Ro=wi(),ph=pr(),fh=fo(),rx=dr().f,ix=lh(),Ts=dh(),ax=at(),sx=Ne(),mh="Array Iterator",nx=fh.set,ox=fh.getterFor(mh);bh.exports=ix(Array,"Array",function(a,e){nx(this,{type:mh,target:tx(a),index:0,kind:e})},function(){var a=ox(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 hh=ph.Arguments=ph.Array;Ro("keys");Ro("values");Ro("entries");if(!ax&&sx&&hh.name!=="values")try{rx(hh,"name",{value:"values"})}catch(a){}});var vh=b((uM,gh)=>{"use strict";var ux=Ae(),lx=pr(),cx=ux("iterator"),dx=Array.prototype;gh.exports=function(a){return a!==void 0&&(lx.Array===a||dx[cx]===a)}});var Lo=b((lM,yh)=>{"use strict";var px=Ri(),Sh=Ii(),hx=Mr(),fx=pr(),mx=Ae(),bx=mx("iterator");yh.exports=function(a){if(!hx(a))return Sh(a,bx)||Sh(a,"@@iterator")||fx[px(a)]}});var Ih=b((cM,Th)=>{"use strict";var gx=Fe(),vx=pt(),Sx=ht(),yx=Ti(),Tx=Lo(),Ix=TypeError;Th.exports=function(a,e){var t=arguments.length<2?Tx(a):e;if(vx(t))return Sx(gx(t,a));throw new Ix(yx(a)+" is not iterable")}});var Ph=b((dM,xh)=>{"use strict";var Ex=Fe(),Eh=ht(),xx=Ii();xh.exports=function(a,e,t){var r,i;Eh(a);try{if(r=xx(a,"return"),!r){if(e==="throw")throw t;return t}r=Ex(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Eh(r),t}});var Es=b((pM,Rh)=>{"use strict";var Px=Vr(),Ax=Fe(),wx=ht(),kx=Ti(),Rx=vh(),$x=Fr(),Ah=yi(),Lx=Ih(),Mx=Lo(),wh=Ph(),Cx=TypeError,Is=function(a,e){this.stopped=a,this.result=e},kh=Is.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=Px(e,r),l,d,c,p,h,m,g,v=function(T){return l&&wh(l,"normal",T),new Is(!0,T)},I=function(T){return i?(wx(T),o?u(T[0],T[1],v):u(T[0],T[1])):o?u(T,v):u(T)};if(s)l=a.iterator;else if(n)l=a;else{if(d=Mx(a),!d)throw new Cx(kx(a)+" is not iterable");if(Rx(d)){for(c=0,p=$x(a);p>c;c++)if(h=I(a[c]),h&&Ah(kh,h))return h;return new Is(!1)}l=Lx(a,d)}for(m=s?a.next:l.next;!(g=Ax(m,l)).done;){try{h=I(g.value)}catch(T){wh(l,"throw",T)}if(typeof h=="object"&&h&&Ah(kh,h))return h}return new Is(!1)}});var Lh=b((hM,$h)=>{"use strict";var Dx=Ne(),Ox=dr(),Vx=Si();$h.exports=function(a,e,t){Dx?Ox.f(a,e,Vx(0,t)):a[e]=t}});var Mh=b(()=>{"use strict";var Bx=fe(),_x=Es(),Nx=Lh();Bx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return _x(e,function(r,i){Nx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Dh=b((bM,Ch)=>{"use strict";$o();Mh();var Fx=Cr();Ch.exports=Fx.Object.fromEntries});var Vh=b((gM,Oh)=>{"use strict";Oh.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 qx=Vh(),Ux=he(),Hx=$i(),Bh=pr();for(xs in qx)Hx(Ux[xs],xs),Bh[xs]=Bh.Array;var xs});var Fh=b((yM,Nh)=>{"use strict";var jx=Dh();_h();Nh.exports=jx});var Mo=b((TM,qh)=>{"use strict";var Gx=Fh();qh.exports=Gx});var Uh=b(()=>{"use strict"});var Co=b((xM,Hh)=>{"use strict";var Ci=he(),Qx=cr(),Wx=ur(),Ps=function(a){return Qx.slice(0,a.length)===a};Hh.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":Wx(Ci.process)==="process"?"NODE":Ci.window&&Ci.document?"BROWSER":"REST"}()});var As=b((PM,jh)=>{"use strict";var Yx=Co();jh.exports=Yx==="NODE"});var Qh=b((AM,Gh)=>{"use strict";var zx=dr();Gh.exports=function(a,e,t){return zx.f(a,e,t)}});var zh=b((wM,Yh)=>{"use strict";var Kx=Et(),Jx=Qh(),Xx=Ae(),Zx=Ne(),Wh=Xx("species");Yh.exports=function(a){var e=Kx(a);Zx&&e&&!e[Wh]&&Jx(e,Wh,{configurable:!0,get:function(){return this}})}});var Jh=b((kM,Kh)=>{"use strict";var eP=yi(),tP=TypeError;Kh.exports=function(a,e){if(eP(e,a))return a;throw new tP("Incorrect invocation")}});var Oo=b((RM,Xh)=>{"use strict";var rP=ve(),iP=pe(),Do=Ei(),aP=rP(Function.toString);iP(Do.inspectSource)||(Do.inspectSource=function(a){return aP(a)});Xh.exports=Do.inspectSource});var Bo=b(($M,af)=>{"use strict";var sP=ve(),nP=Pe(),Zh=pe(),oP=Ri(),uP=Et(),lP=Oo(),ef=function(){},tf=uP("Reflect","construct"),Vo=/^\s*(?:class|function)\b/,cP=sP(Vo.exec),dP=!Vo.test(ef),Di=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(oP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return dP||!!cP(Vo,lP(e))}catch(t){return!0}};rf.sham=!0;af.exports=!tf||nP(function(){var a;return Di(Di.call)||!Di(Object)||!Di(function(){a=!0})||a})?rf:Di});var nf=b((LM,sf)=>{"use strict";var pP=Bo(),hP=Ti(),fP=TypeError;sf.exports=function(a){if(pP(a))return a;throw new fP(hP(a)+" is not a constructor")}});var _o=b((MM,uf)=>{"use strict";var of=ht(),mP=nf(),bP=Mr(),gP=Ae(),vP=gP("species");uf.exports=function(a,e){var t=of(a).constructor,r;return t===void 0||bP(r=of(t)[vP])?e:mP(r)}});var cf=b((CM,lf)=>{"use strict";var SP=ve();lf.exports=SP([].slice)});var pf=b((DM,df)=>{"use strict";var yP=TypeError;df.exports=function(a,e){if(a<e)throw new yP("Not enough arguments");return a}});var No=b((OM,hf)=>{"use strict";var TP=cr();hf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(TP)});var Yo=b((VM,If)=>{"use strict";var Ue=he(),IP=Rn(),EP=Vr(),ff=pe(),xP=st(),Tf=Pe(),mf=vo(),PP=cf(),bf=os(),AP=pf(),wP=No(),kP=As(),Go=Ue.setImmediate,Qo=Ue.clearImmediate,RP=Ue.process,Fo=Ue.Dispatch,$P=Ue.Function,gf=Ue.MessageChannel,LP=Ue.String,qo=0,Oi={},vf="onreadystatechange",Vi,fr,Uo,Ho;Tf(function(){Vi=Ue.location});var Wo=function(a){if(xP(Oi,a)){var e=Oi[a];delete Oi[a],e()}},jo=function(a){return function(){Wo(a)}},Sf=function(a){Wo(a.data)},yf=function(a){Ue.postMessage(LP(a),Vi.protocol+"//"+Vi.host)};(!Go||!Qo)&&(Go=function(e){AP(arguments.length,1);var t=ff(e)?e:$P(e),r=PP(arguments,1);return Oi[++qo]=function(){IP(t,void 0,r)},fr(qo),qo},Qo=function(e){delete Oi[e]},kP?fr=function(a){RP.nextTick(jo(a))}:Fo&&Fo.now?fr=function(a){Fo.now(jo(a))}:gf&&!wP?(Uo=new gf,Ho=Uo.port2,Uo.port1.onmessage=Sf,fr=EP(Ho.postMessage,Ho)):Ue.addEventListener&&ff(Ue.postMessage)&&!Ue.importScripts&&Vi&&Vi.protocol!=="file:"&&!Tf(yf)?(fr=yf,Ue.addEventListener("message",Sf,!1)):vf in bf("script")?fr=function(a){mf.appendChild(bf("script"))[vf]=function(){mf.removeChild(this),Wo(a)}}:fr=function(a){setTimeout(jo(a),0)});If.exports={set:Go,clear:Qo}});var Pf=b((BM,xf)=>{"use strict";var Ef=he(),MP=Ne(),CP=Object.getOwnPropertyDescriptor;xf.exports=function(a){if(!MP)return Ef[a];var e=CP(Ef,a);return e&&e.value}});var zo=b((_M,wf)=>{"use strict";var Af=function(){this.head=null,this.tail=null};Af.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}}};wf.exports=Af});var Rf=b((NM,kf)=>{"use strict";var DP=cr();kf.exports=/ipad|iphone|ipod/i.test(DP)&&typeof Pebble!="undefined"});var Lf=b((FM,$f)=>{"use strict";var OP=cr();$f.exports=/web0s(?!.*chrome)/i.test(OP)});var _f=b((qM,Bf)=>{"use strict";var jr=he(),VP=Pf(),Mf=Vr(),Ko=Yo().set,BP=zo(),_P=No(),NP=Rf(),FP=Lf(),Jo=As(),Cf=jr.MutationObserver||jr.WebKitMutationObserver,Df=jr.document,Of=jr.process,ws=jr.Promise,eu=VP("queueMicrotask"),Hr,Xo,Zo,ks,Vf;eu||(Bi=new BP,_i=function(){var a,e;for(Jo&&(a=Of.domain)&&a.exit();e=Bi.get();)try{e()}catch(t){throw Bi.head&&Hr(),t}a&&a.enter()},!_P&&!Jo&&!FP&&Cf&&Df?(Xo=!0,Zo=Df.createTextNode(""),new Cf(_i).observe(Zo,{characterData:!0}),Hr=function(){Zo.data=Xo=!Xo}):!NP&&ws&&ws.resolve?(ks=ws.resolve(void 0),ks.constructor=ws,Vf=Mf(ks.then,ks),Hr=function(){Vf(_i)}):Jo?Hr=function(){Of.nextTick(_i)}:(Ko=Mf(Ko,jr),Hr=function(){Ko(_i)}),eu=function(a){Bi.head||Hr(),Bi.add(a)});var Bi,_i;Bf.exports=eu});var Ff=b((UM,Nf)=>{"use strict";Nf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Rs=b((HM,qf)=>{"use strict";qf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var mr=b((jM,Uf)=>{"use strict";var qP=he();Uf.exports=qP.Promise});var Gr=b((GM,Qf)=>{"use strict";var UP=he(),Ni=mr(),HP=pe(),jP=Jn(),GP=Oo(),QP=Ae(),Hf=Co(),WP=at(),tu=_n(),jf=Ni&&Ni.prototype,YP=QP("species"),ru=!1,Gf=HP(UP.PromiseRejectionEvent),zP=jP("Promise",function(){var a=GP(Ni),e=a!==String(Ni);if(!e&&tu===66||WP&&!(jf.catch&&jf.finally))return!0;if(!tu||tu<51||!/native code/.test(a)){var t=new Ni(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[YP]=r,ru=t.then(function(){})instanceof r,!ru)return!0}return!e&&(Hf==="BROWSER"||Hf==="DENO")&&!Gf});Qf.exports={CONSTRUCTOR:zP,REJECTION_EVENT:Gf,SUBCLASSING:ru}});var Qr=b((QM,Yf)=>{"use strict";var Wf=pt(),KP=TypeError,JP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new KP("Bad Promise constructor");e=r,t=i}),this.resolve=Wf(e),this.reject=Wf(t)};Yf.exports.f=function(a){return new JP(a)}});var hm=b(()=>{"use strict";var XP=fe(),ZP=at(),Cs=As(),Wt=he(),Kr=Fe(),zf=Ur(),Kf=wo(),eA=$i(),tA=zh(),rA=pt(),Ms=pe(),iA=qe(),aA=Jh(),sA=_o(),tm=Yo().set,ou=_f(),nA=Ff(),oA=Rs(),uA=zo(),rm=fo(),Ds=mr(),uu=Gr(),im=Qr(),Os="Promise",am=uu.CONSTRUCTOR,lA=uu.REJECTION_EVENT,cA=uu.SUBCLASSING,iu=rm.getterFor(Os),dA=rm.set,Wr=Ds&&Ds.prototype,br=Ds,$s=Wr,sm=Wt.TypeError,au=Wt.document,lu=Wt.process,su=im.f,pA=su,hA=!!(au&&au.createEvent&&Wt.dispatchEvent),nm="unhandledrejection",fA="rejectionhandled",Jf=0,om=1,mA=2,cu=1,um=2,Ls,Xf,bA,Zf,lm=function(a){var e;return iA(a)&&Ms(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,d;try{i?(r||(e.rejection===um&&vA(e),e.rejection=cu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),d=!0)),u===a.promise?n(new sm("Promise-chain cycle")):(l=lm(u))?Kr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},dm=function(a,e){a.notified||(a.notified=!0,ou(function(){for(var t=a.reactions,r;r=t.get();)cm(r,a);a.notified=!1,e&&!a.rejection&&gA(a)}))},pm=function(a,e,t){var r,i;hA?(r=au.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Wt.dispatchEvent(r)):r={promise:e,reason:t},!lA&&(i=Wt["on"+a])?i(r):a===nm&&nA("Unhandled promise rejection",t)},gA=function(a){Kr(tm,Wt,function(){var e=a.facade,t=a.value,r=em(a),i;if(r&&(i=oA(function(){Cs?lu.emit("unhandledRejection",t,e):pm(nm,e,t)}),a.rejection=Cs||em(a)?um:cu,i.error))throw i.value})},em=function(a){return a.rejection!==cu&&!a.parent},vA=function(a){Kr(tm,Wt,function(){var e=a.facade;Cs?lu.emit("rejectionHandled",e):pm(fA,e,a.value)})},Yr=function(a,e,t){return function(r){a(e,r,t)}},zr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=mA,dm(a,!0))},nu=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?ou(function(){var i={done:!1};try{Kr(r,e,Yr(nu,i,a),Yr(zr,i,a))}catch(s){zr(i,s,a)}}):(a.value=e,a.state=om,dm(a,!1))}catch(i){zr({done:!1},i,a)}}};if(am&&(br=function(e){aA(this,$s),rA(e),Kr(Ls,this);var t=iu(this);try{e(Yr(nu,t),Yr(zr,t))}catch(r){zr(t,r)}},$s=br.prototype,Ls=function(e){dA(this,{type:Os,done:!1,notified:!1,parent:!1,reactions:new uA,rejection:!1,state:Jf,value:void 0})},Ls.prototype=zf($s,"then",function(e,t){var r=iu(this),i=su(sA(this,br));return r.parent=!0,i.ok=Ms(e)?e:!0,i.fail=Ms(t)&&t,i.domain=Cs?lu.domain:void 0,r.state===Jf?r.reactions.add(i):ou(function(){cm(i,r)}),i.promise}),Xf=function(){var a=new Ls,e=iu(a);this.promise=a,this.resolve=Yr(nu,e),this.reject=Yr(zr,e)},im.f=su=function(a){return a===br||a===bA?new Xf(a):pA(a)},!ZP&&Ms(Ds)&&Wr!==Object.prototype)){Zf=Wr.then,cA||zf(Wr,"then",function(e,t){var r=this;return new br(function(i,s){Kr(Zf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Wr.constructor}catch(a){}Kf&&Kf(Wr,$s)}XP({global:!0,constructor:!0,wrap:!0,forced:am},{Promise:br});eA(br,Os,!1,!0);tA(Os)});var vm=b((zM,gm)=>{"use strict";var SA=Ae(),mm=SA("iterator"),bm=!1;try{fm=0,du={next:function(){return{done:!!fm++}},return:function(){bm=!0}},du[mm]=function(){return this},Array.from(du,function(){throw 2})}catch(a){}var fm,du;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 pu=b((KM,Sm)=>{"use strict";var yA=mr(),TA=vm(),IA=Gr().CONSTRUCTOR;Sm.exports=IA||!TA(function(a){yA.all(a).then(void 0,function(){})})});var ym=b(()=>{"use strict";var EA=fe(),xA=Fe(),PA=pt(),AA=Qr(),wA=Rs(),kA=Es(),RA=pu();EA({target:"Promise",stat:!0,forced:RA},{all:function(e){var t=this,r=AA.f(t),i=r.resolve,s=r.reject,n=wA(function(){var o=PA(t.resolve),u=[],l=0,d=1;kA(e,function(c){var p=l++,h=!1;d++,xA(o,t,c).then(function(m){h||(h=!0,u[p]=m,--d||i(u))},s)}),--d||i(u)});return n.error&&s(n.value),r.promise}})});var Im=b(()=>{"use strict";var $A=fe(),LA=at(),MA=Gr().CONSTRUCTOR,fu=mr(),CA=Et(),DA=pe(),OA=Ur(),Tm=fu&&fu.prototype;$A({target:"Promise",proto:!0,forced:MA,real:!0},{catch:function(a){return this.then(void 0,a)}});!LA&&DA(fu)&&(hu=CA("Promise").prototype.catch,Tm.catch!==hu&&OA(Tm,"catch",hu,{unsafe:!0}));var hu});var Em=b(()=>{"use strict";var VA=fe(),BA=Fe(),_A=pt(),NA=Qr(),FA=Rs(),qA=Es(),UA=pu();VA({target:"Promise",stat:!0,forced:UA},{race:function(e){var t=this,r=NA.f(t),i=r.reject,s=FA(function(){var n=_A(t.resolve);qA(e,function(o){BA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var xm=b(()=>{"use strict";var HA=fe(),jA=Qr(),GA=Gr().CONSTRUCTOR;HA({target:"Promise",stat:!0,forced:GA},{reject:function(e){var t=jA.f(this),r=t.reject;return r(e),t.promise}})});var mu=b((s0,Pm)=>{"use strict";var QA=ht(),WA=qe(),YA=Qr();Pm.exports=function(a,e){if(QA(a),WA(e)&&e.constructor===a)return e;var t=YA.f(a),r=t.resolve;return r(e),t.promise}});var km=b(()=>{"use strict";var zA=fe(),KA=Et(),Am=at(),JA=mr(),wm=Gr().CONSTRUCTOR,XA=mu(),ZA=KA("Promise"),ew=Am&&!wm;zA({target:"Promise",stat:!0,forced:Am||wm},{resolve:function(e){return XA(ew&&this===ZA?JA:this,e)}})});var Rm=b(()=>{"use strict";hm();ym();Im();Em();xm();km()});var Cm=b(()=>{"use strict";var tw=fe(),rw=at(),Vs=mr(),iw=Pe(),Lm=Et(),Mm=pe(),aw=_o(),$m=mu(),sw=Ur(),gu=Vs&&Vs.prototype,nw=!!Vs&&iw(function(){gu.finally.call({then:function(){}},function(){})});tw({target:"Promise",proto:!0,real:!0,forced:nw},{finally:function(a){var e=aw(this,Lm("Promise")),t=Mm(a);return this.then(t?function(r){return $m(e,a()).then(function(){return r})}:a,t?function(r){return $m(e,a()).then(function(){throw r})}:a)}});!rw&&Mm(Vs)&&(bu=Lm("Promise").prototype.finally,gu.finally!==bu&&sw(gu,"finally",bu,{unsafe:!0}));var bu});var Om=b((p0,Dm)=>{"use strict";Uh();Rm();Cm();var ow=Qt();Dm.exports=ow("Promise","finally")});var Bm=b((h0,Vm)=>{"use strict";var uw=Om();Vm.exports=uw});var Bs=b((f0,_m)=>{"use strict";var lw=Bm();_m.exports=lw});var Gm=b(()=>{"use strict";var fw=fe(),mw=lo().values;fw({target:"Object",stat:!0},{values:function(e){return mw(e)}})});var Wm=b((G0,Qm)=>{"use strict";Gm();var bw=Cr();Qm.exports=bw.Object.values});var zm=b((Q0,Ym)=>{"use strict";var gw=Wm();Ym.exports=gw});var qi=b((W0,Km)=>{"use strict";var vw=zm();Km.exports=vw});var eb=b(()=>{"use strict";var Iw=fe(),Ew=Dr(),xw=Fr(),Pw=Ai(),Aw=wi();Iw({target:"Array",proto:!0},{at:function(e){var t=Ew(this),r=xw(t),i=Pw(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});Aw("at")});var rb=b((gC,tb)=>{"use strict";eb();var ww=Qt();tb.exports=ww("Array","at")});var ab=b((vC,ib)=>{"use strict";var kw=rb();ib.exports=kw});var Jr=b((SC,sb)=>{"use strict";var Rw=ab();sb.exports=Rw});var Du=b((FD,Pb)=>{"use strict";var Fw=ur();Pb.exports=Array.isArray||function(e){return Fw(e)==="Array"}});var wb=b((qD,Ab)=>{"use strict";var qw=TypeError,Uw=9007199254740991;Ab.exports=function(a){if(a>Uw)throw qw("Maximum allowed index exceeded");return a}});var $b=b((UD,Rb)=>{"use strict";var Hw=Du(),jw=Fr(),Gw=wb(),Qw=Vr(),kb=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,d=n?Qw(n,o):!1,c,p;l<r;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&Hw(c)?(p=jw(c),u=kb(a,e,c,p,u,s-1)-1):(Gw(u+1),a[u]=c),u++),l++;return u};Rb.exports=kb});var Db=b((HD,Cb)=>{"use strict";var Lb=Du(),Ww=Bo(),Yw=qe(),zw=Ae(),Kw=zw("species"),Mb=Array;Cb.exports=function(a){var e;return Lb(a)&&(e=a.constructor,Ww(e)&&(e===Mb||Lb(e.prototype))?e=void 0:Yw(e)&&(e=e[Kw],e===null&&(e=void 0))),e===void 0?Mb:e}});var Vb=b((jD,Ob)=>{"use strict";var Jw=Db();Ob.exports=function(a,e){return new(Jw(a))(e===0?0:e)}});var Bb=b(()=>{"use strict";var Xw=fe(),Zw=$b(),ek=pt(),tk=Dr(),rk=Fr(),ik=Vb();Xw({target:"Array",proto:!0},{flatMap:function(e){var t=tk(this),r=rk(t),i;return ek(e),i=ik(t,0),i.length=Zw(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var _b=b(()=>{"use strict";var ak=wi();ak("flatMap")});var Fb=b((zD,Nb)=>{"use strict";Bb();_b();var sk=Qt();Nb.exports=sk("Array","flatMap")});var Ub=b((KD,qb)=>{"use strict";var nk=Fb();qb.exports=nk});var Ou=b((JD,Hb)=>{"use strict";var ok=Ub();Hb.exports=ok});var Xi=b((oO,lg)=>{"use strict";var mk=Ri(),bk=String;lg.exports=function(a){if(mk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return bk(a)}});var Bu=b((uO,cg)=>{"use strict";cg.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 hg=b((lO,pg)=>{"use strict";var gk=ve(),vk=Gt(),Sk=Xi(),Nu=Bu(),dg=gk("".replace),yk=RegExp("^["+Nu+"]+"),Tk=RegExp("(^|[^"+Nu+"])["+Nu+"]+$"),_u=function(a){return function(e){var t=Sk(vk(e));return a&1&&(t=dg(t,yk,"")),a&2&&(t=dg(t,Tk,"$1")),t}};pg.exports={start:_u(1),end:_u(2),trim:_u(3)}});var gg=b((cO,bg)=>{"use strict";var Ik=go().PROPER,Ek=Pe(),fg=Bu(),mg="\u200B\x85\u180E";bg.exports=function(a){return Ek(function(){return!!fg[a]()||mg[a]()!==mg||Ik&&fg[a].name!==a})}});var Fu=b((dO,vg)=>{"use strict";var xk=hg().start,Pk=gg();vg.exports=Pk("trimStart")?function(){return xk(this)}:"".trimStart});var yg=b(()=>{"use strict";var Ak=fe(),Sg=Fu();Ak({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Sg},{trimLeft:Sg})});var Ig=b(()=>{"use strict";yg();var wk=fe(),Tg=Fu();wk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Tg},{trimStart:Tg})});var xg=b((bO,Eg)=>{"use strict";Ig();var kk=Qt();Eg.exports=kk("String","trimLeft")});var Ag=b((gO,Pg)=>{"use strict";var Rk=xg();Pg.exports=Rk});var kg=b((vO,wg)=>{"use strict";var $k=Ag();wg.exports=$k});var Ug=b(()=>{"use strict"});var Hg=b(()=>{"use strict"});var Gg=b((qB,jg)=>{"use strict";var Kk=qe(),Jk=ur(),Xk=Ae(),Zk=Xk("match");jg.exports=function(a){var e;return Kk(a)&&((e=a[Zk])!==void 0?!!e:Jk(a)==="RegExp")}});var Wg=b((UB,Qg)=>{"use strict";var eR=ht();Qg.exports=function(){var a=eR(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 Kg=b((HB,zg)=>{"use strict";var tR=Fe(),rR=st(),iR=yi(),aR=Wg(),Yg=RegExp.prototype;zg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Yg)&&!rR(a,"flags")&&iR(Yg,a)?tR(aR,a):e}});var Xg=b((jB,Jg)=>{"use strict";var Wu=ve(),sR=Dr(),nR=Math.floor,Gu=Wu("".charAt),oR=Wu("".replace),Qu=Wu("".slice),uR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,lR=/\$([$&'`]|\d{1,2})/g;Jg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=lR;return i!==void 0&&(i=sR(i),u=uR),oR(s,u,function(l,d){var c;switch(Gu(d,0)){case"$":return"$";case"&":return a;case"`":return Qu(e,0,t);case"'":return Qu(e,n);case"<":c=i[Qu(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=nR(p/10);return h===0?l:h<=o?r[h-1]===void 0?Gu(d,1):r[h-1]+Gu(d,1):l}c=r[p-1]}return c===void 0?"":c})}});var tv=b(()=>{"use strict";var cR=fe(),dR=Fe(),zu=ve(),Zg=Gt(),pR=pe(),hR=Mr(),fR=Gg(),ai=Xi(),mR=Ii(),bR=Kg(),gR=Xg(),vR=Ae(),SR=at(),yR=vR("replace"),TR=TypeError,Yu=zu("".indexOf),IR=zu("".replace),ev=zu("".slice),ER=Math.max;cR({target:"String",proto:!0},{replaceAll:function(e,t){var r=Zg(this),i,s,n,o,u,l,d,c,p,h,m=0,g="";if(!hR(e)){if(i=fR(e),i&&(s=ai(Zg(bR(e))),!~Yu(s,"g")))throw new TR("`.replaceAll` does not allow non-global regexes");if(n=mR(e,yR),n)return dR(n,e,r,t);if(SR&&i)return IR(ai(r),e,t)}for(o=ai(r),u=ai(e),l=pR(t),l||(t=ai(t)),d=u.length,c=ER(1,d),p=Yu(o,u);p!==-1;)h=l?ai(t(u,p,o)):gR(u,o,p,[],void 0,t),g+=ev(o,m,p)+h,m=p+d,p=p+c>o.length?-1:Yu(o,u,p+c);return m<o.length&&(g+=ev(o,m)),g}})});var iv=b((WB,rv)=>{"use strict";Ug();Hg();tv();var xR=Qt();rv.exports=xR("String","replaceAll")});var sv=b((YB,av)=>{"use strict";var PR=iv();av.exports=PR});var ov=b((zB,nv)=>{"use strict";var AR=sv();nv.exports=AR});var lv=b((KB,uv)=>{"use strict";var wR=Ai(),kR=Xi(),RR=Gt(),$R=RangeError;uv.exports=function(e){var t=kR(RR(this)),r="",i=wR(e);if(i<0||i===1/0)throw new $R("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var fv=b((JB,hv)=>{"use strict";var pv=ve(),LR=io(),cv=Xi(),MR=lv(),CR=Gt(),DR=pv(MR),OR=pv("".slice),VR=Math.ceil,dv=function(a){return function(e,t,r){var i=cv(CR(e)),s=LR(t),n=i.length,o=r===void 0?" ":cv(r),u,l;return s<=n||o===""?i:(u=s-n,l=DR(o,VR(u/o.length)),l.length>u&&(l=OR(l,0,u)),a?i+l:l+i)}};hv.exports={start:dv(!1),end:dv(!0)}});var bv=b((XB,mv)=>{"use strict";var BR=cr();mv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(BR)});var gv=b(()=>{"use strict";var _R=fe(),NR=fv().start,FR=bv();_R({target:"String",proto:!0,forced:FR},{padStart:function(e){return NR(this,e,arguments.length>1?arguments[1]:void 0)}})});var Sv=b((t_,vv)=>{"use strict";gv();var qR=Qt();vv.exports=qR("String","padStart")});var Tv=b((r_,yv)=>{"use strict";var UR=Sv();yv.exports=UR});var Ev=b((i_,Iv)=>{"use strict";var HR=Tv();Iv.exports=HR});var o$={};CS(o$,{ChromecastState:()=>bi,HttpConnectionType:()=>is,Observable:()=>yt.Observable,PlaybackState:()=>Re,Player:()=>Ua,SDK_VERSION:()=>n$,Subject:()=>yt.Subject,Subscription:()=>yt.Subscription,Surface:()=>as,VERSION:()=>wn,ValueSubject:()=>yt.ValueSubject,VideoFormat:()=>It,VideoQuality:()=>yt.VideoQuality});module.exports=DS(o$);var wn="2.0.119-beta.0";var Re=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Re||{}),It=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(It||{});var bi=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(bi||{}),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 fS=X(ft(),1);var F=require("@vkontakte/videoplayer-shared/es2015");var jd=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var 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;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.initializeCastApi()},i||jd("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.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)(rI),(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 d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,F.isNullable)(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(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})}}},rI=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 pl=X(ft(),1),tS=X(qr(),1),rS=X(Mo(),1);var Um=X(Bs(),1);var vu=require("@vkontakte/videoplayer-shared/es2015");var we=(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,vu.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,vu.assertNever)(e)}};var k=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var mt=require("@vkontakte/videoplayer-shared/es2015"),j=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 Nm=require("@vkontakte/videoplayer-shared/es2015"),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/es2015");var cw=5,dw=5,pw=500,qm=7e3,Fi=class{constructor(e){this.subscription=new L.Subscription;this.loadMediaTimeoutSubscription=new L.Subscription;this.videoState=new j("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)(pw)).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)>cw)&&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<dw&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let d=t[e];(0,L.assertNonNullable)(d);let c=(0,L.getHighestQuality)(Object.keys(d));(0,L.assertNonNullable)(c);let p=d[c];(0,L.assertNonNullable)(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];(0,L.assertNonNullable)(d),r=d.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];(0,L.assertNonNullable)(d),r=d.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];(0,L.assertNonNullable)(d),r=d.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];(0,L.assertNonNullable)(d),r=we(d.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:c}),c}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 Mu=X(ft(),1);var Iu=require("@vkontakte/videoplayer-shared/es2015");var Hm=require("@vkontakte/videoplayer-shared/es2015"),jm=a=>{try{a.pause(),a.playbackRate=0,(0,Hm.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Ns=require("@vkontakte/videoplayer-shared/es2015"),Su=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)}},yu=window.WeakMap?new WeakMap:new Su,Tu=window.WeakMap?new WeakMap:new Map,hw=(a,e=20)=>{let t=0;return(0,Ns.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Le=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,Iu.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),yu.set(t,r);let i=new Ns.Subscription;return i.add(hw(t,e)),Tu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Me=a=>{let e=Tu.get(a);e==null||e.unsubscribe(),Tu.delete(a);let t=yu.get(a);yu.delete(a),t?(0,Iu.clearVideoElement)(a):jm(a)};var Eu=X(qi(),1),M=require("@vkontakte/videoplayer-shared/es2015");var Yt=require("@vkontakte/videoplayer-shared/es2015"),Fs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Yt.isNullable)(i),l=new Yt.Subscription;return i&&l.add(i.subscribe(d=>{let c=a.getState();r(d,c)&&a.setState(d)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},bt=(a,e,t)=>Fs(e,()=>a.loop,r=>{(0,Yt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Ce=(a,e,t,r)=>Fs(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Yt.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}),ze=(a,e,t,r)=>Fs(e,()=>a.playbackRate,i=>{(0,Yt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),zt=Fs;var Sw=a=>["__",a.language,a.label].join("|"),yw=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},xu=class a{constructor(){this.available$=new M.Subject;this.current$=new M.ValueSubject(void 0);this.error$=new M.Subject;this.subscription=new M.Subscription;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:M.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(zt(t.internalTextTracks,()=>(0,Eu.default)(this.internalTracks),s=>{(0,M.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,M.isNonNullable)(s)&&(0,M.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,M.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(zt(t.externalTextTracks,()=>(0,Eu.default)(this.externalTracks),s=>{(0,M.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,M.isNonNullable)(s)&&(0,M.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,M.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(zt(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(zt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,M.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,M.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,M.merge)((0,M.fromEvent)(e,"addtrack"),(0,M.fromEvent)(e,"removetrack"),(0,M.observableFrom)(["init"])).pipe((0,M.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,M.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,M.merge)((0,M.fromEvent)(e,"change"),(0,M.observableFrom)(["init"])).pipe((0,M.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,M.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,M.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,M.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,d,c,p,h;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,M.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,M.isNonNullable)(t.align)&&(i.align=t.align),(0,M.isNonNullable)(t.position)&&(i.position=t.position),(0,M.isNonNullable)(t.size)&&(i.size=t.size),(0,M.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,M.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:r}=e,i=e.id?e.id:Sw(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(d=this.externalTracks.get(i))==null?void 0:d.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(c=this.internalTracks.get(i))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,M.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,M.isNullable)(e)||!yw(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,M.assertNonNullable)(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,M.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)}},Ke=xu;var At=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 Jm=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},Pu=a=>{let e=Jm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Xm=a=>{let e=Jm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared/es2015");var Tw=3,Zm=(a,e,t=Tw)=>{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 De=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 A;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:(A=a.error)!=null?A:void 0}})),l=(0,D.fromEvent)(a,"timeupdate").pipe((0,D.map)(()=>a.currentTime)),d=new D.Subject,c=.3,p;l.subscribe(x=>{a.loop&&(0,D.isNonNullable)(p)&&(0,D.isNonNullable)(x)&&p>=a.duration-c&&x<=c&&d.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(Xm(a));m.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let I=new D.ValueSubject(Pu(a));return(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.map)(()=>Pu(a))).subscribe(I),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(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/es2015"),Kt=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 Jt=X(Jr(),1),cb=X(ft(),1),qs=X(qr(),1),C=require("@vkontakte/videoplayer-shared/es2015");var Au=!1,kt={},nb=a=>{Au=a},ob=()=>{kt={}},ub=a=>{a(kt)},Ui=(a,e)=>{var t;Au&&(kt.meta=(t=kt.meta)!=null?t:{},kt.meta[a]=e)},$e=class{constructor(e){this.name=e}next(e){var r,i;if(!Au)return;kt.series=(r=kt.series)!=null?r:{};let t=(i=kt.series[this.name])!=null?i:[];t.push([Date.now(),e]),kt.series[this.name]=t}};var $w=new $e("best_bitrate"),db=(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,C.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},pb='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,C.isNonNullable)(l.bitrate)&&(0,C.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Jt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Jt.default)(s,-1);return o&&(0,cb.default)(n,o)?o:n.length?(0,Jt.default)(n,-1):(0,Jt.default)(s,0)},lb=a=>"quality"in a,hb=(a,e,t,r)=>{var n;let i=(0,C.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,C.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,C.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},Rw=(a,e)=>Math.log(e)/Math.log(a),Jt=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{var te,_,ie,U,ne,$;(0,C.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 K=r.pixelRatioLogBase,[Y=0,be=0,Ge=0]=r.pixelRatioLogCoefficients,Bt=Rw(K,Y*P+be)+Ge;Number.isFinite(Bt)&&(g*=Bt)}}let v=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*g,height:e.height*g}:void 0,I=r.considerPlaybackRate&&(0,C.isNonNullable)(o)?o:1,T=a.filter(P=>!(0,C.isInvariantQuality)(P.quality)).sort((P,K)=>(0,C.isHigher)(P.quality,K.quality)?-1:1),x=(te=(0,Kt.default)(T,-1))==null?void 0:te.quality,A=(_=(0,Kt.default)(T,0))==null?void 0:_.quality,w=(0,C.isNullable)(i)||(0,C.isNonNullable)(i.min)&&(0,C.isNonNullable)(i.max)&&(0,C.isLower)(i.max,i.min)||(0,C.isNonNullable)(i.min)&&A&&(0,C.isHigher)(i.min,A)||(0,C.isNonNullable)(i.max)&&x&&(0,C.isLower)(i.max,x),F=I*lb(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),Q={},J=T.filter(P=>{let K=!0;if(v)if(P.size)K=P.size.width<=v.width&&P.size.height<=v.height;else{let Ee=v&&(0,C.videoSizeToQuality)(v);K=Ee?(0,C.isLowerOrEqual)(P.quality,Ee):!0}if(!K)return Q[P.quality]="FitsContainer",!1;let Y=h||t;if(!((0,C.isNonNullable)(Y)&&isFinite(Y)&&(0,C.isNonNullable)(P.bitrate)?Y-s>=P.bitrate*F:!0))return Q[P.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,C.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,C.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,C.isHigher)(P.quality,u.quality))return Q[P.quality]="Buffer",!1;if(!!c&&(0,C.isHigherOrEqual)(P.quality,c))return Q[P.quality]="DroppedFramesLimit",!1;if(!!p&&(0,C.isHigherOrEqual)(P.quality,p))return Q[P.quality]="StallsLimit",!1;let re=w||((0,C.isNullable)(i.max)||(0,C.isLowerOrEqual)(P.quality,i.max))&&((0,C.isNullable)(i.min)||(0,C.isHigherOrEqual)(P.quality,i.min)),Ie=(0,C.isNonNullable)(d)&&!d?(0,C.isLowerOrEqual)(P.quality,r.backgroundVideoQualityLimit):!0;return!re||!Ie?(Q[P.quality]="FitsQualityLimits",!1):!0})[0];J&&J.bitrate&&kw.next(J.bitrate);let W=(ie=J!=null?J:(0,Kt.default)(T,-1))!=null?ie:a[0];return W.quality!==((U=l==null?void 0:l.last)==null?void 0:U.quality)&&m({message:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},Lw=(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:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{var te,B,ie,U,ne,$;(0,C.assertNotEmptyArray)(a,pb);let g=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let P=window.devicePixelRatio;if(r.pixelRatioMultiplier)g*=r.pixelRatioMultiplier*(P-1)+1;else{let K=r.pixelRatioLogBase,[Y=0,be=0,Qe=0]=r.pixelRatioLogCoefficients,Bt=Lw(K,Y*P+be)+Qe;Number.isFinite(Bt)&&(g*=Bt)}}let v=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*g,height:e.height*g}:void 0,I=r.considerPlaybackRate&&(0,C.isNonNullable)(o)?o:1,T=a.filter(P=>!(0,C.isInvariantQuality)(P.quality)).sort((P,K)=>(0,C.isHigher)(P.quality,K.quality)?-1:1),x=(te=(0,Jt.default)(T,-1))==null?void 0:te.quality,A=(B=(0,Jt.default)(T,0))==null?void 0:B.quality,w=(0,C.isNullable)(i)||(0,C.isNonNullable)(i.min)&&(0,C.isNonNullable)(i.max)&&(0,C.isLower)(i.max,i.min)||(0,C.isNonNullable)(i.min)&&A&&(0,C.isHigher)(i.min,A)||(0,C.isNonNullable)(i.max)&&x&&(0,C.isLower)(i.max,x),N=I*db(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),Q={},J=T.filter(P=>{let K=!0;if(v)if(P.size)K=P.size.width<=v.width&&P.size.height<=v.height;else{let Ee=v&&(0,C.videoSizeToQuality)(v);K=Ee?(0,C.isLowerOrEqual)(P.quality,Ee):!0}if(!K)return Q[P.quality]="FitsContainer",!1;let Y=h||t;if(!((0,C.isNonNullable)(Y)&&isFinite(Y)&&(0,C.isNonNullable)(P.bitrate)?Y-s>=P.bitrate*N:!0))return Q[P.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,C.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,C.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,C.isHigher)(P.quality,u.quality))return Q[P.quality]="Buffer",!1;if(!!c&&(0,C.isHigherOrEqual)(P.quality,c))return Q[P.quality]="DroppedFramesLimit",!1;if(!!p&&(0,C.isHigherOrEqual)(P.quality,p))return Q[P.quality]="StallsLimit",!1;let re=w||((0,C.isNullable)(i.max)||(0,C.isLowerOrEqual)(P.quality,i.max))&&((0,C.isNullable)(i.min)||(0,C.isHigherOrEqual)(P.quality,i.min)),Ie=(0,C.isNonNullable)(d)&&!d?(0,C.isLowerOrEqual)(P.quality,r.backgroundVideoQualityLimit):!0;return!re||!Ie?(Q[P.quality]="FitsQualityLimits",!1):!0})[0];J&&J.bitrate&&$w.next(J.bitrate);let W=(ie=J!=null?J:(0,Jt.default)(T,-1))!=null?ie:a[0];return W.quality!==((U=l==null?void 0:l.last)==null?void 0:U.quality)&&m({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
12
  ${a.map(P=>`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate} }`).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,Fs.default)(r!=null?r:{}).map(([P,K])=>`${P}: ${K}`).join(`
16
+ ${(0,qs.default)(r!=null?r:{}).map(([P,K])=>`${P}: ${K}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
@@ -24,7 +24,7 @@
24
24
  playbackRate: ${o},
25
25
  playbackRateFactor: ${I},
26
26
  forwardBufferHealth: ${n},
27
- bitrateFactor: ${F},
27
+ bitrateFactor: ${N},
28
28
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
29
29
  droppedVideoMaxQualityLimit: ${c},
30
30
  stallsVideoMaxQualityLimit: ${p},
@@ -33,19 +33,19 @@
33
33
  minQualityLimit: ${i==null?void 0:i.min},
34
34
 
35
35
  [limited video tracks]
36
- ${(0,Fs.default)(Q).map(([P,K])=>`${P}: ${K}`).join(`
36
+ ${(0,qs.default)(Q).map(([P,K])=>`${P}: ${K}`).join(`
37
37
  `)||"All tracks are available"}
38
38
 
39
39
  [best video track] ${J==null?void 0:J.quality}
40
40
  [selected video track] ${W==null?void 0:W.quality}
41
- `}),db(r,m,W,l)},pb=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var I;(0,C.assertNotEmptyArray)(t,cb);let d=i.considerPlaybackRate&&(0,C.isNonNullable)(s)?s:1,c=[...t].sort(Pu(-1)),p=a.bitrate;(0,C.assertNonNullable)(p);let h=d*lb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,g=qs(a,e,t,i.minVideoAudioRatio),v=l||r;return(0,C.isNonNullable)(v)&&isFinite(v)&&(m=c.find(T=>(0,C.isNonNullable)(T.bitrate)&&(0,C.isNonNullable)(g==null?void 0:g.bitrate)?v-p>=T.bitrate*h&&T.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:`
41
+ `}),hb(r,m,W,l)},fb=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var I;(0,C.assertNotEmptyArray)(t,pb);let d=i.considerPlaybackRate&&(0,C.isNonNullable)(s)?s:1,c=[...t].sort(wu(-1)),p=a.bitrate;(0,C.assertNonNullable)(p);let h=d*db(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,g=Us(a,e,t,i.minVideoAudioRatio),v=l||r;return(0,C.isNonNullable)(v)&&isFinite(v)&&(m=c.find(T=>(0,C.isNonNullable)(T.bitrate)&&(0,C.isNonNullable)(g==null?void 0:g.bitrate)?v-p>=T.bitrate*h&&T.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:`
42
42
  [AUDIO TRACKS ABR]
43
43
  [available audio tracks]
44
44
  ${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
45
45
  `)}
46
46
 
47
47
  [tuning]
48
- ${(0,Fs.default)(i!=null?i:{}).map(([T,x])=>`${T}: ${x}`).join(`
48
+ ${(0,qs.default)(i!=null?i:{}).map(([T,x])=>`${T}: ${x}`).join(`
49
49
  `)}
50
50
 
51
51
  [limit params]
@@ -59,14 +59,14 @@
59
59
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
60
60
 
61
61
  [selected audio track] ${m==null?void 0:m.id}
62
- `}),m&&db(i,u,m,o)};var Se=a=>new URL(a).hostname;var B=require("@vkontakte/videoplayer-shared/es2015");var fb=X(ht(),1);var hb=a=>{if(a instanceof DOMException&&(0,fb.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"))},Oe=(a,e)=>O(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!hb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return hb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});var Ue=require("@vkontakte/videoplayer-shared/es2015");var mb=X(Fi(),1),bt=require("@vkontakte/videoplayer-shared/es2015");function ye(){return(0,bt.now)()}function Au(a){return ye()-a}function wu(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 Jr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",m=7e3,g=2e3,v=()=>{if(u)return;(0,bt.assertNonNullable)(d);let _=Au(d),ie;if(_<g){ie=g-_,setTimeout(v,ie);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,F()},I=_=>(s=_,te),T=_=>(c=_,te),x=()=>(h="json",te),A=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,c&&c(),t&&t()}},w=_=>(p=_,te),F=()=>{d=ye(),n=new i,n.open("get",a);let _=0,ie,U=0,ne=()=>((0,bt.assertNonNullable)(d),Math.max(d,Math.max(ie||0,U||0)));if(s&&n.addEventListener("progress",$=>{let P=ye();s.updateChunk&&$.loaded>_&&(s.updateChunk(ne(),$.loaded-_),_=$.loaded,ie=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(u)return;(0,bt.assertNonNullable)(n);let $=n.status;if($>=200&&$<300){if(n.response.byteLength&&s){let P=n.response.byteLength-_;P&&s.updateChunk&&s.updateChunk(ne(),P)}n.responseType==="json"&&!(0,mb.default)(n.response).length?A():(c&&c(),e(n.response))}else A()}),n.addEventListener("error",()=>{A()}),p){let $=()=>{(0,bt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(U=ye(),n.removeEventListener("readystatechange",$))};n.addEventListener("readystatechange",$)}return n.responseType=h,n.send(),te},te={withBitrateReporting:I,withParallel:w,withJSONResponse:x,withRetryCount:_=>(l=_,te),withRetryInterval:(_,ie)=>((0,bt.isNonNullable)(_)&&(g=_),(0,bt.isNonNullable)(ie)&&(m=ie),te),withTimeout:_=>(o=_,te),withFinally:T,send:F,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return te}var Hi=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=X(Fi(),1);var ji=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=ye(),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=ye()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Jr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ye()}_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=ye();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/es2015"),Us=1e4,ku=3;var Lw=6e4,Mw=10,Cw=1,Dw=500,Gi=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 Hi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=wu(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=wu(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 ji(ku,Us,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let A=s&&(!d||d===this.rep);return A||t("Not running!"),A},p=(A,w,F)=>{u&&u.abort(),u=Jr(this.urlResolver.resolve(A,!1),w,F,()=>this._retryCallback()).withTimeout(Us).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ku).withFinally(()=>{u=null}).send()},h=(A,w,F)=>{(0,Ue.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),w,F,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=A=>{let w=r.playbackRate;r.playbackRate!==A&&(t(`Playback rate switch: ${w}=>${A}`),r.playbackRate=A)},g=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let F=ye()-1e4,Q=0;for(let J=0;J<this.bufferStates.length;J++){let W=this.bufferStates[J];A=Math.min(A,W.buf),W.ts<F&&Q++}this.bufferStates.splice(0,Q),t(`update playback rate; minBuffer=${A} drop=${Q} jitter=${this.sourceJitter}`);let oe=A-Cw;this.sourceJitter>=0?oe-=this.sourceJitter/2:this.sourceJitter-=1,oe>3?m(1.15):oe>1?m(1.1):oe>.3?m(1.05):m(1)}},I=A=>{let w,F=()=>w&&w.start?w.start.length:0,Q=$=>w.start[$]/1e3,oe=$=>w.dur[$]/1e3,J=$=>w.fragIndex+$,W=($,P)=>({chunkIdx:J($),startTS:Q($),dur:oe($),discontinuity:P}),te=()=>{let $=0;if(w&&w.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,K=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=P;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let be=w.dur.length-1;for(;be>=0&&(Y-=w.dur[be],!(Y<=0));--be);$=Math.min(be,w.dur.length-1-K),$=Math.max($,0)}return W($,!0)},_=$=>{let P=F();if(!(P<=0)){if((0,Ue.isNonNullable)($)){for(let K=0;K<P;K++)if(Q(K)>$)return W(K)}return te()}},ie=$=>{let P=F(),K=$?$.chunkIdx+1:0,Y=K-w.fragIndex;if(!(P<=0)){if(!$||Y<0||Y-P>Mw)return t(`Resync: offset=${Y} bChunks=${P} chunk=`+JSON.stringify($)),te();if(!(Y>=P))return W(K-w.fragIndex,!1)}},U=($,P,K)=>{l&&l.abort(),l=Jr(this.urlResolver.resolve($,!0,this.lowLatency),P,K,()=>this._retryCallback()).withTimeout(Us).withRetryCount(ku).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,P)=>{U(A,K=>{if(!c())return;w=K;let Y=!!w.lowLatency;Y!==this.lowLatency&&g(Y);let be=0;for(let Ge=0;Ge<w.dur.length;++Ge)be+=w.dur[Ge];be>0&&((0,Ue.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(be/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,$(_(P))},()=>this._handleNetworkError())},nextChunk:ie}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ue.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:A=>{let{videoElement:w,logger:F}=this.params,Q=I(e.jidxUrl),oe,J,W,te,_=0,ie,U,ne,$=()=>{ie&&(clearTimeout(ie),ie=void 0);let re=Math.max(Dw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ie=_+re,Ee=ye(),Qe=Math.min(1e4,Ie-Ee);_=Ee;let Vt=()=>{l||c()&&Q.seek(()=>{c()&&(_=ye(),P(),$())})};Qe>0?ie=window.setTimeout(()=>{this.paused?$():Vt()},Qe):Vt()},P=()=>{let re;for(;re=Q.nextChunk(te);)te=re,Bt(re);let Ie=Q.nextChunk(W);if(Ie){if(W&&Ie.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?$():(T(),this._initPlayerWith(e));return}Ge(Ie)}else $()},K=(re,Ie)=>{if(!c()||!this.sourceBuffer)return;let Ee,Qe,Vt,Er=_t=>{window.setTimeout(()=>{c()&&K(re,Ie)},_t)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),Er(100);else{let _t=ye(),rr=w.currentTime;!this.paused&&w.buffered.length>1&&U===rr&&_t-ne>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),U!==rr&&(U=rr,ne=_t);let xr=this._getBufferSizeSec();if(xr>30)F(`Buffered ${xr} seconds; delaying appendBuffer`),Er(2e3);else try{this.sourceBuffer.appendBuffer(re),this.videoPlayStarted?(this.bufferStates.push({ts:_t,buf:xr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ie&&Ie()}catch(ui){if(ui.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),Vt=this.sourceBuffer.buffered.length,Vt!==0&&(Ee=this.sourceBuffer.buffered.start(0),Qe=rr,Qe-Ee>4&&this.sourceBuffer.remove(Ee,Qe-3)),Er(1e3);else throw ui}}},Y=()=>{J&&oe&&(F([`Appending chunk, sz=${J.byteLength}:`,JSON.stringify(W)]),K(J,function(){J=null,P()}))},be=re=>e.fragUrlTemplate.replace("%%id%%",re.chunkIdx),Ge=re=>{c()&&h(be(re),(Ie,Ee)=>{if(c()){if(Ee/=1e3,J=Ie,W=re,n=re.startTS,Ee){let Qe=Math.min(10,re.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Qe:Qe}Y()}},()=>this._handleNetworkError())},Bt=re=>{c()&&((0,Ue.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(be(re),!1)))},Ir=re=>{c()&&(e.cachedHeader=re,K(re,()=>{oe=!0,Y()}))};s=!0,Q.seek(re=>{if(c()){if(_=ye(),!re){$();return}te=re,!(0,Ue.isNullable)(A)||re.startTS>A?Ge(re):(W=re,P())}},A),e.cachedHeader?Ir(e.cachedHeader):p(e.headerUrl,Ir,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},d}_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=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/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(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let m=ye();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 c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Au(n)<3e4)return;r(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=ye();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=Jr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Us).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;Oe(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))},Lw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Sb=X(Fr(),1),ce=require("@vkontakte/videoplayer-shared/es2015"),Ru=class{constructor(){this.onDroopedVideoFramesLimit$=new ce.Subject;this.subscription=new ce.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ce.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,ce.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,ce.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,ce.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ce.interval)(this.droppedFramesChecker.checkTime).pipe((0,ce.filter)(()=>this.playing),(0,ce.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,ce.debounce)(this.droppedFramesChecker.checkTime)),r=(0,ce.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,ce.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}},Hs=Ru;var js=require("@vkontakte/videoplayer-shared/es2015"),yb=require("@vkontakte/videoplayer-shared/es2015");var Qi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Ow=(a,e)=>new js.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Qi()))},R(R({},r),e));i.observe(a);let s=(0,yb.fromEvent)(document,"visibilitychange").pipe((0,js.map)(n=>!document.hidden||Qi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ke=Ow;var Bw=["paused","playing","ready"],Vw=["paused","playing","ready"],Wi=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new j("stopped");this.representations$=new B.ValueSubject([]);this.textTracksManager=new ze;this.droppedFramesManager=new Hs;this.maxSeekBackTime$=new B.ValueSubject(1/0);this.zeroTime$=new B.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:B.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),d=(r=zt(u.name))!=null?r:(0,B.videoSizeToQuality)(u.video),c=u.bitrate/1e3,p=R({},u.video);if(!d)continue;let h={id:l,quality:d,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,B.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,$u.default)(Vw,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,$u.default)(Bw,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(we(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(we(this.params.source.url,u))}return;default:return(0,B.assertNever)(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:B.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,B.merge)(this.videoState.stateChangeStarted$.pipe((0,B.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,B.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Le(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(Se(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=De(this.video);this.subscription.add(this.representations$.pipe((0,B.map)(i=>i.map(({track:s})=>s)),(0,B.filter)(i=>!!i.length),(0,B.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,B.filterChanged)(),(0,B.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,B.combine)({zeroTime:this.zeroTime$.pipe((0,B.filter)(B.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(Ce(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ye(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(Ke(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&(0,B.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,B.assertNever)(i.to)}},t)).add((0,B.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.observableFrom)(["init"])).pipe((0,B.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 Gi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,p,h,m;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),r=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,B.isNonNullable)(t)?t:Jt(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,B.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,B.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(we(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Tb=Wi;var Hv=X(ht(),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 V=require("@vkontakte/videoplayer-shared/es2015");var Gs=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}},Xr=class extends Gs{constructor(){super(),this.listeners||Gs.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)}},Yi=class{constructor(){Object.defineProperty(this,"signal",{value:new Xr,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&&(Yi.prototype[Symbol.toStringTag]="AbortController",Xr.prototype[Symbol.toStringTag]="AbortSignal");function Qs(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 Lu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Qs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var zi=Qs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ib=zi?Lu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,kt=zi?Ib.fetch:window.fetch,OD=zi?Ib.Request:window.Request,He=zi?Yi:window.AbortController,BD=zi?Xr:window.AbortSignal;var al=X(Cu(),1);var tn=X(Kr(),1);var Rt=()=>window.ManagedMediaSource||window.MediaSource,Ws=()=>{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/es2015");var Je=document.createElement("video"),uk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',lk='video/mp4; codecs="hev1.1.6.L93.B0"',eg='video/webm; codecs="vp09.00.10.08"',tg='video/webm; codecs="av01.0.00M.08"',ck='audio/mp4; codecs="mp4a.40.2"',dk='audio/webm; codecs="opus"',jb,Gb,Ki={mms:Ws(),mse:Ub(),hls:!!((jb=Je.canPlayType)!=null&&jb.call(Je,"application/x-mpegurl")||(Gb=Je.canPlayType)!=null&&Gb.call(Je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Qb,Wb,Be={mp4:!!((Qb=Je.canPlayType)!=null&&Qb.call(Je,"video/mp4")),webm:!!((Wb=Je.canPlayType)!=null&&Wb.call(Je,"video/webm")),cmaf:!0},zs,Yb,Ks,zb,Js,Kb,Xs,Jb,Zs,Xb,en,Zb,Ve={h264:!!((Yb=(zs=Rt())==null?void 0:zs.isTypeSupported)!=null&&Yb.call(zs,uk)),h265:!!((zb=(Ks=Rt())==null?void 0:Ks.isTypeSupported)!=null&&zb.call(Ks,lk)),vp9:!!((Kb=(Js=Rt())==null?void 0:Js.isTypeSupported)!=null&&Kb.call(Js,eg)),av1:!!((Jb=(Xs=Rt())==null?void 0:Xs.isTypeSupported)!=null&&Jb.call(Xs,tg)),aac:!!((Xb=(Zs=Rt())==null?void 0:Zs.isTypeSupported)!=null&&Xb.call(Zs,ck)),opus:!!((Zb=(en=Rt())==null?void 0:en.isTypeSupported)!=null&&Zb.call(en,dk))},Zr=(Ve.h264||Ve.h265)&&Ve.aac,br,pk=()=>O(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(H(R({},a),{video:H(R({},a.video),{contentType:tg})})),window.navigator.mediaCapabilities.decodingInfo(H(R({},a),{video:H(R({},a.video),{contentType:eg})}))]);br={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{pk()}catch(a){console.error(a)}var ei=Ki.hls&&Be.mp4,rg=()=>Object.keys(Ve).filter(a=>Ve[a]),ig=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Ki.mse&&(!r||!!window.MediaStreamTrack)||Ki.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Be.mp4&&Zr;case"DASH_WEBM":return i&&Be.webm&&Ve.vp9&&Ve.opus;case"DASH_WEBM_AV1":return i&&Be.webm&&Ve.av1&&Ve.opus;case"DASH_STREAMS":return i&&(Be.mp4&&Zr||Be.webm&&(Ve.vp9||Ve.av1)&&(Ve.opus||Ve.aac));case"DASH_LIVE":return i&&Be.mp4&&Zr;case"DASH_LIVE_CMAF":return i&&Be.mp4&&Zr&&Be.cmaf;case"DASH_ONDEMAND":return i&&Be.mp4&&Zr;case"HLS":case"HLS_ONDEMAND":return ei||e&&i&&Be.mp4&&Zr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ei;case"MPEG":return Be.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ki.webrtc&&Ki.ws&&Ve.h264&&(Be.mp4||Be.webm);default:return(0,vt.assertNever)(s)}})},Ys=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 br?br[t].smooth?[t,e]:br[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return br?br[t].powerEfficient?[t,e]:br[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"]:[],...Ys(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",...Ys(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ys(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ys(a),...i,"HLS","HLS_ONDEMAND"];default:(0,vt.assertNever)(e)}return ei?[...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 ei&&!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"]},Du=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,tn.default)(t.value.split("."),0)}for(let t of a){let r=(0,tn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,tn.default)(e.value.split("."),0)};var wg=X(Ag(),1),ti=require("@vkontakte/videoplayer-shared/es2015"),kg=a=>{if(!a)return{id:"EmptyResponse",category:ti.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ti.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,wg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ti.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:ti.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ti.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/es2015");var rn=X(ht(),1),si=X(Kr(),1),an=X(Cu(),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)},$k=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),Nu=$g?Rk:window.requestIdleCallback,Xi=$g?$k:window.cancelIdleCallback;var Ov=X(Bs(),1);var Xe=require("@vkontakte/videoplayer-shared/es2015");var Lk=18,Lg=!1;try{Lg=Xe.clientChecker.isSafari&&!!Xe.clientChecker.macVersion&&Xe.clientChecker.macVersion<=Lk}catch(a){console.error(a)}var Fu=class{constructor(e){this.bufferFull$=new Xe.Subject;this.error$=new Xe.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Xe.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return O(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return O(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return O(this,null,function*(){return new Promise(t=>{let r;Lg&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category: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=Fu;var qu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var E=require("@vkontakte/videoplayer-shared/es2015");var ae=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 ri=class extends ae{};var Zi=class extends ae{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 ea=class extends ae{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 ta=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var de=class extends ae{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ra=class extends de{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 ia=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var aa=class extends ae{constructor(e,t){super(e,t),this.data=this.content}};var gr=class extends de{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 sa=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var na=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends de{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 ua=class extends de{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var la=class extends de{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ca=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends de{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 pa=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ha=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends de{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ma=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ba=class extends de{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 ga=class extends de{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 va=class extends de{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 Ck={ftyp:ea,moov:ta,mvhd:ra,moof:ia,mdat:aa,sidx:gr,trak:sa,mdia:ca,mfhd:fa,tkhd:da,traf:ma,tfhd:ba,tfdt:ga,trun:va,minf:pa,sv3d:na,st3d:oa,prhd:ua,proj:ha,equi:la,uuid:Zi,unknown:ri},$t=class a{constructor(e={}){this.options=R({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=Ck[e];return r?new r(t,new a):new ri(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 Ok=new TextDecoder("ascii"),Bk=a=>Ok.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Vk=a=>{let e=new gr(a,new $t),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 $t().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,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},Nk=a=>{let t=new $t().parse(a),r=new Zt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},Fk=a=>{var i;let t=new $t().parse(a);return(i=new Zt(t).find("sidx"))==null?void 0:i.timescale},qk=(a,e)=>{let r=new $t().parse(a),s=new Zt(r).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},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 $t().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},Cg={validateData:Bk,parseInit:Uk,getIndexRange:()=>{},parseSegments:Vk,parseFeedableSegmentChunk:_k,getChunkEndTime:qk,getServerLatencyTimestamps:Nk,getTimescaleFromIndex:Fk};var ya=X(ht(),1),Lt=require("@vkontakte/videoplayer-shared/es2015");var Og=require("@vkontakte/videoplayer-shared/es2015");var Dg={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Bg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Sa(a,t),i=r in Dg,s=i?Dg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=Sa(u),c=l*ct(2,(o-1)*8)+d,p=t+o,h;return p+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,c),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Sa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*ct(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*ct(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*ct(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},nt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Sa(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)}},vr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Bg(r);if(!e(i))return;i.type==="master"&&vr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Vg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Bg(a);return vr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=nt(o,n):s===17026?t=nt(o,n):s===17029&&(r=nt(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],Hk=[231,22612,22743,167,171,163,160,175],jk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return vr(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let v=nt(m,h);l=Sa(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=nt(m,h):p===17545?i=nt(m,h):p===21420&&l===475249515?u=nt(m,h):p===374648427?vr(m,({tag:v,type:I,value:T})=>v===30321?(d=nt(T,I)===1,!1):!0):s&&n&&(0,ya.default)(_g,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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Gk=a=>{if((0,Lt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Qk=(a,e)=>{let t=!1,r=!1,i=o=>(0,Lt.isNonNullable)(o.time)&&(0,Lt.isNonNullable)(o.position),s=[],n;return vr(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=nt(l,u));break;case 183:break;case 241:n&&(n.position=nt(l,u));break;default:t&&(0,ya.default)(_g,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Wk=a=>{let e=0,t=!1;try{vr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ya.default)(Hk,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ya.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:Vg,parseInit:jk,getIndexRange:Gk,parseSegments:Qk,parseFeedableSegmentChunk:Wk};var Ta=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 Cg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var zu=X(sv(),1),Av=X(Fr(),1),wv=X(Tv(),1),kv=X(Kr(),1);var Iv=X(ht(),1),Yu=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 ai=require("@vkontakte/videoplayer-shared/es2015");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=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})+",d=`^(?:(?<langtag>${`
62
+ `}),m&&hb(i,u,m,o)};var Se=a=>new URL(a).hostname;var V=require("@vkontakte/videoplayer-shared/es2015");var bb=X(ft(),1);var mb=a=>{if(a instanceof DOMException&&(0,bb.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"))},Oe=(a,e)=>O(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!mb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return mb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});var He=require("@vkontakte/videoplayer-shared/es2015");var gb=X(qi(),1),gt=require("@vkontakte/videoplayer-shared/es2015");function ye(){return(0,gt.now)()}function ku(a){return ye()-a}function Ru(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 vb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Xr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",m=7e3,g=2e3,v=()=>{if(u)return;(0,gt.assertNonNullable)(d);let B=ku(d),ie;if(B<g){ie=g-B,setTimeout(v,ie);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new i,N()},I=B=>(s=B,te),T=B=>(c=B,te),x=()=>(h="json",te),A=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,c&&c(),t&&t()}},w=B=>(p=B,te),N=()=>{d=ye(),n=new i,n.open("get",a);let B=0,ie,U=0,ne=()=>((0,gt.assertNonNullable)(d),Math.max(d,Math.max(ie||0,U||0)));if(s&&n.addEventListener("progress",$=>{let P=ye();s.updateChunk&&$.loaded>B&&(s.updateChunk(ne(),$.loaded-B),B=$.loaded,ie=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(u)return;(0,gt.assertNonNullable)(n);let $=n.status;if($>=200&&$<300){if(n.response.byteLength&&s){let P=n.response.byteLength-B;P&&s.updateChunk&&s.updateChunk(ne(),P)}n.responseType==="json"&&!(0,gb.default)(n.response).length?A():(c&&c(),e(n.response))}else A()}),n.addEventListener("error",()=>{A()}),p){let $=()=>{(0,gt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(U=ye(),n.removeEventListener("readystatechange",$))};n.addEventListener("readystatechange",$)}return n.responseType=h,n.send(),te},te={withBitrateReporting:I,withParallel:w,withJSONResponse:x,withRetryCount:B=>(l=B,te),withRetryInterval:(B,ie)=>((0,gt.isNonNullable)(B)&&(g=B),(0,gt.isNonNullable)(ie)&&(m=ie),te),withTimeout:B=>(o=B,te),withFinally:T,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return te}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 Sb=X(qi(),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=ye(),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=ye()-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=Xr(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=ye()}_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=ye();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,Sb.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 yb=require("@vkontakte/videoplayer-shared/es2015"),Hs=1e4,$u=3;var Cw=6e4,Dw=10,Ow=1,Vw=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 yb.Subject,this.chunkRateEstimator=new ji(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ru(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}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=Ru(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,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,He.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=()=>{vb(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($u,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,d=!1,c=()=>{let A=s&&(!d||d===this.rep);return A||t("Not running!"),A},p=(A,w,N)=>{u&&u.abort(),u=Xr(this.urlResolver.resolve(A,!1),w,N,()=>this._retryCallback()).withTimeout(Hs).withBitrateReporting(this.bitrateSwitcher).withRetryCount($u).withFinally(()=>{u=null}).send()},h=(A,w,N)=>{(0,He.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),w,N,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=A=>{let w=r.playbackRate;r.playbackRate!==A&&(t(`Playback rate switch: ${w}=>${A}`),r.playbackRate=A)},g=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let N=ye()-1e4,Q=0;for(let J=0;J<this.bufferStates.length;J++){let W=this.bufferStates[J];A=Math.min(A,W.buf),W.ts<N&&Q++}this.bufferStates.splice(0,Q),t(`update playback rate; minBuffer=${A} drop=${Q} jitter=${this.sourceJitter}`);let oe=A-Ow;this.sourceJitter>=0?oe-=this.sourceJitter/2:this.sourceJitter-=1,oe>3?m(1.15):oe>1?m(1.1):oe>.3?m(1.05):m(1)}},I=A=>{let w,N=()=>w&&w.start?w.start.length:0,Q=$=>w.start[$]/1e3,oe=$=>w.dur[$]/1e3,J=$=>w.fragIndex+$,W=($,P)=>({chunkIdx:J($),startTS:Q($),dur:oe($),discontinuity:P}),te=()=>{let $=0;if(w&&w.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,K=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=P;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let be=w.dur.length-1;for(;be>=0&&(Y-=w.dur[be],!(Y<=0));--be);$=Math.min(be,w.dur.length-1-K),$=Math.max($,0)}return W($,!0)},B=$=>{let P=N();if(!(P<=0)){if((0,He.isNonNullable)($)){for(let K=0;K<P;K++)if(Q(K)>$)return W(K)}return te()}},ie=$=>{let P=N(),K=$?$.chunkIdx+1:0,Y=K-w.fragIndex;if(!(P<=0)){if(!$||Y<0||Y-P>Dw)return t(`Resync: offset=${Y} bChunks=${P} chunk=`+JSON.stringify($)),te();if(!(Y>=P))return W(K-w.fragIndex,!1)}},U=($,P,K)=>{l&&l.abort(),l=Xr(this.urlResolver.resolve($,!0,this.lowLatency),P,K,()=>this._retryCallback()).withTimeout(Hs).withRetryCount($u).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,P)=>{U(A,K=>{if(!c())return;w=K;let Y=!!w.lowLatency;Y!==this.lowLatency&&g(Y);let be=0;for(let Qe=0;Qe<w.dur.length;++Qe)be+=w.dur[Qe];be>0&&((0,He.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(be/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,$(B(P))},()=>this._handleNetworkError())},nextChunk:ie}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,He.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:A=>{let{videoElement:w,logger:N}=this.params,Q=I(e.jidxUrl),oe,J,W,te,B=0,ie,U,ne,$=()=>{ie&&(clearTimeout(ie),ie=void 0);let re=Math.max(Vw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ie=B+re,Ee=ye(),We=Math.min(1e4,Ie-Ee);B=Ee;let _t=()=>{l||c()&&Q.seek(()=>{c()&&(B=ye(),P(),$())})};We>0?ie=window.setTimeout(()=>{this.paused?$():_t()},We):_t()},P=()=>{let re;for(;re=Q.nextChunk(te);)te=re,Bt(re);let Ie=Q.nextChunk(W);if(Ie){if(W&&Ie.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?$():(T(),this._initPlayerWith(e));return}Qe(Ie)}else $()},K=(re,Ie)=>{if(!c()||!this.sourceBuffer)return;let Ee,We,_t,xr=Nt=>{window.setTimeout(()=>{c()&&K(re,Ie)},Nt)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),xr(100);else{let Nt=ye(),ir=w.currentTime;!this.paused&&w.buffered.length>1&&U===ir&&Nt-ne>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),U!==ir&&(U=ir,ne=Nt);let Pr=this._getBufferSizeSec();if(Pr>30)N(`Buffered ${Pr} seconds; delaying appendBuffer`),xr(2e3);else try{this.sourceBuffer.appendBuffer(re),this.videoPlayStarted?(this.bufferStates.push({ts:Nt,buf:Pr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ie&&Ie()}catch(li){if(li.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),_t=this.sourceBuffer.buffered.length,_t!==0&&(Ee=this.sourceBuffer.buffered.start(0),We=ir,We-Ee>4&&this.sourceBuffer.remove(Ee,We-3)),xr(1e3);else throw li}}},Y=()=>{J&&oe&&(N([`Appending chunk, sz=${J.byteLength}:`,JSON.stringify(W)]),K(J,function(){J=null,P()}))},be=re=>e.fragUrlTemplate.replace("%%id%%",re.chunkIdx),Qe=re=>{c()&&h(be(re),(Ie,Ee)=>{if(c()){if(Ee/=1e3,J=Ie,W=re,n=re.startTS,Ee){let We=Math.min(10,re.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*We:We}Y()}},()=>this._handleNetworkError())},Bt=re=>{c()&&((0,He.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(be(re),!1)))},Er=re=>{c()&&(e.cachedHeader=re,K(re,()=>{oe=!0,Y()}))};s=!0,Q.seek(re=>{if(c()){if(B=ye(),!re){$();return}te=re,!(0,He.isNullable)(A)||re.startTS>A?Qe(re):(W=re,P())}},A),e.cachedHeader?Er(e.cachedHeader):p(e.headerUrl,Er,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,He.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,He.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,He.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=c=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),m=c/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(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let m=ye();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 c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&ku(n)<3e4)return;r(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=ye();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=Xr(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;Oe(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))},Cw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Tb=X(qr(),1),ce=require("@vkontakte/videoplayer-shared/es2015"),Lu=class{constructor(){this.onDroopedVideoFramesLimit$=new ce.Subject;this.subscription=new ce.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new ce.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,ce.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,ce.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,ce.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,ce.interval)(this.droppedFramesChecker.checkTime).pipe((0,ce.filter)(()=>this.playing),(0,ce.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,ce.debounce)(this.droppedFramesChecker.checkTime)),r=(0,ce.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,Tb.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,ce.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=Lu;var Gs=require("@vkontakte/videoplayer-shared/es2015"),Ib=require("@vkontakte/videoplayer-shared/es2015");var Wi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Bw=(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(R({},r),e));i.observe(a);let s=(0,Ib.fromEvent)(document,"visibilitychange").pipe((0,Gs.map)(n=>!document.hidden||Wi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Je=Bw;var _w=["paused","playing","ready"],Nw=["paused","playing","ready"],Yi=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new j("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new Ke;this.droppedFramesManager=new js;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new At;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),d=(r=Kt(u.name))!=null?r:(0,V.videoSizeToQuality)(u.video),c=u.bitrate/1e3,p=R({},u.video);if(!d)continue;let h={id:l,quality:d,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(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,Mu.default)(Nw,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Mu.default)(_w,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(we(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(we(this.params.source.url,u))}return;default:return(0,V.assertNever)(e)}};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=Le(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(Se(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=De(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(bt(this.video,this.params.desiredState.isLooped,t)).add(Ce(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(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(Je(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 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,d,c,p,h,m;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),r=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,V.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=(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(we(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Eb=Yi;var Gv=X(ft(),1);var vt=(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 q=require("@vkontakte/videoplayer-shared/es2015");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}},Zr=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 Zr,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",Zr.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 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(!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,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,m)=>{d.addEventListener("abort",()=>m(c),{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}),xb=Ki?Cu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Rt=Ki?xb.fetch:window.fetch,BD=Ki?xb.Request:window.Request,je=Ki?zi:window.AbortController,_D=Ki?Zr:window.AbortSignal;var nl=X(Ou(),1);var rn=X(Jr(),1);var $t=()=>window.ManagedMediaSource||window.MediaSource,Ys=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},jb=()=>{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 St=require("@vkontakte/videoplayer-shared/es2015");var Xe=document.createElement("video"),ck='video/mp4; codecs="avc1.42000a,mp4a.40.2"',dk='video/mp4; codecs="hev1.1.6.L93.B0"',rg='video/webm; codecs="vp09.00.10.08"',ig='video/webm; codecs="av01.0.00M.08"',pk='audio/mp4; codecs="mp4a.40.2"',hk='audio/webm; codecs="opus"',Qb,Wb,Ji={mms:Ys(),mse:jb(),hls:!!((Qb=Xe.canPlayType)!=null&&Qb.call(Xe,"application/x-mpegurl")||(Wb=Xe.canPlayType)!=null&&Wb.call(Xe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Yb,zb,Ve={mp4:!!((Yb=Xe.canPlayType)!=null&&Yb.call(Xe,"video/mp4")),webm:!!((zb=Xe.canPlayType)!=null&&zb.call(Xe,"video/webm")),cmaf:!0},Ks,Kb,Js,Jb,Xs,Xb,Zs,Zb,en,eg,tn,tg,Be={h264:!!((Kb=(Ks=$t())==null?void 0:Ks.isTypeSupported)!=null&&Kb.call(Ks,ck)),h265:!!((Jb=(Js=$t())==null?void 0:Js.isTypeSupported)!=null&&Jb.call(Js,dk)),vp9:!!((Xb=(Xs=$t())==null?void 0:Xs.isTypeSupported)!=null&&Xb.call(Xs,rg)),av1:!!((Zb=(Zs=$t())==null?void 0:Zs.isTypeSupported)!=null&&Zb.call(Zs,ig)),aac:!!((eg=(en=$t())==null?void 0:en.isTypeSupported)!=null&&eg.call(en,pk)),opus:!!((tg=(tn=$t())==null?void 0:tn.isTypeSupported)!=null&&tg.call(tn,hk))},ei=(Be.h264||Be.h265)&&Be.aac,gr,fk=()=>O(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(H(R({},a),{video:H(R({},a.video),{contentType:ig})})),window.navigator.mediaCapabilities.decodingInfo(H(R({},a),{video:H(R({},a.video),{contentType:rg})}))]);gr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{fk()}catch(a){console.error(a)}var ti=Ji.hls&&Ve.mp4,ag=()=>Object.keys(Be).filter(a=>Be[a]),sg=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Ji.mse&&(!r||!!window.MediaStreamTrack)||Ji.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Ve.mp4&&ei;case"DASH_WEBM":return i&&Ve.webm&&Be.vp9&&Be.opus;case"DASH_WEBM_AV1":return i&&Ve.webm&&Be.av1&&Be.opus;case"DASH_STREAMS":return i&&(Ve.mp4&&ei||Ve.webm&&(Be.vp9||Be.av1)&&(Be.opus||Be.aac));case"DASH_LIVE":return i&&Ve.mp4&&ei;case"DASH_LIVE_CMAF":return i&&Ve.mp4&&ei&&Ve.cmaf;case"DASH_ONDEMAND":return i&&Ve.mp4&&ei;case"HLS":case"HLS_ONDEMAND":return ti||e&&i&&Ve.mp4&&ei;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ti;case"MPEG":return Ve.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ji.webrtc&&Ji.ws&&Be.h264&&(Ve.mp4||Ve.webm);default:return(0,St.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 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,St.assertNever)(a)}return[e,t]},ng=({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(St.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,St.assertNever)(e)}return ti?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},og=({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=St.clientChecker.isMac&&St.clientChecker.isSafari;if(St.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,St.assertNever)(a)}else ti&&!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"]},Vu=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ug=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 Rg=X(kg(),1),ri=require("@vkontakte/videoplayer-shared/es2015"),$g=a=>{if(!a)return{id:"EmptyResponse",category:ri.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ri.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,Rg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ri.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:ri.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ri.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Zt=(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/es2015");var an=X(ft(),1),ni=X(Jr(),1),sn=X(Ou(),1);var Lk=(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)},Mk=a=>window.clearTimeout(a),Lg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Mg=!Lg(window.requestIdleCallback)||!Lg(window.cancelIdleCallback),qu=Mg?Lk:window.requestIdleCallback,Zi=Mg?Mk:window.cancelIdleCallback;var Bv=X(Bs(),1);var Ze=require("@vkontakte/videoplayer-shared/es2015");var Ck=18,Cg=!1;try{Cg=Ze.clientChecker.isSafari&&!!Ze.clientChecker.macVersion&&Ze.clientChecker.macVersion<=Ck}catch(a){console.error(a)}var Uu=class{constructor(e){this.bufferFull$=new Ze.Subject;this.error$=new Ze.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Ze.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return O(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return O(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return O(this,null,function*(){return new Promise(t=>{let r;Cg&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Ze.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,Ze.assertNever)(t)}}},Dg=Uu;var Hu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var E=require("@vkontakte/videoplayer-shared/es2015");var ae=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 ii=class extends ae{};var ea=class extends ae{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 ae{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 ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var de=class extends ae{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ia=class extends de{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 ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends ae{constructor(e,t){super(e,t),this.data=this.content}};var vr=class extends de{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 ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ua=class extends de{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 de{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ca=class extends de{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 ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pa=class extends de{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 ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ma=class extends de{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ba=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ga=class extends de{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 de{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 de{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 Ok={ftyp:ta,moov:ra,mvhd:ia,moof:aa,mdat:sa,sidx:vr,trak:na,mdia:da,mfhd:ma,tkhd:pa,traf:ba,tfhd:ga,tfdt:va,trun:Sa,minf:ha,sv3d:oa,st3d:ua,prhd:la,proj:fa,equi:ca,uuid:ea,unknown:ii},Lt=class a{constructor(e={}){this.options=R({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=Ok[e];return r?new r(t,new a):new ii(t,new a)}};var er=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 Bk=new TextDecoder("ascii"),_k=a=>Bk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Nk=a=>{let e=new vr(a,new Lt),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})},Fk=(a,e)=>{let r=new Lt().parse(a),i=new er(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},qk=a=>{let t=new Lt().parse(a),r=new er(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},Uk=a=>{var i;let t=new Lt().parse(a);return(i=new er(t).find("sidx"))==null?void 0:i.timescale},Hk=(a,e)=>{let r=new Lt().parse(a),s=new er(r).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},jk=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 Lt().parse(a),i=new er(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:_k,parseInit:jk,getIndexRange:()=>{},parseSegments:Nk,parseFeedableSegmentChunk:Fk,getChunkEndTime:Hk,getServerLatencyTimestamps:qk,getTimescaleFromIndex:Uk};var Ta=X(ft(),1),Mt=require("@vkontakte/videoplayer-shared/es2015");var Bg=require("@vkontakte/videoplayer-shared/es2015");var Vg={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"}},_g=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 Vg,s=i?Vg[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=ya(u),c=l*dt(2,(o-1)*8)+d,p=t+o,h;return p+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,c),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},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)*dt(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*dt(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*dt(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},ot=(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,Bg.assertNever)(e)}},Sr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=_g(r);if(!e(i))return;i.type==="master"&&Sr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Ng=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=_g(a);return Sr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=ot(o,n):s===17026?t=ot(o,n):s===17029&&(r=ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Fg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Gk=[231,22612,22743,167,171,163,160,175],Qk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return Sr(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let v=ot(m,h);l=ya(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=ot(m,h):p===17545?i=ot(m,h):p===21420&&l===475249515?u=ot(m,h):p===374648427?Sr(m,({tag:v,type:I,value:T})=>v===30321?(d=ot(T,I)===1,!1):!0):s&&n&&(0,Ta.default)(Fg,p)&&(o=!0),!o}),(0,Mt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Mt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Mt.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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Wk=a=>{if((0,Mt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Yk=(a,e)=>{let t=!1,r=!1,i=o=>(0,Mt.isNonNullable)(o.time)&&(0,Mt.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=ot(l,u));break;case 183:break;case 241:n&&(n.position=ot(l,u));break;default:t&&(0,Ta.default)(Fg,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},zk=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,Ta.default)(Gk,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},qg={validateData:Ng,parseInit:Qk,getIndexRange:Wk,parseSegments:Yk,parseFeedableSegmentChunk:zk};var Ia=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return qg;case"mp4":return Og}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ju=X(ov(),1),kv=X(qr(),1),Rv=X(Ev(),1),$v=X(Jr(),1);var xv=X(ft(),1),Ku=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,xv.default)(["6E","7A","F4"],o)}}return!1};var si=require("@vkontakte/videoplayer-shared/es2015");var Pv=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=jR(),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 jR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
63
63
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
64
64
  (-(?<script>[a-z]{4}))?
65
65
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
66
66
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
67
67
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
68
68
  (?:-(?<privateuse>(?:${e})))?
69
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Pv=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Mt=(a,e)=>{let t=a;t=(0,zu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Av.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,zu.default)(t,n,(o,u)=>(0,ai.isNullable)(s)?o:(0,ai.isNullable)(u)?s:(0,wv.default)(s,parseInt(u,10),"0"))}return t},Rv=(a,e)=>{var w,F,Q,oe,J,W,te,_,ie,U,ne,$,P,K,Y,be,Ge,Bt,Ir,re,Ie,Ee,Qe,Vt,Er,_t,rr,xr,ui,hl,fl,ml,bl,gl,vl,Sl,yl,Tl,Il,El,xl,Pl,Al,wl,kl,Rl,$l,Ll,Ml,Cl,Dl,Ol,Bl,Vl,_l,Nl,Fl,ql,Ul,Hl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(xe=>{var Ua,Nt;return(Nt=(Ua=xe.textContent)==null?void 0:Ua.trim())!=null?Nt:""}),u=(w=(0,kv.default)(o,0))!=null?w:"",l=n.children,d=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,h,m=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),v=s.getElementsByTagName("vk:Attrs")[0],I=v==null?void 0:v.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)h=Pv(m);else if(g){let xe=Pv(g);(0,ai.isNonNullable)(xe)&&(h=xe)}else I&&(h=parseInt(I,10));let T=0,x=(Q=(F=s.getAttribute("profiles"))==null?void 0:F.split(","))!=null?Q:[];for(let xe of l){let Ua=(oe=xe.getAttribute("id"))!=null?oe:"id"+(T++).toString(10),Nt=(J=xe.getAttribute("mimeType"))!=null?J:"",vn=(W=xe.getAttribute("codecs"))!=null?W:"",Sn=(te=xe.getAttribute("contentType"))!=null?te:Nt==null?void 0:Nt.split("/")[0],hS=(ie=(_=xe.getAttribute("profiles"))==null?void 0:_.split(","))!=null?ie:[],jl=(ne=xv((U=xe.getAttribute("lang"))!=null?U:""))!=null?ne:{},fS=(K=(P=($=xe.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:P.trim())!=null?K:void 0,mS=xe.querySelectorAll("Representation"),bS=xe.querySelector("SegmentTemplate"),gS=(be=(Y=xe.querySelector("Role"))==null?void 0:Y.getAttribute("value"))!=null?be:void 0,li=Sn,ge={id:Ua,language:jl.language,isDefault:gS==="main",label:fS,codecs:vn,hdr:li==="video"&&Yu(vn),mime:Nt,representations:[]};for(let ue of mS){let vS=(Ge=ue.getAttribute("lang"))!=null?Ge:void 0,SS=(Bt=ue.getAttribute("label"))!=null?Bt:void 0,yS=(Ie=(re=(Ir=ue.querySelector("BaseURL"))==null?void 0:Ir.textContent)==null?void 0:re.trim())!=null?Ie:"",Ha=new URL(yS||u,e).toString(),Pr=(Ee=ue.getAttribute("mimeType"))!=null?Ee:Nt,ja=(Vt=(Qe=ue.getAttribute("codecs"))!=null?Qe:vn)!=null?Vt:"",Ga;if(Sn==="text"){let Ft=ue.getAttribute("id")||"",Qa=((Er=jl.privateuse)==null?void 0:Er.includes("x-auto"))||Ft.includes("_auto"),ir=ue.querySelector("SegmentTemplate");if(ir){let ci={representationId:(_t=ue.getAttribute("id"))!=null?_t:void 0,bandwidth:(rr=ue.getAttribute("bandwidth"))!=null?rr:void 0},Wa=parseInt((xr=ue.getAttribute("bandwidth"))!=null?xr:"",10)/1e3,Ya=(hl=parseInt((ui=ir.getAttribute("startNumber"))!=null?ui:"",10))!=null?hl:1,Ar=parseInt((fl=ir.getAttribute("timescale"))!=null?fl:"",10),yn=(ml=ir.querySelectorAll("SegmentTimeline S"))!=null?ml:[],wr=ir.getAttribute("media");if(!wr)continue;let za=[],Ka=0,Ja="",kr=0,di=Ya,ke=0;for(let et of yn){let ar=parseInt((bl=et.getAttribute("d"))!=null?bl:"",10),We=parseInt((gl=et.getAttribute("r"))!=null?gl:"",10)||0,qt=parseInt((vl=et.getAttribute("t"))!=null?vl:"",10);ke=Number.isFinite(qt)?qt:ke;let sr=ar/Ar*1e3,Ut=ke/Ar*1e3;for(let ut=0;ut<We+1;ut++){let Ht=Mt(wr,H(R({},ci),{segmentNumber:di.toString(10),segmentTime:(ke+ut*ar).toString(10)})),Rr=(Ut!=null?Ut:0)+ut*sr,hi=Rr+sr;di++,za.push({time:{from:Rr,to:hi},url:Ht})}ke+=(We+1)*ar,Ka+=(We+1)*sr}kr=ke/Ar*1e3,Ja=Mt(wr,H(R({},ci),{segmentNumber:di.toString(10),segmentTime:ke.toString(10)}));let pi={time:{from:kr,to:1/0},url:Ja},yt={type:"template",baseUrl:Ha,segmentTemplateUrl:wr,initUrl:"",totalSegmentsDurationMs:Ka,segments:za,nextSegmentBeyondManifest:pi,timescale:Ar};Ga={id:Ft,kind:"text",segmentReference:yt,profiles:[],duration:h,bitrate:Wa,mime:"",codecs:"",width:0,height:0,isAuto:Qa}}else Ga={id:Ft,isAuto:Qa,kind:"text",url:Ha}}else{let Ft=(yl=(Sl=ue.getAttribute("contentType"))!=null?Sl:Pr==null?void 0:Pr.split("/")[0])!=null?yl:Sn,Qa=(Il=(Tl=xe.getAttribute("profiles"))==null?void 0:Tl.split(","))!=null?Il:[],ir=parseInt((El=ue.getAttribute("width"))!=null?El:"",10),ci=parseInt((xl=ue.getAttribute("height"))!=null?xl:"",10),Wa=parseInt((Pl=ue.getAttribute("bandwidth"))!=null?Pl:"",10)/1e3,Ya=(Al=ue.getAttribute("frameRate"))!=null?Al:"",Ar=(wl=ue.getAttribute("quality"))!=null?wl:void 0,yn=Ya?Ev(Ya):void 0,wr=(kl=ue.getAttribute("id"))!=null?kl:"id"+(T++).toString(10),za=Ft==="video"?`${ci}p`:Ft==="audio"?`${Wa}Kbps`:ja,Ka=`${wr}@${za}`,Ja=[...x,...hS,...Qa],kr,di=ue.querySelector("SegmentBase"),ke=(Rl=ue.querySelector("SegmentTemplate"))!=null?Rl:bS;if(di){let yt=(Ll=($l=ue.querySelector("SegmentBase Initialization"))==null?void 0:$l.getAttribute("range"))!=null?Ll:"",[et,ar]=yt.split("-").map(Ht=>parseInt(Ht,10)),We={from:et,to:ar},qt=(Ml=ue.querySelector("SegmentBase"))==null?void 0:Ml.getAttribute("indexRange"),[sr,Ut]=qt?qt.split("-").map(Ht=>parseInt(Ht,10)):[],ut=qt?{from:sr,to:Ut}:void 0;kr={type:"byteRange",url:Ha,initRange:We,indexRange:ut}}else if(ke){let yt={representationId:(Cl=ue.getAttribute("id"))!=null?Cl:void 0,bandwidth:(Dl=ue.getAttribute("bandwidth"))!=null?Dl:void 0},et=parseInt((Ol=ke.getAttribute("timescale"))!=null?Ol:"",10),ar=(Bl=ke.getAttribute("initialization"))!=null?Bl:"",We=ke.getAttribute("media"),qt=(_l=parseInt((Vl=ke.getAttribute("startNumber"))!=null?Vl:"",10))!=null?_l:1,sr=Mt(ar,yt);if(!We)throw new ReferenceError("No media attribute in SegmentTemplate");let Ut=(Nl=ke.querySelectorAll("SegmentTimeline S"))!=null?Nl:[],ut=[],Ht=0,Rr="",hi=0;if(Ut.length){let Xa=qt,tt=0;for(let $r of Ut){let lt=parseInt((Fl=$r.getAttribute("d"))!=null?Fl:"",10),nr=parseInt((ql=$r.getAttribute("r"))!=null?ql:"",10)||0,Za=parseInt((Ul=$r.getAttribute("t"))!=null?Ul:"",10);tt=Number.isFinite(Za)?Za:tt;let Tn=lt/et*1e3,In=tt/et*1e3;for(let es=0;es<nr+1;es++){let IS=Mt(We,H(R({},yt),{segmentNumber:Xa.toString(10),segmentTime:(tt+es*lt).toString(10)})),Gl=(In!=null?In:0)+es*Tn,ES=Gl+Tn;Xa++,ut.push({time:{from:Gl,to:ES},url:IS})}tt+=(nr+1)*lt,Ht+=(nr+1)*Tn}hi=tt/et*1e3,Rr=Mt(We,H(R({},yt),{segmentNumber:Xa.toString(10),segmentTime:tt.toString(10)}))}else if((0,ai.isNonNullable)(h)){let tt=parseInt((Hl=ke.getAttribute("duration"))!=null?Hl:"",10)/et*1e3,$r=Math.ceil(h/tt),lt=0;for(let nr=1;nr<$r;nr++){let Za=Mt(We,H(R({},yt),{segmentNumber:nr.toString(10),segmentTime:lt.toString(10)}));ut.push({time:{from:lt,to:lt+tt},url:Za}),lt+=tt}hi=lt,Rr=Mt(We,H(R({},yt),{segmentNumber:$r.toString(10),segmentTime:lt.toString(10)}))}let TS={time:{from:hi,to:1/0},url:Rr};kr={type:"template",baseUrl:Ha,segmentTemplateUrl:We,initUrl:sr,totalSegmentsDurationMs:Ht,segments:ut,nextSegmentBeyondManifest:TS,timescale:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ft||!Pr)continue;let pi={video:"video",audio:"audio",text:"text"}[Ft];if(!pi)continue;li||(li=pi),Ga={id:Ka,kind:pi,segmentReference:kr,profiles:Ja,duration:h,bitrate:Wa,mime:Pr,codecs:ja,width:ir,height:ci,fps:yn,quality:Ar}}ge.language||(ge.language=vS),ge.label||(ge.label=SS),ge.mime||(ge.mime=Pr),ge.codecs||(ge.codecs=ja),ge.hdr||(ge.hdr=li==="video"&&Yu(ja)),ge.representations.push(Ga)}li&&i[li].push(ge)}return{dynamic:d,liveAvailabilityStartTime:p,duration:h,streams:i,baseUrls:o}};var Xu=X(Kr(),1);var $v=require("@vkontakte/videoplayer-shared/es2015"),Lv=({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,$v.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Mv=({id:a,bitrate:e})=>({id:a,bitrate:e}),Cv=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Dv=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Zu=({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}),el=({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)}),tl=a=>"url"in a,je=a=>a.type==="template",Ia=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Ea=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new E.ValueSubject(0);this.currentSegmentLength$=new E.ValueSubject(0);this.onLastSegment$=new E.ValueSubject(!1);this.fullyBuffered$=new E.ValueSubject(!1);this.playingRepresentation$=new E.ValueSubject(void 0);this.playingRepresentationInit$=new E.ValueSubject(void 0);this.error$=new E.Subject;this.gaps=[];this.subscription=new E.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new He;this.switchAbortController=new He;this.destroyAbortController=new He;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,E.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){let t=this.representations.get(e);(0,E.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,E.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:E.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,qu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=gt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,E.assertNonNullable)(r,"No init buffer for starting representation"),(0,E.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,E.abortable)(this.destroyAbortController.signal,function(e,t=!1){return me(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,E.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,E.isNullable)(s)||(0,E.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,E.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,E.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new xn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,E.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){var u,l;let t=(u=(0,an.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(m=>m.id===d);c&&this.representations.set(d,c);let p=this.representations.get(d);if(!p||!je(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,E.assertNonNullable)(i);let s=this.segments.get(r);(0,E.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,E.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new He,(0,E.abortable)(this.switchAbortController.signal,function(r,i=!1){return me(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,E.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,E.isNullable)(o)||(0,E.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,E.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,E.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))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new He,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,d;if((0,E.isNullable)(e)||(0,E.isNullable)(this.downloadingRepresentationId)||(0,E.isNullable)(this.playingRepresentationId)||(0,E.isNullable)(this.sourceBuffer)||(0,E.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,E.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((d=i==null?void 0:i.time.from)!=null?d:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=gt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&qu(this.sourceBuffer.buffered)>=this.bufferLimit){let c=gt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,rn.default)(o,i))c="high";else{let p=(0,si.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&gt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,si.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,E.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,an.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,an.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];for(let o of t){if(!o||!je(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>H(R({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,si.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,c=u==null?void 0:u.findIndex(p=>Math.floor(d)>=Math.floor(p.time.from)&&Math.floor(d)<=Math.floor(p.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(c+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,E.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 t;for(let r of this.representations.values()){let i=r.segmentReference;if(!je(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=Mt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Xi&&Xi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Xi&&Xi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:c,time:{from:p,to:h}},m)=>{let g=p<=r&&h>=r,v=p>r||g||m===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=r+I||h<=r+I;return(c==="none"||c==="partially_ejected"&&v&&T&&this.sourceBuffer&&!(Xt(this.sourceBuffer.buffered,p)&&Xt(this.sourceBuffer.buffered,h)))&&v&&T});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=i;c<s.length&&(n<=l||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return O(this,null,function*(){je(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return O(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,E.abortable)(o,function(){return me(this,null,function*(){let d=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,E.now)(),!d)return;let c=new DataView(d),p=Ta(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(c,g)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ia(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())je(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return O(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,E.abortable)(n,function(){return me(this,null,function*(){let u=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,E.fromEvent)(window,"online").pipe((0,E.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=(0,E.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ia(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(je(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,si.default)(e,0).byte.from,to:(0,si.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)(),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:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!je(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,rn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return O(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=Ta(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return O(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let c=d.byte.from-r,p=d.byte.to-r,h=p-c+1,m=c<i,g=p<=i;if(!m)continue;let v=Ta(u.mime);if(d.status==="downloading"&&g){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+c,h);(yield this.sourceBufferTaskQueue.append(I,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-c),l.loadedBytes>l.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===h?I:v.parseFeedableSegmentChunk(I);T!=null&&T.byteLength&&(d.status="partially_fed",l.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(l.fedBytes+=T.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&((0,E.assertNonNullable)(this.sourceBuffer),Xt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Xt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",tl(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");(0,E.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Nu(()=>(0,Ov.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return O(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,E.abortable)(this.destroyAbortController.signal,function(){return me(this,null,function*(){let o=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ta(e.mime),i)).then(o=>O(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&je(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:E.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return O(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return O(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,E.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return i;i.push(R({},u.time)),i=n(i);let l=tl(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)(0,rn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,E.isNullable)(e)?0:gt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){(0,E.assertNonNullable)(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=Nu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:E.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,E.isNullable)(this.sourceBuffer)||(0,E.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(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(d=>d.from===i.time.from||d.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var xa=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/es2015");var Vv=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var sn=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 He;this.subscription=new Z.Subscription;this.fetchManifest=(0,Z.abortable)(this.abortAllController.signal,function(e){return me(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=xa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Vv(r));let i=yield kt(r,{signal:this.abortAllController.signal}).catch(Pa);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,function(l){return me(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var _,ie;let d=e,c=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let U=new URL(d,location.href);U.searchParams.append("bytes",`${r.from}-${r.to}`),d=U.toString();break}default:(0,Z.assertNever)(t)}this.requestQuic&&(d=xa(d));let h=this.abortAllController.signal,m;if(n){let U=new He;if(m=(0,Z.merge)((0,Z.fromEvent)(this.abortAllController.signal,"abort"),(0,Z.fromEvent)(n,"abort")).subscribe(()=>{try{U.abort()}catch(ne){Pa(ne)}}),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(ne){Pa(ne)}h=U.signal}let g=(0,Z.now)();p.log("startRequest",(0,Z.flattenObject)({url:d,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let v=yield kt(d,{priority:s,headers:c,signal:h}).catch(Pa),I=(0,Z.now)();if(!v)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(I-g),!v.ok||!v.body){m==null||m.unsubscribe();let U=`Fetch error ${v.status}: ${v.statusText}`;return p.error("error",{message:U}),p.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!i&&!o){m==null||m.unsubscribe();let U=(0,Z.now)(),ne={requestStartedAt:g,requestEndedAt:U,duration:U-g};return p.log("endRequest",(0,Z.flattenObject)(ne)),p.end(),v.arrayBuffer()}let[T,x]=v.body.tee(),A=T.getReader();o&&((ie=this.throughputEstimator)==null||ie.trackStream(x,u));let w=0,F=new Uint8Array(0),Q=!1,oe=U=>{m==null||m.unsubscribe(),Q=!0,Pa(U)},J=(0,Z.abortable)(h,function($){return me(this,arguments,function*({done:U,value:ne}){if(w===0&&this.lastRequestFirstBytes$.next((0,Z.now)()-g),h.aborted){m==null||m.unsubscribe();return}if(!U&&ne){let P=new Uint8Array(F.length+ne.length);P.set(F),P.set(ne,F.length),F=P,w+=ne.byteLength,i==null||i(new DataView(F.buffer),w),yield A==null?void 0:A.read().then(J,oe)}})}.bind(this));yield A==null?void 0:A.read().then(J,oe),m==null||m.unsubscribe();let W=(0,Z.now)(),te={failed:Q,requestStartedAt:g,requestEndedAt:W,duration:W-g};return Q?(p.error("endRequest",(0,Z.flattenObject)(te)),p.end(),null):(p.log("endRequest",(0,Z.flattenObject)(te)),p.end(),F.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,Z.abortable)(this.abortAllController.signal,function(e,t,r){return me(this,null,function*(){var I;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!c)return null;let p=new DataView(c,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),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(c,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(c),segments:v}})}.bind(this));this.fetchTemplateRepresentation=(0,Z.abortable)(this.abortAllController.signal,function(e,t){return me(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>H(R({},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)}fetchRepresentation(e,t,r="auto"){return O(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,Z.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Pa=a=>{if(!Ia(a))throw a};var Sr=(a,e,t)=>t*e+(1-t)*a,rl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,_v=(a,e,t,r)=>{let i=0,s=t,n=rl(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 Aa=require("@vkontakte/videoplayer-shared/es2015");var 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 Aa.ValueSubject(e.initial),this.debounced$=new Aa.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new $e(`raw_${t}`),this.smoothedSeries$=new $e(`smoothed_${t}`),this.reportedSeries$=new $e(`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+=ct(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,Aa.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 nn=class extends er{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Sr(this.slow,e,this.params.emaAlphaSlow),this.fast=Sr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var on=class extends er{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=rl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Sr(this.emaSmoothed,e,this.params.emaAlpha);let r=_v(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var un=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?Sr(this.smoothed,t,this.params.emaAlpha):t}};var yr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new nn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new on({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 un(R({initial:e,label:"liveEdgeDelay"},t))}};var il=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var ln=require("@vkontakte/videoplayer-shared/es2015");var wa=class a{constructor(e,t){this.currentRepresentation$=new ln.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,ln.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(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(H(R({},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&&je(t.segmentReference))}};var GR=["timeupdate","progress","play","seeked","stalled","waiting"],QR=["timeupdate","progress","loadeddata","playing","seeked"];var cn=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 j("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 He;this.initManifest=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return me(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=we(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,function(){return me(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Rv(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,d)=>{var c,p,h,m;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,l)&&((m=(h=Rt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${d}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),c=new Set(d.map(({codecs:h})=>h)),p=ng(c);if(p&&(i[u]=d.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=H(R({},t),{streams:i});return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return me(this,null,function*(){var p;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=h=>{this.representationSubscription.add((0,S.fromEvent)(h,"error").pipe((0,S.filter)(m=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};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&&Ws())if(r){let h=document.createElement("source");i(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((h,m)=>[...h,...m.representations],[]);if(this.videoBufferManager=new Ea("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((m,g)=>[...m,...g.representations],[]);this.audioBufferManager=new Ea("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}wa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new wa(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(h=>{var m;if((m=this.element)!=null&&m.paused){let g=Vs(this.manifestUrlString,2);this.manifestUrlString=we(this.manifestUrlString,g+1e3,2)}}));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...QR.map(h=>(0,S.fromEvent)(this.element,h))).pipe((0,S.map)(h=>this.element?gt(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(h=>{h>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(m=>il(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:m,isActiveLowLatency:g})=>g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),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:m})=>m),(0,S.map)(m=>R({},m)),(0,S.filterChanged)((m,g)=>g.bufferLength<m.bufferLength),(0,S.map)(({rtt:m,bufferLength:g,segmentServerLatency:v})=>{let I=Vs(this.manifestUrlString,2);return(m/2+g+v+I)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:m,isActiveLowLatency:g})=>{if(!g)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,I=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=m-v,A=1;Math.abs(x)>I&&(A=1+Math.sign(x)*T),il(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var v,I;let g=0;if(m){let T=((I=(v=this.element)==null?void 0:v.currentTime)!=null?I:0)*1e3;g=Math.min(...this.bufferManagers.map(A=>{var w,F;return(F=(w=A.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?F:T}))-T}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let h=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(v=>O(this,[v],function*({liveLoadBufferLength:m,bufferLength:g}){if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let I=this.element.playbackRate,T=Vs(this.manifestUrlString,2),x=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,A=Math.min(x,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*I),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*I,F=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*I,Q=isFinite(m)?m:g,oe=this.isActiveLowLatency$.getValue(),J=x<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(oe&&J);let W="none";if(oe?W="active_low_latency":this.isLowLatency$.getValue()&&J?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(te=>te.proceedLowLatencyLive()),W="active_low_latency"):T!==0&&Q<A?W="live_forward_buffering":Q<A+F&&(W="live_with_target_offset"),isFinite(m)&&(h=m>h?m:h),W==="live_forward_buffering"||W==="live_with_target_offset"){let te=h-(A+w),_=this.normolizeLiveOffset(Math.trunc(T+te/I)),ie=Math.abs(_-T),U;!m||ie<=this.tuning.dashCmafLive.offsetCalculationError?U=T:_>0&&ie>this.tuning.dashCmafLive.offsetCalculationError?U=_:U=0,this.manifestUrlString=we(this.manifestUrlString,U,2)}W!=="none"&&W!=="active_low_latency"&&(h=0,this.updateLive())})))}let l=(0,S.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=(0,S.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,S.filter)(({allBuffersFull:h,someBufferEnded:m})=>h&&m))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(h=this.source)==null||h.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(h=>{var m;return(m=this.source)==null?void 0:m.addEventListener("sourceopen",h)}));let c=[(p=this.manifest.duration)!=null?p:0,...(0,al.default)((0,al.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),je(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/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 sn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=yr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,R({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return O(this,null,function*(){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=we(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...GR.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,T,x,A,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=(T=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,d=(A=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?A:0,c=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let Q=this.element.currentTime*1e3;(w=this.videoBufferManager)==null||w.maintain(Q),(F=this.audioBufferManager)==null||F.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()}switchRepresentation(e,t,r=!1){return O(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u;(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)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(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=>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}updateLive(){return O(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=H(R({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,S.flattenObject)(t)))}}};var dn=class{constructor(e,t){this.fov=e,this.orientation=t}};var pn=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/ct(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=R({},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*ct(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 Fv=`attribute vec2 a_vertex;
69
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var wv=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Ct=(a,e)=>{let t=a;t=(0,Ju.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,kv.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ju.default)(t,n,(o,u)=>(0,si.isNullable)(s)?o:(0,si.isNullable)(u)?s:(0,Rv.default)(s,parseInt(u,10),"0"))}return t},Lv=(a,e)=>{var w,N,Q,oe,J,W,te,B,ie,U,ne,$,P,K,Y,be,Qe,Bt,Er,re,Ie,Ee,We,_t,xr,Nt,ir,Pr,li,ml,bl,gl,vl,Sl,yl,Tl,Il,El,xl,Pl,Al,wl,kl,Rl,$l,Ll,Ml,Cl,Dl,Ol,Vl,Bl,_l,Nl,Fl,ql,Ul,Hl,jl,Gl;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(xe=>{var Ha,Ft;return(Ft=(Ha=xe.textContent)==null?void 0:Ha.trim())!=null?Ft:""}),u=(w=(0,$v.default)(o,0))!=null?w:"",l=n.children,d=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,h,m=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),v=s.getElementsByTagName("vk:Attrs")[0],I=v==null?void 0:v.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)h=wv(m);else if(g){let xe=wv(g);(0,si.isNonNullable)(xe)&&(h=xe)}else I&&(h=parseInt(I,10));let T=0,x=(Q=(N=s.getAttribute("profiles"))==null?void 0:N.split(","))!=null?Q:[];for(let xe of l){let Ha=(oe=xe.getAttribute("id"))!=null?oe:"id"+(T++).toString(10),Ft=(J=xe.getAttribute("mimeType"))!=null?J:"",yn=(W=xe.getAttribute("codecs"))!=null?W:"",Tn=(te=xe.getAttribute("contentType"))!=null?te:Ft==null?void 0:Ft.split("/")[0],mS=(ie=(B=xe.getAttribute("profiles"))==null?void 0:B.split(","))!=null?ie:[],Ql=(ne=Av((U=xe.getAttribute("lang"))!=null?U:""))!=null?ne:{},bS=(K=(P=($=xe.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:P.trim())!=null?K:void 0,gS=xe.querySelectorAll("Representation"),vS=xe.querySelector("SegmentTemplate"),SS=(be=(Y=xe.querySelector("Role"))==null?void 0:Y.getAttribute("value"))!=null?be:void 0,ci=Tn,ge={id:Ha,language:Ql.language,isDefault:SS==="main",label:bS,codecs:yn,hdr:ci==="video"&&Ku(yn),mime:Ft,representations:[]};for(let ue of gS){let yS=(Qe=ue.getAttribute("lang"))!=null?Qe:void 0,TS=(Bt=ue.getAttribute("label"))!=null?Bt:void 0,IS=(Ie=(re=(Er=ue.querySelector("BaseURL"))==null?void 0:Er.textContent)==null?void 0:re.trim())!=null?Ie:"",ja=new URL(IS||u,e).toString(),Ar=(Ee=ue.getAttribute("mimeType"))!=null?Ee:Ft,Ga=(_t=(We=ue.getAttribute("codecs"))!=null?We:yn)!=null?_t:"",Qa;if(Tn==="text"){let qt=ue.getAttribute("id")||"",Wa=((xr=Ql.privateuse)==null?void 0:xr.includes("x-auto"))||qt.includes("_auto"),ar=ue.querySelector("SegmentTemplate");if(ar){let di={representationId:(Nt=ue.getAttribute("id"))!=null?Nt:void 0,bandwidth:(ir=ue.getAttribute("bandwidth"))!=null?ir:void 0},Ya=parseInt((Pr=ue.getAttribute("bandwidth"))!=null?Pr:"",10)/1e3,za=(ml=parseInt((li=ar.getAttribute("startNumber"))!=null?li:"",10))!=null?ml:1,wr=parseInt((bl=ar.getAttribute("timescale"))!=null?bl:"",10),In=(gl=ar.querySelectorAll("SegmentTimeline S"))!=null?gl:[],kr=ar.getAttribute("media");if(!kr)continue;let Ka=[],Ja=0,Xa="",Rr=0,pi=za,ke=0;for(let tt of In){let sr=parseInt((vl=tt.getAttribute("d"))!=null?vl:"",10),Ye=parseInt((Sl=tt.getAttribute("r"))!=null?Sl:"",10)||0,Ut=parseInt((yl=tt.getAttribute("t"))!=null?yl:"",10);ke=Number.isFinite(Ut)?Ut:ke;let nr=sr/wr*1e3,Ht=ke/wr*1e3;for(let lt=0;lt<Ye+1;lt++){let jt=Ct(kr,H(R({},di),{segmentNumber:pi.toString(10),segmentTime:(ke+lt*sr).toString(10)})),$r=(Ht!=null?Ht:0)+lt*nr,fi=$r+nr;pi++,Ka.push({time:{from:$r,to:fi},url:jt})}ke+=(Ye+1)*sr,Ja+=(Ye+1)*nr}Rr=ke/wr*1e3,Xa=Ct(kr,H(R({},di),{segmentNumber:pi.toString(10),segmentTime:ke.toString(10)}));let hi={time:{from:Rr,to:1/0},url:Xa},Tt={type:"template",baseUrl:ja,segmentTemplateUrl:kr,initUrl:"",totalSegmentsDurationMs:Ja,segments:Ka,nextSegmentBeyondManifest:hi,timescale:wr};Qa={id:qt,kind:"text",segmentReference:Tt,profiles:[],duration:h,bitrate:Ya,mime:"",codecs:"",width:0,height:0,isAuto:Wa}}else Qa={id:qt,isAuto:Wa,kind:"text",url:ja}}else{let qt=(Il=(Tl=ue.getAttribute("contentType"))!=null?Tl:Ar==null?void 0:Ar.split("/")[0])!=null?Il:Tn,Wa=(xl=(El=xe.getAttribute("profiles"))==null?void 0:El.split(","))!=null?xl:[],ar=parseInt((Pl=ue.getAttribute("width"))!=null?Pl:"",10),di=parseInt((Al=ue.getAttribute("height"))!=null?Al:"",10),Ya=parseInt((wl=ue.getAttribute("bandwidth"))!=null?wl:"",10)/1e3,za=(kl=ue.getAttribute("frameRate"))!=null?kl:"",wr=(Rl=ue.getAttribute("quality"))!=null?Rl:void 0,In=za?Pv(za):void 0,kr=($l=ue.getAttribute("id"))!=null?$l:"id"+(T++).toString(10),Ka=qt==="video"?`${di}p`:qt==="audio"?`${Ya}Kbps`:Ga,Ja=`${kr}@${Ka}`,Xa=[...x,...mS,...Wa],Rr,pi=ue.querySelector("SegmentBase"),ke=(Ll=ue.querySelector("SegmentTemplate"))!=null?Ll:vS;if(pi){let Tt=(Cl=(Ml=ue.querySelector("SegmentBase Initialization"))==null?void 0:Ml.getAttribute("range"))!=null?Cl:"",[tt,sr]=Tt.split("-").map(jt=>parseInt(jt,10)),Ye={from:tt,to:sr},Ut=(Dl=ue.querySelector("SegmentBase"))==null?void 0:Dl.getAttribute("indexRange"),[nr,Ht]=Ut?Ut.split("-").map(jt=>parseInt(jt,10)):[],lt=Ut?{from:nr,to:Ht}:void 0;Rr={type:"byteRange",url:ja,initRange:Ye,indexRange:lt}}else if(ke){let Tt={representationId:(Ol=ue.getAttribute("id"))!=null?Ol:void 0,bandwidth:(Vl=ue.getAttribute("bandwidth"))!=null?Vl:void 0},tt=parseInt((Bl=ke.getAttribute("timescale"))!=null?Bl:"",10),sr=(_l=ke.getAttribute("initialization"))!=null?_l:"",Ye=ke.getAttribute("media"),Ut=(Fl=parseInt((Nl=ke.getAttribute("startNumber"))!=null?Nl:"",10))!=null?Fl:1,nr=Ct(sr,Tt);if(!Ye)throw new ReferenceError("No media attribute in SegmentTemplate");let Ht=(ql=ke.querySelectorAll("SegmentTimeline S"))!=null?ql:[],lt=[],jt=0,$r="",fi=0;if(Ht.length){let Za=Ut,rt=0;for(let Lr of Ht){let ct=parseInt((Ul=Lr.getAttribute("d"))!=null?Ul:"",10),or=parseInt((Hl=Lr.getAttribute("r"))!=null?Hl:"",10)||0,es=parseInt((jl=Lr.getAttribute("t"))!=null?jl:"",10);rt=Number.isFinite(es)?es:rt;let En=ct/tt*1e3,xn=rt/tt*1e3;for(let ts=0;ts<or+1;ts++){let xS=Ct(Ye,H(R({},Tt),{segmentNumber:Za.toString(10),segmentTime:(rt+ts*ct).toString(10)})),Wl=(xn!=null?xn:0)+ts*En,PS=Wl+En;Za++,lt.push({time:{from:Wl,to:PS},url:xS})}rt+=(or+1)*ct,jt+=(or+1)*En}fi=rt/tt*1e3,$r=Ct(Ye,H(R({},Tt),{segmentNumber:Za.toString(10),segmentTime:rt.toString(10)}))}else if((0,si.isNonNullable)(h)){let rt=parseInt((Gl=ke.getAttribute("duration"))!=null?Gl:"",10)/tt*1e3,Lr=Math.ceil(h/rt),ct=0;for(let or=1;or<Lr;or++){let es=Ct(Ye,H(R({},Tt),{segmentNumber:or.toString(10),segmentTime:ct.toString(10)}));lt.push({time:{from:ct,to:ct+rt},url:es}),ct+=rt}fi=ct,$r=Ct(Ye,H(R({},Tt),{segmentNumber:Lr.toString(10),segmentTime:ct.toString(10)}))}let ES={time:{from:fi,to:1/0},url:$r};Rr={type:"template",baseUrl:ja,segmentTemplateUrl:Ye,initUrl:nr,totalSegmentsDurationMs:jt,segments:lt,nextSegmentBeyondManifest:ES,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!qt||!Ar)continue;let hi={video:"video",audio:"audio",text:"text"}[qt];if(!hi)continue;ci||(ci=hi),Qa={id:Ja,kind:hi,segmentReference:Rr,profiles:Xa,duration:h,bitrate:Ya,mime:Ar,codecs:Ga,width:ar,height:di,fps:In,quality:wr}}ge.language||(ge.language=yS),ge.label||(ge.label=TS),ge.mime||(ge.mime=Ar),ge.codecs||(ge.codecs=Ga),ge.hdr||(ge.hdr=ci==="video"&&Ku(Ga)),ge.representations.push(Qa)}ci&&i[ci].push(ge)}return{dynamic:d,liveAvailabilityStartTime:p,duration:h,streams:i,baseUrls:o}};var el=X(Jr(),1);var Mv=require("@vkontakte/videoplayer-shared/es2015"),Cv=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:(0,Mv.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Dv=({id:a,bitrate:e})=>({id:a,bitrate:e}),Ov=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Vv=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),tl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,el.default)(r.split("."),0),isDefault:i}),rl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,el.default)(i.split("."),0)}),il=a=>"url"in a,Ge=a=>a.type==="template",Ea=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var xa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new E.ValueSubject(0);this.currentSegmentLength$=new E.ValueSubject(0);this.onLastSegment$=new E.ValueSubject(!1);this.fullyBuffered$=new E.ValueSubject(!1);this.playingRepresentation$=new E.ValueSubject(void 0);this.playingRepresentationInit$=new E.ValueSubject(void 0);this.error$=new E.Subject;this.gaps=[];this.subscription=new E.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new je;this.switchAbortController=new je;this.destroyAbortController=new je;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,E.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){let t=this.representations.get(e);(0,E.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 Dg(this.sourceBuffer),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,E.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:E.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Hu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=vt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,E.assertNonNullable)(r,"No init buffer for starting representation"),(0,E.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,E.abortable)(this.destroyAbortController.signal,function(e,t=!1){return me(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,E.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,E.isNullable)(s)||(0,E.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,E.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,E.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new An(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,E.abortable)(this.destroyAbortController.signal,function(e){return me(this,null,function*(){var u,l;let t=(u=(0,sn.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(m=>m.id===d);c&&this.representations.set(d,c);let p=this.representations.get(d);if(!p||!Ge(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,E.assertNonNullable)(i);let s=this.segments.get(r);(0,E.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,E.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new je,(0,E.abortable)(this.switchAbortController.signal,function(r,i=!1){return me(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,E.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,E.isNullable)(o)||(0,E.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,E.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,E.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))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new je,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,d;if((0,E.isNullable)(e)||(0,E.isNullable)(this.downloadingRepresentationId)||(0,E.isNullable)(this.playingRepresentationId)||(0,E.isNullable)(this.sourceBuffer)||(0,E.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,E.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((d=i==null?void 0:i.time.from)!=null?d:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=vt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&Hu(this.sourceBuffer.buffered)>=this.bufferLimit){let c=vt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,an.default)(o,i))c="high";else{let p=(0,ni.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&vt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ni.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,E.isNonNullable)(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,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:[];for(let o of t){if(!o||!Ge(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>H(R({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ni.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,c=u==null?void 0:u.findIndex(p=>Math.floor(d)>=Math.floor(p.time.from)&&Math.floor(d)<=Math.floor(p.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(c+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,E.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 t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Ge(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=Ct(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Zi&&Zi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Zi&&Zi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:c,time:{from:p,to:h}},m)=>{let g=p<=r&&h>=r,v=p>r||g||m===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=r+I||h<=r+I;return(c==="none"||c==="partially_ejected"&&v&&T&&this.sourceBuffer&&!(Zt(this.sourceBuffer.buffered,p)&&Zt(this.sourceBuffer.buffered,h)))&&v&&T});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=i;c<s.length&&(n<=l||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return O(this,null,function*(){Ge(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return O(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,E.abortable)(o,function(){return me(this,null,function*(){let d=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,E.now)(),!d)return;let c=new DataView(d),p=Ia(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(c,g)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(c);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ea(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ge(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return O(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,E.abortable)(n,function(){return me(this,null,function*(){let u=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,E.fromEvent)(window,"online").pipe((0,E.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=(0,E.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ea(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Ge(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ni.default)(e,0).byte.from,to:(0,ni.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)(),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:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ge(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,an.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return O(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=Ia(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return O(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let c=d.byte.from-r,p=d.byte.to-r,h=p-c+1,m=c<i,g=p<=i;if(!m)continue;let v=Ia(u.mime);if(d.status==="downloading"&&g){d.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+c,h);(yield this.sourceBufferTaskQueue.append(I,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-c),l.loadedBytes>l.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===h?I:v.parseFeedableSegmentChunk(I);T!=null&&T.byteLength&&(d.status="partially_fed",l.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(l.fedBytes+=T.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&((0,E.assertNonNullable)(this.sourceBuffer),Zt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Zt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",il(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");(0,E.assertNonNullable)(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=qu(()=>(0,Bv.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return O(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,E.abortable)(this.destroyAbortController.signal,function(){return me(this,null,function*(){let o=(0,E.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(o=>O(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&Ge(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:E.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return O(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return O(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||(0,E.isNullable)(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return i;i.push(R({},u.time)),i=n(i);let l=il(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let 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(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,E.isNullable)(e)?0:vt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){(0,E.assertNonNullable)(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=qu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:E.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,E.isNullable)(this.sourceBuffer)||(0,E.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(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(d=>d.from===i.time.from||d.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Pa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var _v=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/es2015");var Nv=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 je;this.subscription=new Z.Subscription;this.fetchManifest=(0,Z.abortable)(this.abortAllController.signal,function(e){return me(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Pa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Nv(r));let i=yield Rt(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,function(l){return me(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var B,ie;let d=e,c=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let U=new URL(d,location.href);U.searchParams.append("bytes",`${r.from}-${r.to}`),d=U.toString();break}default:(0,Z.assertNever)(t)}this.requestQuic&&(d=Pa(d));let h=this.abortAllController.signal,m;if(n){let U=new je;if(m=(0,Z.merge)((0,Z.fromEvent)(this.abortAllController.signal,"abort"),(0,Z.fromEvent)(n,"abort")).subscribe(()=>{try{U.abort()}catch(ne){Aa(ne)}}),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(ne){Aa(ne)}h=U.signal}let g=(0,Z.now)();p.log("startRequest",(0,Z.flattenObject)({url:d,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let v=yield Rt(d,{priority:s,headers:c,signal:h}).catch(Aa),I=(0,Z.now)();if(!v)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((B=this.throughputEstimator)==null||B.addRawRtt(I-g),!v.ok||!v.body){m==null||m.unsubscribe();let U=`Fetch error ${v.status}: ${v.statusText}`;return p.error("error",{message:U}),p.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!i&&!o){m==null||m.unsubscribe();let U=(0,Z.now)(),ne={requestStartedAt:g,requestEndedAt:U,duration:U-g};return p.log("endRequest",(0,Z.flattenObject)(ne)),p.end(),v.arrayBuffer()}let[T,x]=v.body.tee(),A=T.getReader();o&&((ie=this.throughputEstimator)==null||ie.trackStream(x,u));let w=0,N=new Uint8Array(0),Q=!1,oe=U=>{m==null||m.unsubscribe(),Q=!0,Aa(U)},J=(0,Z.abortable)(h,function($){return me(this,arguments,function*({done:U,value:ne}){if(w===0&&this.lastRequestFirstBytes$.next((0,Z.now)()-g),h.aborted){m==null||m.unsubscribe();return}if(!U&&ne){let P=new Uint8Array(N.length+ne.length);P.set(N),P.set(ne,N.length),N=P,w+=ne.byteLength,i==null||i(new DataView(N.buffer),w),yield A==null?void 0:A.read().then(J,oe)}})}.bind(this));yield A==null?void 0:A.read().then(J,oe),m==null||m.unsubscribe();let W=(0,Z.now)(),te={failed:Q,requestStartedAt:g,requestEndedAt:W,duration:W-g};return Q?(p.error("endRequest",(0,Z.flattenObject)(te)),p.end(),null):(p.log("endRequest",(0,Z.flattenObject)(te)),p.end(),N.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,Z.abortable)(this.abortAllController.signal,function(e,t,r){return me(this,null,function*(){var I;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!c)return null;let p=new DataView(c,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),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(c,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(c),segments:v}})}.bind(this));this.fetchTemplateRepresentation=(0,Z.abortable)(this.abortAllController.signal,function(e,t){return me(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>H(R({},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}=_v(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return O(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,Z.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Aa=a=>{if(!Ea(a))throw a};var yr=(a,e,t)=>t*e+(1-t)*a,al=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Fv=(a,e,t,r)=>{let i=0,s=t,n=al(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 wa=require("@vkontakte/videoplayer-shared/es2015");var tr=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 wa.ValueSubject(e.initial),this.debounced$=new wa.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new $e(`raw_${t}`),this.smoothedSeries$=new $e(`smoothed_${t}`),this.reportedSeries$=new $e(`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+=dt(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,wa.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 tr{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 un=class extends tr{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=al(this.pastMeasures,this.takenMeasures);this.emaSmoothed=yr(this.emaSmoothed,e,this.params.emaAlpha);let r=Fv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var ln=class extends tr{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 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(R({initial:e,label:"liveEdgeDelay"},t))}};var sl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var cn=require("@vkontakte/videoplayer-shared/es2015");var ka=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(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(H(R({},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&&Ge(t.segmentReference))}};var WR=["timeupdate","progress","play","seeked","stalled","waiting"],YR=["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 j("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 je;this.initManifest=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return me(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=we(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,function(){return me(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Lv(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,d)=>{var c,p,h,m;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,l)&&((m=(h=$t())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${d}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),c=new Set(d.map(({codecs:h})=>h)),p=ug(c);if(p&&(i[u]=d.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=H(R({},t),{streams:i});return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return me(this,null,function*(){var p;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=h=>{this.representationSubscription.add((0,S.fromEvent)(h,"error").pipe((0,S.filter)(m=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};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&&Ys())if(r){let h=document.createElement("source");i(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((h,m)=>[...h,...m.representations],[]);if(this.videoBufferManager=new xa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((m,g)=>[...m,...g.representations],[]);this.audioBufferManager=new xa("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}ka.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ka(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(h=>{var m;if((m=this.element)!=null&&m.paused){let g=_s(this.manifestUrlString,2);this.manifestUrlString=we(this.manifestUrlString,g+1e3,2)}}));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...YR.map(h=>(0,S.fromEvent)(this.element,h))).pipe((0,S.map)(h=>this.element?vt(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(h=>{h>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(m=>sl(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:m,isActiveLowLatency:g})=>g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),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:m})=>m),(0,S.map)(m=>R({},m)),(0,S.filterChanged)((m,g)=>g.bufferLength<m.bufferLength),(0,S.map)(({rtt:m,bufferLength:g,segmentServerLatency:v})=>{let I=_s(this.manifestUrlString,2);return(m/2+g+v+I)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:m,isActiveLowLatency:g})=>{if(!g)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,I=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=m-v,A=1;Math.abs(x)>I&&(A=1+Math.sign(x)*T),sl(this.element,A)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var v,I;let g=0;if(m){let T=((I=(v=this.element)==null?void 0:v.currentTime)!=null?I:0)*1e3;g=Math.min(...this.bufferManagers.map(A=>{var w,N;return(N=(w=A.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?N:T}))-T}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let h=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(v=>O(this,[v],function*({liveLoadBufferLength:m,bufferLength:g}){if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let I=this.element.playbackRate,T=_s(this.manifestUrlString,2),x=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,A=Math.min(x,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*I),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*I,N=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*I,Q=isFinite(m)?m:g,oe=this.isActiveLowLatency$.getValue(),J=x<=this.tuning.live.activeLiveDelay&&T===0;this.isActiveLowLatency$.next(oe&&J);let W="none";if(oe?W="active_low_latency":this.isLowLatency$.getValue()&&J?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(te=>te.proceedLowLatencyLive()),W="active_low_latency"):T!==0&&Q<A?W="live_forward_buffering":Q<A+N&&(W="live_with_target_offset"),isFinite(m)&&(h=m>h?m:h),W==="live_forward_buffering"||W==="live_with_target_offset"){let te=h-(A+w),B=this.normolizeLiveOffset(Math.trunc(T+te/I)),ie=Math.abs(B-T),U;!m||ie<=this.tuning.dashCmafLive.offsetCalculationError?U=T:B>0&&ie>this.tuning.dashCmafLive.offsetCalculationError?U=B:U=0,this.manifestUrlString=we(this.manifestUrlString,U,2)}W!=="none"&&W!=="active_low_latency"&&(h=0,this.updateLive())})))}let l=(0,S.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=(0,S.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:d}).pipe((0,S.filter)(({allBuffersFull:h,someBufferEnded:m})=>h&&m))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(h=this.source)==null||h.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(h=>{var m;return(m=this.source)==null?void 0:m.addEventListener("sourceopen",h)}));let c=[(p=this.manifest.duration)!=null?p:0,...(0,nl.default)((0,nl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ge(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/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=Tr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,R({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return O(this,null,function*(){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=we(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...WR.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&&Zt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,g,v,I,T,x,A,w,N;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=(T=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,d=(A=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?A:0,c=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let Q=this.element.currentTime*1e3;(w=this.videoBufferManager)==null||w.maintain(Q),(N=this.audioBufferManager)==null||N.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()}switchRepresentation(e,t,r=!1){return O(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u;(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),Zt(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(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=>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}updateLive(){return O(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=H(R({},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/dt(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=R({},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*dt(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 Uv=`attribute vec2 a_vertex;
70
70
  attribute vec2 a_texel;
71
71
 
72
72
  varying vec2 v_texel;
@@ -77,7 +77,7 @@ void main(void) {
77
77
  // save texel vector to pass to fragment shader
78
78
  v_texel = a_texel;
79
79
  }
80
- `;var qv=`#ifdef GL_ES
80
+ `;var Hv=`#ifdef GL_ES
81
81
  precision highp float;
82
82
  precision highp int;
83
83
  #else
@@ -120,5 +120,5 @@ void main(void) {
120
120
  // sample using new coordinates
121
121
  gl_FragColor = texture2D(u_texture, tc);
122
122
  }
123
- `;var hn=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 dn(this.params.fov,this.params.orientation),this.cameraRotationManager=new pn(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(Fv,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,d=t+i,c=e-r,p=t+i;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Te=require("@vkontakte/videoplayer-shared/es2015"),sl=class{constructor(){this.isSeeked$=new Te.ValueSubject(!1);this.isBuffering$=new Te.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Te.Subscription}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,Te.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,Te.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,Te.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if((0,Te.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),d=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,Te.now)(),p=n&&this.currentStallsCount>=n,h=i&&!r&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,m=s&&c-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&c-d>=s+u&&t>=s;(p||h||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Te.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Te.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Uv=sl;var Tr=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new j("stopped");this.elementSize$=new V.ValueSubject(void 0);this.textTracksManager=new ze;this.droppedFramesManager=new Hs;this.stallsManager=new Uv;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ui;this.audioTrackSwitchHistory=new Ui;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&k(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"&&k(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"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,V.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new hn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=Le(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(Se(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 cn({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=De(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:V.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(){var d;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,V.filter)(c=>!!c.length),(0,V.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,V.map)(c=>c.to.state!=="none"),(0,V.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,V.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,V.filter)(V.isNonNullable),(0,V.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,V.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(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(this.video,t.playbackRate,r.playbackRateState$,i)),s((0,V.observeElementSize)(this.video),this.elementSize$),s(Ke(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if((0,V.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of p.audio){m.push(Zu(g));let v=[];for(let I of g.representations){let T=Mv(I);v.push(T),this.audioTracksMap.set(T,{stream:g,representation:I})}this.audioStreamsMap.set(g,v)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of p.video){h.push(el(m));let g=[];for(let v of m.representations){let I=Lv(H(R({},v),{streamId:m.id}));I&&(g.push(I),this.videoTracksMap.set(I,{stream:m,representation:v}))}this.videoStreamsMap.set(m,g)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let m of p.text)for(let g of m.representations){let v=Cv(m,g);this.textTracksMap.set(v,{stream:m,representation:g})}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:V.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,V.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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,V.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(!(0,Hv.default)(["manifest_ready","running"],c)||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,g]=h,v=[...this.videoTracksMap.keys()].find(T=>{var x;return((x=this.videoTracksMap.get(T))==null?void 0:x.representation.id)===m.id});(0,V.isNonNullable)(v)&&(this.stallsManager.lastVideoTrackSelected=v);let I=this.params.desiredState.autoVideoTrackLimits.getTransition();if(I&&this.params.output.autoVideoTrackLimits$.next(I.to),c==="manifest_ready")this.player.initRepresentations(m.id,g==null?void 0:g.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),g){let T=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",g.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.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,V.filterChanged)()).subscribe(c=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.videoStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.videoStream.setState(g.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(el(m))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,V.filterChanged)()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.audioStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.audioStream.setState(g.to),e.currentAudioStream$.next(Zu(m))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),(d=this.textTracksManager)==null||d.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,V.map)(({to:c})=>c==="ready"),(0,V.filterChanged)());this.subscription.add((0,V.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,V.merge)(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,V.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var F,Q,oe,J,W,te,_,ie,U,ne,$,P,K;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(F=e.videoTrack.getState())==null?void 0:F.id,n=[...this.videoTracksMap.keys()].find(({id:Y})=>Y===i),o=t.currentVideoTrack$.getValue(),u=((J=(oe=e.videoStream.getState())!=null?oe:n&&((Q=this.videoTracksMap.get(n))==null?void 0:Q.stream))!=null?J:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:Y})=>Y===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=gt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(W=e.audioStream.getState())!=null?W:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(te=[...this.audioStreamsMap.keys()].find(({id:Y})=>Y===(m==null?void 0:m.id)))!=null?te:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let Y=qs(n,d,(_=this.audioStreamsMap.get(g))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(ie=Y==null?void 0:Y.bitrate)!=null?ie:-1/0)}if(o){let Y=qs(o,d,(U=this.audioStreamsMap.get(g))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(ne=Y==null?void 0:Y.bitrate)!=null?ne:-1/0)}}let I=Jt(d,{container:this.elementSize$.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}),T=r?I!=null?I:n:n!=null?n:I,x=g&&pb(T,d,($=this.audioStreamsMap.get(g))!=null?$:[],{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}),A=(P=this.videoTracksMap.get(T))==null?void 0:P.representation,w=x&&((K=this.audioTracksMap.get(x))==null?void 0:K.representation);if(A&&w)return[A,w];if(A&&!w&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:V.ErrorCategory.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Me(this.video),this.tracer.end()}};var Ra=class extends Tr{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/es2015");var $a=class extends Tr{constructor(e){super(e),this.liveOffset=new Pt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((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=Dv(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 jv=X(Bs(),1);var z=require("@vkontakte/videoplayer-shared/es2015");var ot={};var ni=(a,e)=>new z.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),La=class{constructor(e){this.subscription=new z.Subscription;this.videoState=new j("initializing");this.textTracksManager=new ze;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,z.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,z.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,z.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,z.assertNever)(e)}break;default:(0,z.assertNever)(t)}};this.video=Le(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(Se(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:z.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,jv.default)(import("hls.js").then(i=>{e||(ot.Hls=i.default,ot.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,z.assertNonNullable)(ot.Hls,"hls.js not loaded"),this.hls=new ot.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,z.assertNonNullable)(ot.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:z.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=De(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(mt(this.video,e.isLooped,r)),this.subscription.add(Ce(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ye(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ke(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,z.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ni(this.hls,ot.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:z.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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(ni(this.hls,ot.Events.MANIFEST_PARSED).pipe((0,z.map)(({levels:l})=>l.reduce((d,c)=>{var T,x;let p=c.name||c.height.toString(10),{width:h,height:m}=c,g=(x=zt((T=c.attrs.QUALITY)!=null?T:""))!=null?x:(0,z.videoSizeToQuality)({width:h,height:m});if(!g)return d;let v=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,I={id:p.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:v};return this.trackLevels.set(p,{track:I,level:c}),d.push(I),d},[]))),t.availableVideoTracks$),s(ni(this.hls,ot.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(ni(this.hls,ot.Events.LEVEL_LOADING).pipe((0,z.map)(({url:l})=>Se(l))),t.hostname$),s(ni(this.hls,ot.Events.FRAG_CHANGED),l=>{var p,h,m,g;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=d==null?void 0:d.endPTS)!=null?p:0)-((h=d==null?void 0:d.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=c==null?void 0:c.endPTS)!=null?m:0)-((g=c==null?void 0:c.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 d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=ni(this.hls,ot.Events.LEVEL_SWITCHED).pipe((0,z.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,z.filter)(z.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Yt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,z.isNullable)(l))return;let d=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,z.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,z.observableFrom)(["init"])).pipe((0,z.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)}playIfAllowed(){return O(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:z.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),k(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"),k(this.params.desiredState.playbackState,"stopped",!0)}};var Gv="X-Playback-Duration",nl=a=>O(void 0,null,function*(){var i;let e=yield kt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Gv)?parseInt(e.headers.get(Gv),10):void 0});var G=require("@vkontakte/videoplayer-shared/es2015");var ul=X($o(),1);var fn=require("@vkontakte/videoplayer-shared/es2015");var JR=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,fn.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},XR=(a,e)=>{var s,n;let t=a.split(`
124
- `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,ul.default)(l[1].split(",").map(T=>T.split("="))),p=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,h=JR(c),m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,v;if(c.RESOLUTION){let[T,x]=c.RESOLUTION.split("x").map(A=>parseInt(A,10));T&&x&&(v={width:T,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(d){let c=(0,ul.default)(d[1].split(",").map(g=>g.split("=")).map(([g,v])=>[g,v.replace(/^"|"$/g,"")])),p=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,m=c.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)}),ol=0,Qv=(r,...i)=>O(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield kt(a)).text();ol+=1;try{let{qualityManifests:o,textTracks:u}=XR(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(ol<=t.manifestRetryMaxCount)return yield ZR((0,fn.getExponentialDelay)(ol-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Qv(a,e,t)}return{qualityManifests:[],textTracks:[]}}),mn=Qv;var Ma=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new j("stopped");this.textTracksManager=new ze;this.manifests$=new G.ValueSubject([]);this.liveOffset=new Pt;this.manifestStartTime$=new G.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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};var t;this.params=e,this.video=Le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:G.VideoQuality.INVARIANT,url:this.params.source.url},mn(we(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:G.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:G.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new G.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(c=(d=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:G.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=De(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(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ye(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ke(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,G.filterChanged)(),(0,G.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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,G.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Se(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,G.combine)({startTime:this.manifestStartTime$.pipe((0,G.filter)(G.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,G.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,G.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,G.observableFrom)(["init"])).pipe((0,G.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 o,u;let e=this.selectManifest();if((0,G.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:l,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[c,p]of[[l,"mq"],[d,"lq"]]){let h=String(parseFloat(c||""));p&&c&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=we(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),nl(n).then(l=>{var d;if(!(0,G.isNullable)(l))this.maxSeekBackTime$.next(l);else{let c=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();if((0,G.isNullable)(c)||!isFinite(c))try{kt(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();nl(g).then(v=>{(0,G.isNullable)(v)||this.maxSeekBackTime$.next(v)})}})}catch(p){}}})}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.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()}};var ee=require("@vkontakte/videoplayer-shared/es2015");var Ca=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new j("stopped");this.textTracksManager=new ze;this.manifests$=new ee.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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,ee.assertNever)(t)}};this.params=e,this.video=Le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ee.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(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),mn(we(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:ee.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(c=(d=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:ee.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=De(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,ee.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ye(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ee.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(Se(g.url)))}let c=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,ee.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!ee.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,ee.merge)((0,ee.fromEvent)(o,"addtrack"),(0,ee.fromEvent)(o,"removetrack"),(0,ee.fromEvent)(o,"change"),(0,ee.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,ee.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ee.observableFrom)(["init"])).pipe((0,ee.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,ee.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,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&i.searchParams.set(d,c)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ee.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Wv=X(Fr(),1),Da=X(Fi(),1);var se=require("@vkontakte/videoplayer-shared/es2015");var Oa=class{constructor(e){this.subscription=new se.Subscription;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new ze;this.syncPlayback=()=>{var u,l,d;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((d=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:d.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,se.assertNever)(e)}};this.params=e,this.video=Le(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Wv.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,Da.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:se.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=De(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,se.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ye(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ke(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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,se.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,se.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,se.observableFrom)(["init"])).pipe((0,se.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,se.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,se.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=xa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Se(t))}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:se.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,Da.default)(this.trackUrls).find(c=>!(0,se.isInvariantQuality)(c.track.quality)&&(0,se.isLowerOrEqual)(c.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,d=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&d&&(0,se.isHigherOrEqual)(d.quality,u.quality)&&(t=u),!t){let c=(0,Da.default)(this.trackUrls).filter(h=>!(0,se.isInvariantQuality)(h.track.quality)&&(0,se.isHigher)(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Da.default)(this.trackUrls).map(l=>l.track);t=Jt(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 le=require("@vkontakte/videoplayer-shared/es2015");var zv=require("@vkontakte/videoplayer-shared/es2015");var Yv=["stun:videostun.mycdn.me:80"],e$=1e3,t$=3,ll=()=>null,bn=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=ll;this.externalStopCallback=ll;this.externalErrorCallback=ll;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return O(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return O(this,null,function*(){try{let e={iceServers:[{urls:Yv}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return O(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return O(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:zv.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return O(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return O(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),e$)}normalizeOptions(e={}){let t={stunServerList:Yv,maxRetryNumber:t$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ba=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new le.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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,le.assertNever)(e)}};this.subscription=new le.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Le(e.container,e.tuning),this.liveStreamClient=new bn(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:le.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,le.merge)(this.videoState.stateChangeStarted$.pipe((0,le.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,le.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=De(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(Ke(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(Ce(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,le.assertNever)(n.to)}},r)).add((0,le.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,le.observableFrom)(["init"])).pipe((0,le.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(Se(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:le.VideoQuality.INVARIANT}),this.video.srcObject=e,k(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:le.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:le.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Va=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/es2015");var Ct=require("@vkontakte/videoplayer-shared/es2015"),Kv=a=>new Ct.Observable(e=>{let t=new Ct.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Ct.map)(({from:l,to:d})=>`${l}-${d}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Ct.map)(({type:l})=>l!==void 0)),n=new Ct.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 Ze=require("@vkontakte/videoplayer-shared/es2015");function Jv(){return new(window.AudioContext||window.webkitAudioContext)}var Xv=require("@vkontakte/videoplayer-shared/es2015");var _a=class _a{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new He;this.subscriptions=new Ze.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,Ze.filter)(s=>!!s.type),(0,Ze.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){Xv.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,Ze.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,Ze.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,Ze.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}initAudioContextOnce(e){return O(this,null,function*(){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"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:_a.errorId,category:Ze.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${_a.errorId} exception`,thrown:e})}};_a.errorId="VolumeMultiplierManager";var oi=_a;var r$={chunkDuration:5e3,maxParallelRequests:5},Na=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("")};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,cl.default)(i,l)),...t.filter(l=>(0,cl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new Va(s);let n=[...Du(!0),...Du(!1)];this.chromecastFormatsIterator=new Va(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&&oi.isSupported()&&(this.volumeMultiplierManager=new oi(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 Ra(H(R({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new $a(H(R({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ei||!this.params.tuning.useHlsJs?new Ca(H(R({},n),{source:o})):new La(H(R({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ma(H(R({},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 Oa(H(R({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Tb(H(R({},n),{source:o,config:H(R({},r$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ba({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(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 Ni({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 H(R({},e),{url:r(e.url)})}return(0,eS.default)((0,Zv.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))),Kv({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),d=r<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n=H(R({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d}),d?(r++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var N=require("@vkontakte/videoplayer-shared/es2015");var i$=5e3,tS="one_video_throughput",rS="one_video_rtt",Dt=window.navigator.connection,iS=()=>{let a=Dt==null?void 0:Dt.downlink;if((0,N.isNonNullable)(a)&&a!==10)return a*1e3},aS=()=>{let a=Dt==null?void 0:Dt.rtt;if((0,N.isNonNullable)(a)&&a!==3e3)return a},sS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},dl=class a{constructor(e){this.subscription=new N.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(tS)||(e.useBrowserEstimation?iS():void 0)||i$,r=(s=(i=a.load(rS))!=null?i:e.useBrowserEstimation?aS():void 0)!=null?s:0;if(this.throughput$=new N.ValueSubject(t),this.rtt$=new N.ValueSubject(r),this.rttAdjustedThroughput$=new N.ValueSubject(sS(t,r,e.rttPenaltyRequestSize)),this.throughput=yr.getSmoothedValue(t,-1,e),this.rtt=yr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=iS();u&&this.throughput.next(u);let l=aS();(0,N.isNonNullable)(l)&&this.rtt.next(l)};Dt&&"onchange"in Dt&&this.subscription.add((0,N.fromEvent)(Dt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{N.safeStorage.set(tS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{N.safeStorage.set(rS,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,N.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,N.map)(({throughput:n,rtt:o})=>sS(n,o,e.rttPenaltyRequestSize)),(0,N.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,N.now)(),i=new N.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,N.fromEvent)(e,"progress").pipe((0,N.once)()).subscribe(s=>{t=s.loaded,r=(0,N.now)()}));break;case 1:case 0:i.add((0,N.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,N.now)()}));break}i.add((0,N.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,N.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,N.now)(),n=0,o=(0,N.now)(),u=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=p=>O(this,[p],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(i,(0,N.now)()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=(0,N.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=c.byteLength,s=(0,N.now)()}else n+=c.byteLength;o=(0,N.now)()}else i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,N.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,N.now)()-o,this.concurrentDownloads.size),n=0,o=(0,N.now)());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=N.safeStorage.get(e);if((0,N.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},nS=dl;var Fa=require("@vkontakte/videoplayer-shared/es2015");var oS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Fa.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Fa.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:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1},uS=a=>{var e;return H(R({},(0,Fa.fillWithDefault)(a,oS)),{configName:[...(e=a.configName)!=null?e:[],...oS.configName]})};var f=require("@vkontakte/videoplayer-shared/es2015");var Ot=require("@vkontakte/videoplayer-shared/es2015"),pl=({seekState:a,position$:e})=>(0,Ot.merge)(a.stateChangeEnded$.pipe((0,Ot.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Ot.filter)(Ot.isNonNullable)),e.pipe((0,Ot.filter)(()=>a.getState().state==="none")));var lS=require("@vkontakte/videoplayer-shared/es2015"),cS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,lS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var gn=require("@vkontakte/videoplayer-shared/es2015"),dS=(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,gn.filter)(i=>i.length>0),(0,gn.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var qa=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.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),isLowLatency:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({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({}),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:nb};if(this.initLogs(),this.tuning=uS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new us({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new nS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return(0,pS.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),d=`Player.${String(i)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:f.ErrorCategory.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var s,n,o;this.config=e;let i=e,{container:t}=i,r=Yl(i,["container"]);return this.tracer.log("initVideo",(0,f.flattenObject)(r)),this.domContainer=cS(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Na({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Qi()?(this.tracer.log("request play from hidden tab"),(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-.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,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}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=>R({type:"external"},t))),this}selectTextTrack(e){var t;return dS(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",R({},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(this.info.autoQualityLimits$)),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(H(R({},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:pl({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(pl({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.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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((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=Jt(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),sb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>ab(r)),this.providerContainer.current$.subscribe(({type:r})=>qi("provider",r)),e.duration$.subscribe(r=>qi("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>qi("tracks",r)),this.events.fatalError$.subscribe(new $e("fatalError")),this.events.managedError$.subscribe(new $e("managedError")),e.position$.subscribe(new $e("position")),e.currentVideoTrack$.pipe((0,f.map)(r=>r==null?void 0:r.quality)).subscribe(new $e("quality")),this.info.currentBuffer$.subscribe(new $e("buffer")),e.isBuffering$.subscribe(new $e("isBuffering"))].forEach(r=>this.subscription.add(r)),qi("codecs",rg())}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=()=>O(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category: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/es2015"),a$=`@vkontakte/videoplayer-core@${Pn}`;
123
+ `;var fn=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(Uv,this.gl.VERTEX_SHADER),r=this.createShader(Hv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,d=t+i,c=e-r,p=t+i;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Te=require("@vkontakte/videoplayer-shared/es2015"),ol=class{constructor(){this.isSeeked$=new Te.ValueSubject(!1);this.isBuffering$=new Te.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Te.Subscription}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,Te.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,Te.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,Te.combine)({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if((0,Te.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),d=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,Te.now)(),p=n&&this.currentStallsCount>=n,h=i&&!r&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,m=s&&c-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&c-d>=s+u&&t>=s;(p||h||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Te.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Te.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},jv=ol;var _e=require("@vkontakte/videoplayer-shared/es2015"),mn=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 q.Subscription;this.videoState=new j("stopped");this.textTracksManager=new Ke;this.droppedFramesManager=new js;this.stallsManager=new jv;this.elementSizeManager=new mn;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.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"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&k(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"&&k(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"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,q.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new fn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=Le(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(Se(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=De(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:q.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(){var d;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,q.filter)(c=>!!c.length),(0,q.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,q.map)(c=>c.to.state!=="none"),(0,q.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,q.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,q.filter)(q.isNonNullable),(0,q.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,q.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if((0,q.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of p.audio){m.push(tl(g));let v=[];for(let I of g.representations){let T=Dv(I);v.push(T),this.audioTracksMap.set(T,{stream:g,representation:I})}this.audioStreamsMap.set(g,v)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of p.video){h.push(rl(m));let g=[];for(let v of m.representations){let I=Cv(H(R({},v),{streamId:m.id}));I&&(g.push(I),this.videoTracksMap.set(I,{stream:m,representation:v}))}this.videoStreamsMap.set(m,g)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let m of p.text)for(let g of m.representations){let v=Ov(m,g);this.textTracksMap.set(v,{stream:m,representation:g})}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:q.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,q.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,q.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(!(0,Gv.default)(["manifest_ready","running"],c)||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,g]=h,v=[...this.videoTracksMap.keys()].find(T=>{var x;return((x=this.videoTracksMap.get(T))==null?void 0:x.representation.id)===m.id});(0,q.isNonNullable)(v)&&(this.stallsManager.lastVideoTrackSelected=v);let I=this.params.desiredState.autoVideoTrackLimits.getTransition();if(I&&this.params.output.autoVideoTrackLimits$.next(I.to),c==="manifest_ready")this.player.initRepresentations(m.id,g==null?void 0:g.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),g){let T=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",g.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,q.filterChanged)()).subscribe(c=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.videoStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.videoStream.setState(g.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(rl(m))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,q.filterChanged)()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:v}])=>v.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.audioStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.audioStream.setState(g.to),e.currentAudioStream$.next(tl(m))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),(d=this.textTracksManager)==null||d.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,q.map)(({to:c})=>c==="ready"),(0,q.filterChanged)());this.subscription.add((0,q.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,q.merge)(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,q.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var N,Q,oe,J,W,te,B,ie,U,ne,$,P,K;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(N=e.videoTrack.getState())==null?void 0:N.id,n=[...this.videoTracksMap.keys()].find(({id:Y})=>Y===i),o=t.currentVideoTrack$.getValue(),u=((J=(oe=e.videoStream.getState())!=null?oe:n&&((Q=this.videoTracksMap.get(n))==null?void 0:Q.stream))!=null?J:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:Y})=>Y===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=vt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(W=e.audioStream.getState())!=null?W:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(te=[...this.audioStreamsMap.keys()].find(({id:Y})=>Y===(m==null?void 0:m.id)))!=null?te:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let Y=Us(n,d,(B=this.audioStreamsMap.get(g))!=null?B:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(ie=Y==null?void 0:Y.bitrate)!=null?ie:-1/0)}if(o){let Y=Us(o,d,(U=this.audioStreamsMap.get(g))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(ne=Y==null?void 0:Y.bitrate)!=null?ne:-1/0)}}let I=Xt(d,{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}),T=r?I!=null?I:n:n!=null?n:I,x=g&&fb(T,d,($=this.audioStreamsMap.get(g))!=null?$:[],{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}),A=(P=this.videoTracksMap.get(T))==null?void 0:P.representation,w=x&&((K=this.audioTracksMap.get(x))==null?void 0:K.representation);if(A&&w)return[A,w];if(A&&!w&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:q.ErrorCategory.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Me(this.video),this.tracer.end()}};var $a=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 rr=require("@vkontakte/videoplayer-shared/es2015");var La=class extends Ir{constructor(e){super(e),this.liveOffset=new At,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((0,rr.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,rr.combine)({interval:(0,rr.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,rr.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,rr.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Vv(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 Qv=X(Bs(),1);var z=require("@vkontakte/videoplayer-shared/es2015");var ut={};var oi=(a,e)=>new z.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ma=class{constructor(e){this.subscription=new z.Subscription;this.videoState=new j("initializing");this.textTracksManager=new Ke;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,z.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,z.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,z.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,z.assertNever)(e)}break;default:(0,z.assertNever)(t)}};this.video=Le(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(Se(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:z.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Qv.default)(import("hls.js").then(i=>{e||(ut.Hls=i.default,ut.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,z.assertNonNullable)(ut.Hls,"hls.js not loaded"),this.hls=new ut.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,z.assertNonNullable)(ut.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:z.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=De(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(bt(this.video,e.isLooped,r)),this.subscription.add(Ce(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ze(this.video,e.playbackRate,i.playbackRateState$,r)),s(Je(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,z.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(oi(this.hls,ut.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:z.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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(oi(this.hls,ut.Events.MANIFEST_PARSED).pipe((0,z.map)(({levels:l})=>l.reduce((d,c)=>{var T,x;let p=c.name||c.height.toString(10),{width:h,height:m}=c,g=(x=Kt((T=c.attrs.QUALITY)!=null?T:""))!=null?x:(0,z.videoSizeToQuality)({width:h,height:m});if(!g)return d;let v=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,I={id:p.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:h,height:m},fps:v};return this.trackLevels.set(p,{track:I,level:c}),d.push(I),d},[]))),t.availableVideoTracks$),s(oi(this.hls,ut.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,h=c.attrs.URI||"",m=c.lang;d.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(oi(this.hls,ut.Events.LEVEL_LOADING).pipe((0,z.map)(({url:l})=>Se(l))),t.hostname$),s(oi(this.hls,ut.Events.FRAG_CHANGED),l=>{var p,h,m,g;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=d==null?void 0:d.endPTS)!=null?p:0)-((h=d==null?void 0:d.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=c==null?void 0:c.endPTS)!=null?m:0)-((g=c==null?void 0:c.startPTS)!=null?g:0))*1e3)}),this.subscription.add(zt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=oi(this.hls,ut.Events.LEVEL_SWITCHED).pipe((0,z.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,z.filter)(z.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(zt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if((0,z.isNullable)(l))return;let d=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,z.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,z.observableFrom)(["init"])).pipe((0,z.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)}playIfAllowed(){return O(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:z.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),k(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"),k(this.params.desiredState.playbackState,"stopped",!0)}};var Wv="X-Playback-Duration",ul=a=>O(void 0,null,function*(){var i;let e=yield Rt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Wv)?parseInt(e.headers.get(Wv),10):void 0});var G=require("@vkontakte/videoplayer-shared/es2015");var cl=X(Mo(),1);var bn=require("@vkontakte/videoplayer-shared/es2015");var ZR=a=>{let e=null;if(a.QUALITY&&(e=Kt(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},e$=(a,e)=>{var s,n;let t=a.split(`
124
+ `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,cl.default)(l[1].split(",").map(T=>T.split("="))),p=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,h=ZR(c),m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,v;if(c.RESOLUTION){let[T,x]=c.RESOLUTION.split("x").map(A=>parseInt(A,10));T&&x&&(v={width:T,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(d){let c=(0,cl.default)(d[1].split(",").map(g=>g.split("=")).map(([g,v])=>[g,v.replace(/^"|"$/g,"")])),p=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,m=c.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}},t$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),ll=0,Yv=(r,...i)=>O(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield Rt(a)).text();ll+=1;try{let{qualityManifests:o,textTracks:u}=e$(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(ll<=t.manifestRetryMaxCount)return yield t$((0,bn.getExponentialDelay)(ll-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Yv(a,e,t)}return{qualityManifests:[],textTracks:[]}}),gn=Yv;var Ca=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new j("stopped");this.textTracksManager=new Ke;this.manifests$=new G.ValueSubject([]);this.liveOffset=new At;this.manifestStartTime$=new G.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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};var t;this.params=e,this.video=Le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:G.VideoQuality.INVARIANT,url:this.params.source.url},gn(we(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:G.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:G.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new G.ValueSubject((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(c=(d=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:G.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=De(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(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),s(Je(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe((0,G.filterChanged)(),(0,G.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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,G.isNonNullable)(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Se(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,G.combine)({startTime:this.manifestStartTime$.pipe((0,G.filter)(G.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,G.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,G.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,G.observableFrom)(["init"])).pipe((0,G.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 o,u;let e=this.selectManifest();if((0,G.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:l,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[c,p]of[[l,"mq"],[d,"lq"]]){let h=String(parseFloat(c||""));p&&c&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=we(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ul(n).then(l=>{var d;if(!(0,G.isNullable)(l))this.maxSeekBackTime$.next(l);else{let c=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();if((0,G.isNullable)(c)||!isFinite(c))try{Rt(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();ul(g).then(v=>{(0,G.isNullable)(v)||this.maxSeekBackTime$.next(v)})}})}catch(p){}}})}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.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()}};var ee=require("@vkontakte/videoplayer-shared/es2015");var Da=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new j("stopped");this.textTracksManager=new Ke;this.manifests$=new ee.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"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?k(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,ee.assertNever)(t)}};this.params=e,this.video=Le(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ee.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(Se(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),gn(we(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:ee.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(c=(d=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:ee.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=De(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,ee.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ee.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(Se(g.url)))}let c=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,ee.map)(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!ee.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,ee.merge)((0,ee.fromEvent)(o,"addtrack"),(0,ee.fromEvent)(o,"removetrack"),(0,ee.fromEvent)(o,"change"),(0,ee.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,ee.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ee.observableFrom)(["init"])).pipe((0,ee.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,ee.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,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&i.searchParams.set(d,c)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ee.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var zv=X(qr(),1),Oa=X(qi(),1);var se=require("@vkontakte/videoplayer-shared/es2015");var Va=class{constructor(e){this.subscription=new se.Subscription;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new Ke;this.syncPlayback=()=>{var u,l,d;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((d=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:d.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,se.assertNever)(e)}};this.params=e,this.video=Le(e.container,e.tuning),this.params.output.element$.next(this.video),(0,zv.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Oa.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:se.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=De(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,se.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),s(Je(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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,se.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,se.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,se.observableFrom)(["init"])).pipe((0,se.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,se.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,se.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Pa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Se(t))}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:se.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,Oa.default)(this.trackUrls).find(c=>!(0,se.isInvariantQuality)(c.track.quality)&&(0,se.isLowerOrEqual)(c.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,d=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&d&&(0,se.isHigherOrEqual)(d.quality,u.quality)&&(t=u),!t){let c=(0,Oa.default)(this.trackUrls).filter(h=>!(0,se.isInvariantQuality)(h.track.quality)&&(0,se.isHigher)(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Oa.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 le=require("@vkontakte/videoplayer-shared/es2015");var Jv=require("@vkontakte/videoplayer-shared/es2015");var Kv=["stun:videostun.mycdn.me:80"],r$=1e3,i$=3,dl=()=>null,vn=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=dl;this.externalStopCallback=dl;this.externalErrorCallback=dl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return O(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return O(this,null,function*(){try{let e={iceServers:[{urls:Kv}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return O(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return O(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:Jv.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return O(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return O(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),r$)}normalizeOptions(e={}){let t={stunServerList:Kv,maxRetryNumber:i$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ba=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new le.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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return(0,le.assertNever)(e)}};this.subscription=new le.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Le(e.container,e.tuning),this.liveStreamClient=new vn(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:le.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,le.merge)(this.videoState.stateChangeStarted$.pipe((0,le.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,le.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=De(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(Je(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(Ce(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,le.assertNever)(n.to)}},r)).add((0,le.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,le.observableFrom)(["init"])).pipe((0,le.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(Se(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:le.VideoQuality.INVARIANT}),this.video.srcObject=e,k(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:le.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Oe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:le.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var _a=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared/es2015");var Dt=require("@vkontakte/videoplayer-shared/es2015"),Xv=a=>new Dt.Observable(e=>{let t=new Dt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Dt.map)(({from:l,to:d})=>`${l}-${d}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Dt.map)(({type:l})=>l!==void 0)),n=new Dt.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 et=require("@vkontakte/videoplayer-shared/es2015");function Zv(){return new(window.AudioContext||window.webkitAudioContext)}var eS=require("@vkontakte/videoplayer-shared/es2015");var Na=class Na{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new je;this.subscriptions=new et.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,et.filter)(s=>!!s.type),(0,et.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){eS.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,et.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,et.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,et.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}initAudioContextOnce(e){return O(this,null,function*(){let{volumeMultiplier:t}=this,r=Zv();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Na.errorId,category:et.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Na.errorId} exception`,thrown:e})}};Na.errorId="VolumeMultiplierManager";var ui=Na;var a$={chunkDuration:5e3,maxParallelRequests:5},Fa=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("")};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=sg([...og(this.params.tuning),...ng(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,pl.default)(i,l)),...t.filter(l=>(0,pl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new _a(s);let n=[...Vu(!0),...Vu(!1)];this.chromecastFormatsIterator=new _a(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&&ui.isSupported()&&(this.volumeMultiplierManager=new ui(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 $a(H(R({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new La(H(R({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ti||!this.params.tuning.useHlsJs?new Da(H(R({},n),{source:o})):new Ma(H(R({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ca(H(R({},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 Va(H(R({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Eb(H(R({},n),{source:o,config:H(R({},a$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ba({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(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 Fi({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 H(R({},e),{url:r(e.url)})}return(0,rS.default)((0,tS.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),d=r<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n=H(R({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d}),d?(r++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var _=require("@vkontakte/videoplayer-shared/es2015");var s$=5e3,iS="one_video_throughput",aS="one_video_rtt",Ot=window.navigator.connection,sS=()=>{let a=Ot==null?void 0:Ot.downlink;if((0,_.isNonNullable)(a)&&a!==10)return a*1e3},nS=()=>{let a=Ot==null?void 0:Ot.rtt;if((0,_.isNonNullable)(a)&&a!==3e3)return a},oS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},hl=class a{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(iS)||(e.useBrowserEstimation?sS():void 0)||s$,r=(s=(i=a.load(aS))!=null?i:e.useBrowserEstimation?nS():void 0)!=null?s:0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(r),this.rttAdjustedThroughput$=new _.ValueSubject(oS(t,r,e.rttPenaltyRequestSize)),this.throughput=Tr.getSmoothedValue(t,-1,e),this.rtt=Tr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=sS();u&&this.throughput.next(u);let l=nS();(0,_.isNonNullable)(l)&&this.rtt.next(l)};Ot&&"onchange"in Ot&&this.subscription.add((0,_.fromEvent)(Ot,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{_.safeStorage.set(iS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{_.safeStorage.set(aS,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,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:n,rtt:o})=>oS(n,o,e.rttPenaltyRequestSize)),(0,_.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,_.now)(),i=new _.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,_.fromEvent)(e,"progress").pipe((0,_.once)()).subscribe(s=>{t=s.loaded,r=(0,_.now)()}));break;case 1:case 0:i.add((0,_.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,_.now)()}));break}i.add((0,_.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,_.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,_.now)(),n=0,o=(0,_.now)(),u=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=p=>O(this,[p],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(i,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=(0,_.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=c.byteLength,s=(0,_.now)()}else n+=c.byteLength;o=(0,_.now)()}else i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,_.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,_.now)()-o,this.concurrentDownloads.size),n=0,o=(0,_.now)());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=_.safeStorage.get(e);if((0,_.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},uS=hl;var qa=require("@vkontakte/videoplayer-shared/es2015");var lS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:qa.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:qa.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:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,exposeInternalsToGlobal:!1},cS=a=>{var e;return H(R({},(0,qa.fillWithDefault)(a,lS)),{configName:[...(e=a.configName)!=null?e:[],...lS.configName]})};var f=require("@vkontakte/videoplayer-shared/es2015");var Vt=require("@vkontakte/videoplayer-shared/es2015"),fl=({seekState:a,position$:e})=>(0,Vt.merge)(a.stateChangeEnded$.pipe((0,Vt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Vt.filter)(Vt.isNonNullable)),e.pipe((0,Vt.filter)(()=>a.getState().state==="none")));var dS=require("@vkontakte/videoplayer-shared/es2015"),pS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,dS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Sn=require("@vkontakte/videoplayer-shared/es2015"),hS=(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,Sn.filter)(i=>i.length>0),(0,Sn.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ua=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 j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),isLowLatency:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({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({}),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};if(this.initLogs(),this.tuning=cS(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 uS(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,fS.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),d=`Player.${String(i)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:f.ErrorCategory.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=Kl(i,["container"]);return this.tracer.log("initVideo",(0,f.flattenObject)(r)),this.domContainer=pS(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Fa({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.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,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-.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,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}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=>R({type:"external"},t))),this}selectTextTrack(e){var t;return hS(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",R({},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(this.info.autoQualityLimits$)),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(H(R({},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:fl({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(fl({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.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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((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=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,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})=>Ui("provider",r)),e.duration$.subscribe(r=>Ui("duration",r)),e.availableVideoTracks$.pipe((0,f.filter)(r=>!!r.length),(0,f.once)()).subscribe(r=>Ui("tracks",r)),this.events.fatalError$.subscribe(new $e("fatalError")),this.events.managedError$.subscribe(new $e("managedError")),e.position$.subscribe(new $e("position")),e.currentVideoTrack$.pipe((0,f.map)(r=>r==null?void 0:r.quality)).subscribe(new $e("quality")),this.info.currentBuffer$.subscribe(new $e("buffer")),e.isBuffering$.subscribe(new $e("isBuffering"))].forEach(r=>this.subscription.add(r)),Ui("codecs",ag())}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=()=>O(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category: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 yt=require("@vkontakte/videoplayer-shared/es2015"),n$=`@vkontakte/videoplayer-core@${wn}`;