@vkontakte/videoplayer-core 2.0.123-dev.cdb07745.0 → 2.0.123-dev.ebdb6ff0.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.123-dev.cdb07745.0
3
- * Tue, 17 Dec 2024 12:58:59 GMT
2
+ * @vkontakte/videoplayer-core v2.0.123-dev.ebdb6ff0.0
3
+ * Tue, 17 Dec 2024 15:30:00 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-123/doc/
5
5
  */
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 c=t[n](o),d=(o=c.value)instanceof An,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?r(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>r("throw",p,u,l))}catch(p){l(p)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[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,c,d,h,p,m,g,v,I;for(h in e)l=MT(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&Pd(n,h),m=o[h],c&&(a.dontCallGetSet?(I=LT(n,h),g=I&&I.value):g=n[h]),p=c&&g?g:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?v=CT(p,Pi):a.wrap&&c?v=DT(p):s&&$T(p)?v=RT(p):v=p,(a.sham||p&&p.sham||m&&m.sham)&&Nr(v,"sham",!0),Nr(o,h,v),s&&(d=t+"Prototype",Pd(_r,d)||Nr(_r,d,{}),Nr(_r[d],h,p),a.real&&u&&(l||!u[h])&&Nr(u,h,p)))}});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&&h)return h;if(!ys&&I&&I in c)return c[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,c=a.prototype,d=c[Li]||c["@@iterator"]||i&&c[i],h=!ys&&d||o(i),p=e==="Array"&&c.entries||d,m,g,v;if(p&&(m=Zp(p.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&&d&&d.name!==Mi&&(!Ss&&ex?JE(c,"name",Mi):(l=!0,h=function(){return WE(d,this)})),i)if(g={values:o(Mi),keys:s?h:o(ih),entries:o(ah)},n)for(v in g)(ys||l||!(v in c))&&ko(c,v,g[v]);else QE({target:e,proto:!0,forced:ys||l},g);return(!Ss||n)&&c[Li]!==h&&ko(c,Li,h,{name:i}),th[e]=h,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,c,d,h,p,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(c=Mx(a),!c)throw new Cx(kx(a)+" is not iterable");if(Rx(c)){for(d=0,h=$x(a);h>d;d++)if(p=I(a[d]),p&&Ah(kh,p))return p;return new Is(!1)}l=Lx(a,c)}for(m=s?a.next:l.next;!(g=Ax(m,l)).done;){try{p=I(g.value)}catch(T){wh(l,"throw",T)}if(typeof p=="object"&&p&&Ah(kh,p))return p}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,c;try{i?(r||(e.rejection===um&&vA(e),e.rejection=cu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new sm("Promise-chain cycle")):(l=lm(u))?Kr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},dm=function(a,e){a.notified||(a.notified=!0,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,c=1;kA(e,function(d){var h=l++,p=!1;c++,xA(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||i(u))},s)}),--c||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((sC,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((pC,Dm)=>{"use strict";Uh();Rm();Cm();var ow=Qt();Dm.exports=ow("Promise","finally")});var Bm=b((hC,Vm)=>{"use strict";var uw=Om();Vm.exports=uw});var Bs=b((fC,_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((GC,Qm)=>{"use strict";Gm();var bw=Cr();Qm.exports=bw.Object.values});var zm=b((QC,Ym)=>{"use strict";var gw=Wm();Ym.exports=gw});var qi=b((WC,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((g0,tb)=>{"use strict";eb();var ww=Qt();tb.exports=ww("Array","at")});var ab=b((v0,ib)=>{"use strict";var kw=rb();ib.exports=kw});var Jr=b((S0,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,c=n?Qw(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&Hw(d)?(h=jw(d),u=kb(a,e,d,h,u,s-1)-1):(Gw(u+1),a[u]=d),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,c){var d;switch(Gu(c,0)){case"$":return"$";case"&":return a;case"`":return Qu(e,0,t);case"'":return Qu(e,n);case"<":d=i[Qu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=nR(h/10);return p===0?l:p<=o?r[p-1]===void 0?Gu(c,1):r[p-1]+Gu(c,1):l}d=r[h-1]}return d===void 0?"":d})}});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,c,d,h,p,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)),c=u.length,d=ER(1,c),h=Yu(o,u);h!==-1;)p=l?ai(t(u,h,o)):gR(u,o,h,[],void 0,t),g+=ev(o,m,h)+p,m=h+c,h=h+d>o.length?-1:Yu(o,u,h+d);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.123-dev.cdb07745.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=i=>t(i),document.body.appendChild(r)});var ls=class{constructor(e){this.connection$=new F.ValueSubject(void 0);this.castState$=new F.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new F.Subject;this.realCastState$=new F.ValueSubject("NOT_AVAILABLE");this.subscription=new F.Subscription;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,F.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||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.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,F.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,F.assertNever)(i.sessionState)}})).add((0,F.merge)((0,F.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,F.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,F.map)(i=>i.castState)),(0,F.observableFrom)([r.getCastState()])).pipe((0,F.filterChanged)(),(0,F.map)(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 c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,F.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,F.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:F.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},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 c=t[e];(0,L.assertNonNullable)(c);let d=(0,L.getHighestQuality)(Object.keys(c));(0,L.assertNonNullable)(d);let h=c[d];(0,L.assertNonNullable)(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,L.assertNonNullable)(c),r=we(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,L.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,L.isNonNullable)(o)&&(n.metadata.title=o),(0,L.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add((0,L.timeout)(qm).subscribe(()=>s(`timeout(${qm})`)))});(0,Um.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:L.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var 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(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},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,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((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,c,d;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:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,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)),c=new D.Subject,d=.3,h;l.subscribe(x=>{a.loop&&(0,D.isNonNullable)(h)&&(0,D.isNonNullable)(x)&&h>=a.duration-d&&x<=d&&c.next(h),h=x});let p=e("pause").pipe((0,D.filter)(()=>!a.error&&h!==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$:p,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(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:`
6
+ "use strict";var kS=Object.create;var bi=Object.defineProperty,RS=Object.defineProperties,$S=Object.getOwnPropertyDescriptor,LS=Object.getOwnPropertyDescriptors,MS=Object.getOwnPropertyNames,is=Object.getOwnPropertySymbols,DS=Object.getPrototypeOf,An=Object.prototype.hasOwnProperty,Jl=Object.prototype.propertyIsEnumerable;var CS=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var ht=Math.pow,Kl=(a,e,t)=>e in a?bi(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,k=(a,e)=>{for(var t in e||(e={}))An.call(e,t)&&Kl(a,t,e[t]);if(is)for(var t of is(e))Jl.call(e,t)&&Kl(a,t,e[t]);return a},F=(a,e)=>RS(a,LS(e));var Xl=(a,e)=>{var t={};for(var r in a)An.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&is)for(var r of is(a))e.indexOf(r)<0&&Jl.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),OS=(a,e)=>{for(var t in e)bi(a,t,{get:e[t],enumerable:!0})},Zl=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of MS(e))!An.call(a,i)&&i!==t&&bi(a,i,{get:()=>e[i],enumerable:!(r=$S(e,i))||r.enumerable});return a};var X=(a,e,t)=>(t=a!=null?kS(DS(a)):{},Zl(e||!a||!a.__esModule?bi(t,"default",{value:a,enumerable:!0}):t,a)),VS=a=>Zl(bi({},"__esModule",{value:!0}),a);var L=(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())}),kn=function(a,e){this[0]=a,this[1]=e},fe=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof kn,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?r(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>r("throw",p,u,l))}catch(p){l(p)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[CS("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var he=b(($n,ec)=>{"use strict";var vi=function(a){return a&&a.Math===Math&&a};ec.exports=vi(typeof globalThis=="object"&&globalThis)||vi(typeof window=="object"&&window)||vi(typeof self=="object"&&self)||vi(typeof global=="object"&&global)||vi(typeof $n=="object"&&$n)||function(){return this}()||Function("return this")()});var Pe=b((h$,tc)=>{"use strict";tc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Si=b((m$,rc)=>{"use strict";var BS=Pe();rc.exports=!BS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Ln=b((f$,nc)=>{"use strict";var _S=Si(),sc=Function.prototype,ic=sc.apply,ac=sc.call;nc.exports=typeof Reflect=="object"&&Reflect.apply||(_S?ac.bind(ic):function(){return ac.apply(ic,arguments)})});var ve=b((b$,lc)=>{"use strict";var oc=Si(),uc=Function.prototype,Mn=uc.call,NS=oc&&uc.bind.bind(Mn,Mn);lc.exports=oc?NS:function(a){return function(){return Mn.apply(a,arguments)}}});var lr=b((g$,dc)=>{"use strict";var cc=ve(),FS=cc({}.toString),qS=cc("".slice);dc.exports=function(a){return qS(FS(a),8,-1)}});var Dn=b((v$,pc)=>{"use strict";var US=lr(),HS=ve();pc.exports=function(a){if(US(a)==="Function")return HS(a)}});var pe=b((S$,hc)=>{"use strict";var Cn=typeof document=="object"&&document.all;hc.exports=typeof Cn=="undefined"&&Cn!==void 0?function(a){return typeof a=="function"||a===Cn}:function(a){return typeof a=="function"}});var qe=b((y$,mc)=>{"use strict";var jS=Pe();mc.exports=!jS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ue=b((T$,fc)=>{"use strict";var GS=Si(),ns=Function.prototype.call;fc.exports=GS?ns.bind(ns):function(){return ns.apply(ns,arguments)}});var On=b(vc=>{"use strict";var bc={}.propertyIsEnumerable,gc=Object.getOwnPropertyDescriptor,QS=gc&&!bc.call({1:2},1);vc.f=QS?function(e){var t=gc(this,e);return!!t&&t.enumerable}:bc});var yi=b((E$,Sc)=>{"use strict";Sc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Tc=b((x$,yc)=>{"use strict";var WS=ve(),YS=Pe(),zS=lr(),Vn=Object,KS=WS("".split);yc.exports=YS(function(){return!Vn("z").propertyIsEnumerable(0)})?function(a){return zS(a)==="String"?KS(a,""):Vn(a)}:Vn});var Dr=b((P$,Ic)=>{"use strict";Ic.exports=function(a){return a==null}});var Qt=b((w$,Ec)=>{"use strict";var JS=Dr(),XS=TypeError;Ec.exports=function(a){if(JS(a))throw new XS("Can't call method on "+a);return a}});var cr=b((A$,xc)=>{"use strict";var ZS=Tc(),ey=Qt();xc.exports=function(a){return ZS(ey(a))}});var He=b((k$,Pc)=>{"use strict";var ty=pe();Pc.exports=function(a){return typeof a=="object"?a!==null:ty(a)}});var Cr=b((R$,wc)=>{"use strict";wc.exports={}});var Pt=b(($$,kc)=>{"use strict";var Bn=Cr(),_n=he(),ry=pe(),Ac=function(a){return ry(a)?a:void 0};kc.exports=function(a,e){return arguments.length<2?Ac(Bn[a])||Ac(_n[a]):Bn[a]&&Bn[a][e]||_n[a]&&_n[a][e]}});var Ti=b((L$,Rc)=>{"use strict";var iy=ve();Rc.exports=iy({}.isPrototypeOf)});var dr=b((M$,Mc)=>{"use strict";var ay=he(),$c=ay.navigator,Lc=$c&&$c.userAgent;Mc.exports=Lc?String(Lc):""});var Fn=b((D$,_c)=>{"use strict";var Bc=he(),Nn=dr(),Dc=Bc.process,Cc=Bc.Deno,Oc=Dc&&Dc.versions||Cc&&Cc.version,Vc=Oc&&Oc.v8,at,os;Vc&&(at=Vc.split("."),os=at[0]>0&&at[0]<4?1:+(at[0]+at[1]));!os&&Nn&&(at=Nn.match(/Edge\/(\d+)/),(!at||at[1]>=74)&&(at=Nn.match(/Chrome\/(\d+)/),at&&(os=+at[1])));_c.exports=os});var qn=b((C$,Fc)=>{"use strict";var Nc=Fn(),sy=Pe(),ny=he(),oy=ny.String;Fc.exports=!!Object.getOwnPropertySymbols&&!sy(function(){var a=Symbol("symbol detection");return!oy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Nc&&Nc<41})});var Un=b((O$,qc)=>{"use strict";var uy=qn();qc.exports=uy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Hn=b((V$,Uc)=>{"use strict";var ly=Pt(),cy=pe(),dy=Ti(),py=Un(),hy=Object;Uc.exports=py?function(a){return typeof a=="symbol"}:function(a){var e=ly("Symbol");return cy(e)&&dy(e.prototype,hy(a))}});var Ii=b((B$,Hc)=>{"use strict";var my=String;Hc.exports=function(a){try{return my(a)}catch(e){return"Object"}}});var mt=b((_$,jc)=>{"use strict";var fy=pe(),by=Ii(),gy=TypeError;jc.exports=function(a){if(fy(a))return a;throw new gy(by(a)+" is not a function")}});var Ei=b((N$,Gc)=>{"use strict";var vy=mt(),Sy=Dr();Gc.exports=function(a,e){var t=a[e];return Sy(t)?void 0:vy(t)}});var Wc=b((F$,Qc)=>{"use strict";var jn=Ue(),Gn=pe(),Qn=He(),yy=TypeError;Qc.exports=function(a,e){var t,r;if(e==="string"&&Gn(t=a.toString)&&!Qn(r=jn(t,a))||Gn(t=a.valueOf)&&!Qn(r=jn(t,a))||e!=="string"&&Gn(t=a.toString)&&!Qn(r=jn(t,a)))return r;throw new yy("Can't convert object to primitive value")}});var st=b((q$,Yc)=>{"use strict";Yc.exports=!0});var Jc=b((U$,Kc)=>{"use strict";var zc=he(),Ty=Object.defineProperty;Kc.exports=function(a,e){try{Ty(zc,a,{value:e,configurable:!0,writable:!0})}catch(t){zc[a]=e}return e}});var xi=b((H$,ed)=>{"use strict";var Iy=st(),Ey=he(),xy=Jc(),Xc="__core-js_shared__",Zc=ed.exports=Ey[Xc]||xy(Xc,{});(Zc.versions||(Zc.versions=[])).push({version:"3.38.0",mode:Iy?"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 Wn=b((j$,rd)=>{"use strict";var td=xi();rd.exports=function(a,e){return td[a]||(td[a]=e||{})}});var Or=b((G$,id)=>{"use strict";var Py=Qt(),wy=Object;id.exports=function(a){return wy(Py(a))}});var nt=b((Q$,ad)=>{"use strict";var Ay=ve(),ky=Or(),Ry=Ay({}.hasOwnProperty);ad.exports=Object.hasOwn||function(e,t){return Ry(ky(e),t)}});var Yn=b((W$,sd)=>{"use strict";var $y=ve(),Ly=0,My=Math.random(),Dy=$y(1 .toString);sd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Dy(++Ly+My,36)}});var we=b((Y$,od)=>{"use strict";var Cy=he(),Oy=Wn(),nd=nt(),Vy=Yn(),By=qn(),_y=Un(),Vr=Cy.Symbol,zn=Oy("wks"),Ny=_y?Vr.for||Vr:Vr&&Vr.withoutSetter||Vy;od.exports=function(a){return nd(zn,a)||(zn[a]=By&&nd(Vr,a)?Vr[a]:Ny("Symbol."+a)),zn[a]}});var dd=b((z$,cd)=>{"use strict";var Fy=Ue(),ud=He(),ld=Hn(),qy=Ei(),Uy=Wc(),Hy=we(),jy=TypeError,Gy=Hy("toPrimitive");cd.exports=function(a,e){if(!ud(a)||ld(a))return a;var t=qy(a,Gy),r;if(t){if(e===void 0&&(e="default"),r=Fy(t,a,e),!ud(r)||ld(r))return r;throw new jy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Uy(a,e)}});var Kn=b((K$,pd)=>{"use strict";var Qy=dd(),Wy=Hn();pd.exports=function(a){var e=Qy(a,"string");return Wy(e)?e:e+""}});var us=b((J$,md)=>{"use strict";var Yy=he(),hd=He(),Jn=Yy.document,zy=hd(Jn)&&hd(Jn.createElement);md.exports=function(a){return zy?Jn.createElement(a):{}}});var Xn=b((X$,fd)=>{"use strict";var Ky=qe(),Jy=Pe(),Xy=us();fd.exports=!Ky&&!Jy(function(){return Object.defineProperty(Xy("div"),"a",{get:function(){return 7}}).a!==7})});var vd=b(gd=>{"use strict";var Zy=qe(),eT=Ue(),tT=On(),rT=yi(),iT=cr(),aT=Kn(),sT=nt(),nT=Xn(),bd=Object.getOwnPropertyDescriptor;gd.f=Zy?bd:function(e,t){if(e=iT(e),t=aT(t),nT)try{return bd(e,t)}catch(r){}if(sT(e,t))return rT(!eT(tT.f,e,t),e[t])}});var Zn=b((eL,Sd)=>{"use strict";var oT=Pe(),uT=pe(),lT=/#|\.prototype\./,Pi=function(a,e){var t=dT[cT(a)];return t===hT?!0:t===pT?!1:uT(e)?oT(e):!!e},cT=Pi.normalize=function(a){return String(a).replace(lT,".").toLowerCase()},dT=Pi.data={},pT=Pi.NATIVE="N",hT=Pi.POLYFILL="P";Sd.exports=Pi});var Br=b((tL,Td)=>{"use strict";var yd=Dn(),mT=mt(),fT=Si(),bT=yd(yd.bind);Td.exports=function(a,e){return mT(a),e===void 0?a:fT?bT(a,e):function(){return a.apply(e,arguments)}}});var eo=b((rL,Id)=>{"use strict";var gT=qe(),vT=Pe();Id.exports=gT&&vT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=b((iL,Ed)=>{"use strict";var ST=He(),yT=String,TT=TypeError;Ed.exports=function(a){if(ST(a))return a;throw new TT(yT(a)+" is not an object")}});var pr=b(Pd=>{"use strict";var IT=qe(),ET=Xn(),xT=eo(),ls=ft(),xd=Kn(),PT=TypeError,to=Object.defineProperty,wT=Object.getOwnPropertyDescriptor,ro="enumerable",io="configurable",ao="writable";Pd.f=IT?xT?function(e,t,r){if(ls(e),t=xd(t),ls(r),typeof e=="function"&&t==="prototype"&&"value"in r&&ao in r&&!r[ao]){var i=wT(e,t);i&&i[ao]&&(e[t]=r.value,r={configurable:io in r?r[io]:i[io],enumerable:ro in r?r[ro]:i[ro],writable:!1})}return to(e,t,r)}:to:function(e,t,r){if(ls(e),t=xd(t),ls(r),ET)try{return to(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new PT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=b((sL,wd)=>{"use strict";var AT=qe(),kT=pr(),RT=yi();wd.exports=AT?function(a,e,t){return kT.f(a,e,RT(1,t))}:function(a,e,t){return a[e]=t,a}});var me=b((nL,kd)=>{"use strict";var wi=he(),$T=Ln(),LT=Dn(),MT=pe(),DT=vd().f,CT=Zn(),Nr=Cr(),OT=Br(),Fr=_r(),Ad=nt();xi();var VT=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 $T(a,this,arguments)};return e.prototype=a.prototype,e};kd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?wi:i?wi[t]:wi[t]&&wi[t].prototype,o=r?Nr:Nr[t]||Fr(Nr,t,{})[t],u=o.prototype,l,c,d,h,p,f,g,v,I;for(h in e)l=CT(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&Ad(n,h),f=o[h],c&&(a.dontCallGetSet?(I=DT(n,h),g=I&&I.value):g=n[h]),p=c&&g?g:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?v=OT(p,wi):a.wrap&&c?v=VT(p):s&&MT(p)?v=LT(p):v=p,(a.sham||p&&p.sham||f&&f.sham)&&Fr(v,"sham",!0),Fr(o,h,v),s&&(d=t+"Prototype",Ad(Nr,d)||Fr(Nr,d,{}),Fr(Nr[d],h,p),a.real&&u&&(l||!u[h])&&Fr(u,h,p)))}});var $d=b((oL,Rd)=>{"use strict";var BT=Math.ceil,_T=Math.floor;Rd.exports=Math.trunc||function(e){var t=+e;return(t>0?_T:BT)(t)}});var Ai=b((uL,Ld)=>{"use strict";var NT=$d();Ld.exports=function(a){var e=+a;return e!==e||e===0?0:NT(e)}});var Dd=b((lL,Md)=>{"use strict";var FT=Ai(),qT=Math.max,UT=Math.min;Md.exports=function(a,e){var t=FT(a);return t<0?qT(t+e,0):UT(t,e)}});var so=b((cL,Cd)=>{"use strict";var HT=Ai(),jT=Math.min;Cd.exports=function(a){var e=HT(a);return e>0?jT(e,9007199254740991):0}});var qr=b((dL,Od)=>{"use strict";var GT=so();Od.exports=function(a){return GT(a.length)}});var no=b((pL,Bd)=>{"use strict";var QT=cr(),WT=Dd(),YT=qr(),Vd=function(a){return function(e,t,r){var i=QT(e),s=YT(i);if(s===0)return!a&&-1;var n=WT(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}};Bd.exports={includes:Vd(!0),indexOf:Vd(!1)}});var ki=b((hL,_d)=>{"use strict";_d.exports=function(){}});var Nd=b(()=>{"use strict";var zT=me(),KT=no().includes,JT=Pe(),XT=ki(),ZT=JT(function(){return!Array(1).includes()});zT({target:"Array",proto:!0,forced:ZT},{includes:function(e){return KT(this,e,arguments.length>1?arguments[1]:void 0)}});XT("includes")});var Wt=b((bL,Fd)=>{"use strict";var eI=Pt();Fd.exports=eI});var Ud=b((gL,qd)=>{"use strict";Nd();var tI=Wt();qd.exports=tI("Array","includes")});var jd=b((vL,Hd)=>{"use strict";var rI=Ud();Hd.exports=rI});var bt=b((SL,Gd)=>{"use strict";var iI=jd();Gd.exports=iI});var ds=b(($L,Yd)=>{"use strict";var sI=Wn(),nI=Yn(),Wd=sI("keys");Yd.exports=function(a){return Wd[a]||(Wd[a]=nI(a))}});var Kd=b((LL,zd)=>{"use strict";var oI=Pe();zd.exports=!oI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ps=b((ML,Xd)=>{"use strict";var uI=nt(),lI=pe(),cI=Or(),dI=ds(),pI=Kd(),Jd=dI("IE_PROTO"),oo=Object,hI=oo.prototype;Xd.exports=pI?oo.getPrototypeOf:function(a){var e=cI(a);if(uI(e,Jd))return e[Jd];var t=e.constructor;return lI(t)&&e instanceof t?t.prototype:e instanceof oo?hI:null}});var hs=b((DL,Zd)=>{"use strict";Zd.exports={}});var rp=b((CL,tp)=>{"use strict";var mI=ve(),uo=nt(),fI=cr(),bI=no().indexOf,gI=hs(),ep=mI([].push);tp.exports=function(a,e){var t=fI(a),r=0,i=[],s;for(s in t)!uo(gI,s)&&uo(t,s)&&ep(i,s);for(;e.length>r;)uo(t,s=e[r++])&&(~bI(i,s)||ep(i,s));return i}});var lo=b((OL,ip)=>{"use strict";ip.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var co=b((VL,ap)=>{"use strict";var vI=rp(),SI=lo();ap.exports=Object.keys||function(e){return vI(e,SI)}});var po=b((BL,lp)=>{"use strict";var np=qe(),yI=Pe(),op=ve(),TI=ps(),II=co(),EI=cr(),xI=On().f,up=op(xI),PI=op([].push),wI=np&&yI(function(){var a=Object.create(null);return a[2]=2,!up(a,2)}),sp=function(a){return function(e){for(var t=EI(e),r=II(t),i=wI&&TI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!np||(i?u in t:up(t,u)))&&PI(o,a?[u,t[u]]:t[u]);return o}};lp.exports={entries:sp(!0),values:sp(!1)}});var cp=b(()=>{"use strict";var AI=me(),kI=po().entries;AI({target:"Object",stat:!0},{entries:function(e){return kI(e)}})});var pp=b((FL,dp)=>{"use strict";cp();var RI=Cr();dp.exports=RI.Object.entries});var mp=b((qL,hp)=>{"use strict";var $I=pp();hp.exports=$I});var Ur=b((UL,fp)=>{"use strict";var LI=mp();fp.exports=LI});var hr=b((HL,bp)=>{"use strict";bp.exports={}});var Sp=b((jL,vp)=>{"use strict";var MI=he(),DI=pe(),gp=MI.WeakMap;vp.exports=DI(gp)&&/native code/.test(String(gp))});var bo=b((GL,Ip)=>{"use strict";var CI=Sp(),Tp=he(),OI=He(),VI=_r(),ho=nt(),mo=xi(),BI=ds(),_I=hs(),yp="Object already initialized",fo=Tp.TypeError,NI=Tp.WeakMap,ms,Ri,fs,FI=function(a){return fs(a)?Ri(a):ms(a,{})},qI=function(a){return function(e){var t;if(!OI(e)||(t=Ri(e)).type!==a)throw new fo("Incompatible receiver, "+a+" required");return t}};CI||mo.state?(ot=mo.state||(mo.state=new NI),ot.get=ot.get,ot.has=ot.has,ot.set=ot.set,ms=function(a,e){if(ot.has(a))throw new fo(yp);return e.facade=a,ot.set(a,e),e},Ri=function(a){return ot.get(a)||{}},fs=function(a){return ot.has(a)}):(mr=BI("state"),_I[mr]=!0,ms=function(a,e){if(ho(a,mr))throw new fo(yp);return e.facade=a,VI(a,mr,e),e},Ri=function(a){return ho(a,mr)?a[mr]:{}},fs=function(a){return ho(a,mr)});var ot,mr;Ip.exports={set:ms,get:Ri,has:fs,enforce:FI,getterFor:qI}});var So=b((QL,xp)=>{"use strict";var go=qe(),UI=nt(),Ep=Function.prototype,HI=go&&Object.getOwnPropertyDescriptor,vo=UI(Ep,"name"),jI=vo&&function(){}.name==="something",GI=vo&&(!go||go&&HI(Ep,"name").configurable);xp.exports={EXISTS:vo,PROPER:jI,CONFIGURABLE:GI}});var wp=b(Pp=>{"use strict";var QI=qe(),WI=eo(),YI=pr(),zI=ft(),KI=cr(),JI=co();Pp.f=QI&&!WI?Object.defineProperties:function(e,t){zI(e);for(var r=KI(t),i=JI(t),s=i.length,n=0,o;s>n;)YI.f(e,o=i[n++],r[o]);return e}});var yo=b((YL,Ap)=>{"use strict";var XI=Pt();Ap.exports=XI("document","documentElement")});var xo=b((zL,Cp)=>{"use strict";var ZI=ft(),eE=wp(),kp=lo(),tE=hs(),rE=yo(),iE=us(),aE=ds(),Rp=">",$p="<",Io="prototype",Eo="script",Mp=aE("IE_PROTO"),To=function(){},Dp=function(a){return $p+Eo+Rp+a+$p+"/"+Eo+Rp},Lp=function(a){a.write(Dp("")),a.close();var e=a.parentWindow.Object;return a=null,e},sE=function(){var a=iE("iframe"),e="java"+Eo+":",t;return a.style.display="none",rE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Dp("document.F=Object")),t.close(),t.F},bs,gs=function(){try{bs=new ActiveXObject("htmlfile")}catch(e){}gs=typeof document!="undefined"?document.domain&&bs?Lp(bs):sE():Lp(bs);for(var a=kp.length;a--;)delete gs[Io][kp[a]];return gs()};tE[Mp]=!0;Cp.exports=Object.create||function(e,t){var r;return e!==null?(To[Io]=ZI(e),r=new To,To[Io]=null,r[Mp]=e):r=gs(),t===void 0?r:eE.f(r,t)}});var Hr=b((KL,Op)=>{"use strict";var nE=_r();Op.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:nE(a,e,t),a}});var ko=b((JL,_p)=>{"use strict";var oE=Pe(),uE=pe(),lE=He(),cE=xo(),Vp=ps(),dE=Hr(),pE=we(),hE=st(),Ao=pE("iterator"),Bp=!1,wt,Po,wo;[].keys&&(wo=[].keys(),"next"in wo?(Po=Vp(Vp(wo)),Po!==Object.prototype&&(wt=Po)):Bp=!0);var mE=!lE(wt)||oE(function(){var a={};return wt[Ao].call(a)!==a});mE?wt={}:hE&&(wt=cE(wt));uE(wt[Ao])||dE(wt,Ao,function(){return this});_p.exports={IteratorPrototype:wt,BUGGY_SAFARI_ITERATORS:Bp}});var vs=b((XL,Fp)=>{"use strict";var fE=we(),bE=fE("toStringTag"),Np={};Np[bE]="z";Fp.exports=String(Np)==="[object z]"});var $i=b((ZL,qp)=>{"use strict";var gE=vs(),vE=pe(),Ss=lr(),SE=we(),yE=SE("toStringTag"),TE=Object,IE=Ss(function(){return arguments}())==="Arguments",EE=function(a,e){try{return a[e]}catch(t){}};qp.exports=gE?Ss:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=EE(e=TE(a),yE))=="string"?t:IE?Ss(e):(r=Ss(e))==="Object"&&vE(e.callee)?"Arguments":r}});var Hp=b((eM,Up)=>{"use strict";var xE=vs(),PE=$i();Up.exports=xE?{}.toString:function(){return"[object "+PE(this)+"]"}});var Li=b((tM,Gp)=>{"use strict";var wE=vs(),AE=pr().f,kE=_r(),RE=nt(),$E=Hp(),LE=we(),jp=LE("toStringTag");Gp.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(RE(i,jp)||AE(i,jp,{configurable:!0,value:e}),r&&!wE&&kE(i,"toString",$E))}});var Wp=b((rM,Qp)=>{"use strict";var ME=ko().IteratorPrototype,DE=xo(),CE=yi(),OE=Li(),VE=hr(),BE=function(){return this};Qp.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=DE(ME,{next:CE(+!r,t)}),OE(a,i,!1,!0),VE[i]=BE,a}});var zp=b((iM,Yp)=>{"use strict";var _E=ve(),NE=mt();Yp.exports=function(a,e,t){try{return _E(NE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Jp=b((aM,Kp)=>{"use strict";var FE=He();Kp.exports=function(a){return FE(a)||a===null}});var Zp=b((sM,Xp)=>{"use strict";var qE=Jp(),UE=String,HE=TypeError;Xp.exports=function(a){if(qE(a))return a;throw new HE("Can't set "+UE(a)+" as a prototype")}});var Ro=b((nM,eh)=>{"use strict";var jE=zp(),GE=He(),QE=Qt(),WE=Zp();eh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=jE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return QE(i),WE(s),GE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var dh=b((oM,ch)=>{"use strict";var YE=me(),zE=Ue(),ys=st(),uh=So(),KE=pe(),JE=Wp(),th=ps(),rh=Ro(),XE=Li(),ZE=_r(),$o=Hr(),ex=we(),ih=hr(),lh=ko(),tx=uh.PROPER,rx=uh.CONFIGURABLE,ah=lh.IteratorPrototype,Ts=lh.BUGGY_SAFARI_ITERATORS,Mi=ex("iterator"),sh="keys",Di="values",nh="entries",oh=function(){return this};ch.exports=function(a,e,t,r,i,s,n){JE(t,e,r);var o=function(I){if(I===i&&h)return h;if(!Ts&&I&&I in c)return c[I];switch(I){case sh:return function(){return new t(this,I)};case Di:return function(){return new t(this,I)};case nh:return function(){return new t(this,I)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Mi]||c["@@iterator"]||i&&c[i],h=!Ts&&d||o(i),p=e==="Array"&&c.entries||d,f,g,v;if(p&&(f=th(p.call(new a)),f!==Object.prototype&&f.next&&(!ys&&th(f)!==ah&&(rh?rh(f,ah):KE(f[Mi])||$o(f,Mi,oh)),XE(f,u,!0,!0),ys&&(ih[u]=oh))),tx&&i===Di&&d&&d.name!==Di&&(!ys&&rx?ZE(c,"name",Di):(l=!0,h=function(){return zE(d,this)})),i)if(g={values:o(Di),keys:s?h:o(sh),entries:o(nh)},n)for(v in g)(Ts||l||!(v in c))&&$o(c,v,g[v]);else YE({target:e,proto:!0,forced:Ts||l},g);return(!ys||n)&&c[Mi]!==h&&$o(c,Mi,h,{name:i}),ih[e]=h,g}});var hh=b((uM,ph)=>{"use strict";ph.exports=function(a,e){return{value:a,done:e}}});var Mo=b((lM,vh)=>{"use strict";var ix=cr(),Lo=ki(),mh=hr(),bh=bo(),ax=pr().f,sx=dh(),Is=hh(),nx=st(),ox=qe(),gh="Array Iterator",ux=bh.set,lx=bh.getterFor(gh);vh.exports=sx(Array,"Array",function(a,e){ux(this,{type:gh,target:ix(a),index:0,kind:e})},function(){var a=lx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Is(void 0,!0);switch(a.kind){case"keys":return Is(t,!1);case"values":return Is(e[t],!1)}return Is([t,e[t]],!1)},"values");var fh=mh.Arguments=mh.Array;Lo("keys");Lo("values");Lo("entries");if(!nx&&ox&&fh.name!=="values")try{ax(fh,"name",{value:"values"})}catch(a){}});var yh=b((cM,Sh)=>{"use strict";var cx=we(),dx=hr(),px=cx("iterator"),hx=Array.prototype;Sh.exports=function(a){return a!==void 0&&(dx.Array===a||hx[px]===a)}});var Do=b((dM,Ih)=>{"use strict";var mx=$i(),Th=Ei(),fx=Dr(),bx=hr(),gx=we(),vx=gx("iterator");Ih.exports=function(a){if(!fx(a))return Th(a,vx)||Th(a,"@@iterator")||bx[mx(a)]}});var xh=b((pM,Eh)=>{"use strict";var Sx=Ue(),yx=mt(),Tx=ft(),Ix=Ii(),Ex=Do(),xx=TypeError;Eh.exports=function(a,e){var t=arguments.length<2?Ex(a):e;if(yx(t))return Tx(Sx(t,a));throw new xx(Ix(a)+" is not iterable")}});var Ah=b((hM,wh)=>{"use strict";var Px=Ue(),Ph=ft(),wx=Ei();wh.exports=function(a,e,t){var r,i;Ph(a);try{if(r=wx(a,"return"),!r){if(e==="throw")throw t;return t}r=Px(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Ph(r),t}});var xs=b((mM,Lh)=>{"use strict";var Ax=Br(),kx=Ue(),Rx=ft(),$x=Ii(),Lx=yh(),Mx=qr(),kh=Ti(),Dx=xh(),Cx=Do(),Rh=Ah(),Ox=TypeError,Es=function(a,e){this.stopped=a,this.result=e},$h=Es.prototype;Lh.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=Ax(e,r),l,c,d,h,p,f,g,v=function(T){return l&&Rh(l,"normal",T),new Es(!0,T)},I=function(T){return i?(Rx(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(c=Cx(a),!c)throw new Ox($x(a)+" is not iterable");if(Lx(c)){for(d=0,h=Mx(a);h>d;d++)if(p=I(a[d]),p&&kh($h,p))return p;return new Es(!1)}l=Dx(a,c)}for(f=s?a.next:l.next;!(g=kx(f,l)).done;){try{p=I(g.value)}catch(T){Rh(l,"throw",T)}if(typeof p=="object"&&p&&kh($h,p))return p}return new Es(!1)}});var Dh=b((fM,Mh)=>{"use strict";var Vx=qe(),Bx=pr(),_x=yi();Mh.exports=function(a,e,t){Vx?Bx.f(a,e,_x(0,t)):a[e]=t}});var Ch=b(()=>{"use strict";var Nx=me(),Fx=xs(),qx=Dh();Nx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Fx(e,function(r,i){qx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Vh=b((vM,Oh)=>{"use strict";Mo();Ch();var Ux=Cr();Oh.exports=Ux.Object.fromEntries});var _h=b((SM,Bh)=>{"use strict";Bh.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Fh=b(()=>{"use strict";Mo();var Hx=_h(),jx=he(),Gx=Li(),Nh=hr();for(Ps in Hx)Gx(jx[Ps],Ps),Nh[Ps]=Nh.Array;var Ps});var Uh=b((IM,qh)=>{"use strict";var Qx=Vh();Fh();qh.exports=Qx});var Co=b((EM,Hh)=>{"use strict";var Wx=Uh();Hh.exports=Wx});var jh=b(()=>{"use strict"});var Oo=b((wM,Gh)=>{"use strict";var Ci=he(),Yx=dr(),zx=lr(),ws=function(a){return Yx.slice(0,a.length)===a};Gh.exports=function(){return ws("Bun/")?"BUN":ws("Cloudflare-Workers")?"CLOUDFLARE":ws("Deno/")?"DENO":ws("Node.js/")?"NODE":Ci.Bun&&typeof Bun.version=="string"?"BUN":Ci.Deno&&typeof Deno.version=="object"?"DENO":zx(Ci.process)==="process"?"NODE":Ci.window&&Ci.document?"BROWSER":"REST"}()});var As=b((AM,Qh)=>{"use strict";var Kx=Oo();Qh.exports=Kx==="NODE"});var Yh=b((kM,Wh)=>{"use strict";var Jx=pr();Wh.exports=function(a,e,t){return Jx.f(a,e,t)}});var Jh=b((RM,Kh)=>{"use strict";var Xx=Pt(),Zx=Yh(),eP=we(),tP=qe(),zh=eP("species");Kh.exports=function(a){var e=Xx(a);tP&&e&&!e[zh]&&Zx(e,zh,{configurable:!0,get:function(){return this}})}});var Zh=b(($M,Xh)=>{"use strict";var rP=Ti(),iP=TypeError;Xh.exports=function(a,e){if(rP(e,a))return a;throw new iP("Incorrect invocation")}});var Bo=b((LM,em)=>{"use strict";var aP=ve(),sP=pe(),Vo=xi(),nP=aP(Function.toString);sP(Vo.inspectSource)||(Vo.inspectSource=function(a){return nP(a)});em.exports=Vo.inspectSource});var No=b((MM,sm)=>{"use strict";var oP=ve(),uP=Pe(),tm=pe(),lP=$i(),cP=Pt(),dP=Bo(),rm=function(){},im=cP("Reflect","construct"),_o=/^\s*(?:class|function)\b/,pP=oP(_o.exec),hP=!_o.test(rm),Oi=function(e){if(!tm(e))return!1;try{return im(rm,[],e),!0}catch(t){return!1}},am=function(e){if(!tm(e))return!1;switch(lP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return hP||!!pP(_o,dP(e))}catch(t){return!0}};am.sham=!0;sm.exports=!im||uP(function(){var a;return Oi(Oi.call)||!Oi(Object)||!Oi(function(){a=!0})||a})?am:Oi});var om=b((DM,nm)=>{"use strict";var mP=No(),fP=Ii(),bP=TypeError;nm.exports=function(a){if(mP(a))return a;throw new bP(fP(a)+" is not a constructor")}});var Fo=b((CM,lm)=>{"use strict";var um=ft(),gP=om(),vP=Dr(),SP=we(),yP=SP("species");lm.exports=function(a,e){var t=um(a).constructor,r;return t===void 0||vP(r=um(t)[yP])?e:gP(r)}});var dm=b((OM,cm)=>{"use strict";var TP=ve();cm.exports=TP([].slice)});var hm=b((VM,pm)=>{"use strict";var IP=TypeError;pm.exports=function(a,e){if(a<e)throw new IP("Not enough arguments");return a}});var qo=b((BM,mm)=>{"use strict";var EP=dr();mm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(EP)});var Ko=b((_M,Em)=>{"use strict";var je=he(),xP=Ln(),PP=Br(),fm=pe(),wP=nt(),Im=Pe(),bm=yo(),AP=dm(),gm=us(),kP=hm(),RP=qo(),$P=As(),Wo=je.setImmediate,Yo=je.clearImmediate,LP=je.process,Uo=je.Dispatch,MP=je.Function,vm=je.MessageChannel,DP=je.String,Ho=0,Vi={},Sm="onreadystatechange",Bi,fr,jo,Go;Im(function(){Bi=je.location});var zo=function(a){if(wP(Vi,a)){var e=Vi[a];delete Vi[a],e()}},Qo=function(a){return function(){zo(a)}},ym=function(a){zo(a.data)},Tm=function(a){je.postMessage(DP(a),Bi.protocol+"//"+Bi.host)};(!Wo||!Yo)&&(Wo=function(e){kP(arguments.length,1);var t=fm(e)?e:MP(e),r=AP(arguments,1);return Vi[++Ho]=function(){xP(t,void 0,r)},fr(Ho),Ho},Yo=function(e){delete Vi[e]},$P?fr=function(a){LP.nextTick(Qo(a))}:Uo&&Uo.now?fr=function(a){Uo.now(Qo(a))}:vm&&!RP?(jo=new vm,Go=jo.port2,jo.port1.onmessage=ym,fr=PP(Go.postMessage,Go)):je.addEventListener&&fm(je.postMessage)&&!je.importScripts&&Bi&&Bi.protocol!=="file:"&&!Im(Tm)?(fr=Tm,je.addEventListener("message",ym,!1)):Sm in gm("script")?fr=function(a){bm.appendChild(gm("script"))[Sm]=function(){bm.removeChild(this),zo(a)}}:fr=function(a){setTimeout(Qo(a),0)});Em.exports={set:Wo,clear:Yo}});var wm=b((NM,Pm)=>{"use strict";var xm=he(),CP=qe(),OP=Object.getOwnPropertyDescriptor;Pm.exports=function(a){if(!CP)return xm[a];var e=OP(xm,a);return e&&e.value}});var Jo=b((FM,km)=>{"use strict";var Am=function(){this.head=null,this.tail=null};Am.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}}};km.exports=Am});var $m=b((qM,Rm)=>{"use strict";var VP=dr();Rm.exports=/ipad|iphone|ipod/i.test(VP)&&typeof Pebble!="undefined"});var Mm=b((UM,Lm)=>{"use strict";var BP=dr();Lm.exports=/web0s(?!.*chrome)/i.test(BP)});var Nm=b((HM,_m)=>{"use strict";var Gr=he(),_P=wm(),Dm=Br(),Xo=Ko().set,NP=Jo(),FP=qo(),qP=$m(),UP=Mm(),Zo=As(),Cm=Gr.MutationObserver||Gr.WebKitMutationObserver,Om=Gr.document,Vm=Gr.process,ks=Gr.Promise,ru=_P("queueMicrotask"),jr,eu,tu,Rs,Bm;ru||(_i=new NP,Ni=function(){var a,e;for(Zo&&(a=Vm.domain)&&a.exit();e=_i.get();)try{e()}catch(t){throw _i.head&&jr(),t}a&&a.enter()},!FP&&!Zo&&!UP&&Cm&&Om?(eu=!0,tu=Om.createTextNode(""),new Cm(Ni).observe(tu,{characterData:!0}),jr=function(){tu.data=eu=!eu}):!qP&&ks&&ks.resolve?(Rs=ks.resolve(void 0),Rs.constructor=ks,Bm=Dm(Rs.then,Rs),jr=function(){Bm(Ni)}):Zo?jr=function(){Vm.nextTick(Ni)}:(Xo=Dm(Xo,Gr),jr=function(){Xo(Ni)}),ru=function(a){_i.head||jr(),_i.add(a)});var _i,Ni;_m.exports=ru});var qm=b((jM,Fm)=>{"use strict";Fm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var $s=b((GM,Um)=>{"use strict";Um.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var br=b((QM,Hm)=>{"use strict";var HP=he();Hm.exports=HP.Promise});var Qr=b((WM,Wm)=>{"use strict";var jP=he(),Fi=br(),GP=pe(),QP=Zn(),WP=Bo(),YP=we(),jm=Oo(),zP=st(),iu=Fn(),Gm=Fi&&Fi.prototype,KP=YP("species"),au=!1,Qm=GP(jP.PromiseRejectionEvent),JP=QP("Promise",function(){var a=WP(Fi),e=a!==String(Fi);if(!e&&iu===66||zP&&!(Gm.catch&&Gm.finally))return!0;if(!iu||iu<51||!/native code/.test(a)){var t=new Fi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[KP]=r,au=t.then(function(){})instanceof r,!au)return!0}return!e&&(jm==="BROWSER"||jm==="DENO")&&!Qm});Wm.exports={CONSTRUCTOR:JP,REJECTION_EVENT:Qm,SUBCLASSING:au}});var Wr=b((YM,zm)=>{"use strict";var Ym=mt(),XP=TypeError,ZP=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new XP("Bad Promise constructor");e=r,t=i}),this.resolve=Ym(e),this.reject=Ym(t)};zm.exports.f=function(a){return new ZP(a)}});var ff=b(()=>{"use strict";var ew=me(),tw=st(),Cs=As(),Yt=he(),Jr=Ue(),Km=Hr(),Jm=Ro(),rw=Li(),iw=Jh(),aw=mt(),Ds=pe(),sw=He(),nw=Zh(),ow=Fo(),rf=Ko().set,lu=Nm(),uw=qm(),lw=$s(),cw=Jo(),af=bo(),Os=br(),cu=Qr(),sf=Wr(),Vs="Promise",nf=cu.CONSTRUCTOR,dw=cu.REJECTION_EVENT,pw=cu.SUBCLASSING,su=af.getterFor(Vs),hw=af.set,Yr=Os&&Os.prototype,gr=Os,Ls=Yr,of=Yt.TypeError,nu=Yt.document,du=Yt.process,ou=sf.f,mw=ou,fw=!!(nu&&nu.createEvent&&Yt.dispatchEvent),uf="unhandledrejection",bw="rejectionhandled",Xm=0,lf=1,gw=2,pu=1,cf=2,Ms,Zm,vw,ef,df=function(a){var e;return sw(a)&&Ds(e=a.then)?e:!1},pf=function(a,e){var t=e.value,r=e.state===lf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===cf&&yw(e),e.rejection=pu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new of("Promise-chain cycle")):(l=df(u))?Jr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},hf=function(a,e){a.notified||(a.notified=!0,lu(function(){for(var t=a.reactions,r;r=t.get();)pf(r,a);a.notified=!1,e&&!a.rejection&&Sw(a)}))},mf=function(a,e,t){var r,i;fw?(r=nu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Yt.dispatchEvent(r)):r={promise:e,reason:t},!dw&&(i=Yt["on"+a])?i(r):a===uf&&uw("Unhandled promise rejection",t)},Sw=function(a){Jr(rf,Yt,function(){var e=a.facade,t=a.value,r=tf(a),i;if(r&&(i=lw(function(){Cs?du.emit("unhandledRejection",t,e):mf(uf,e,t)}),a.rejection=Cs||tf(a)?cf:pu,i.error))throw i.value})},tf=function(a){return a.rejection!==pu&&!a.parent},yw=function(a){Jr(rf,Yt,function(){var e=a.facade;Cs?du.emit("rejectionHandled",e):mf(bw,e,a.value)})},zr=function(a,e,t){return function(r){a(e,r,t)}},Kr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=gw,hf(a,!0))},uu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new of("Promise can't be resolved itself");var r=df(e);r?lu(function(){var i={done:!1};try{Jr(r,e,zr(uu,i,a),zr(Kr,i,a))}catch(s){Kr(i,s,a)}}):(a.value=e,a.state=lf,hf(a,!1))}catch(i){Kr({done:!1},i,a)}}};if(nf&&(gr=function(e){nw(this,Ls),aw(e),Jr(Ms,this);var t=su(this);try{e(zr(uu,t),zr(Kr,t))}catch(r){Kr(t,r)}},Ls=gr.prototype,Ms=function(e){hw(this,{type:Vs,done:!1,notified:!1,parent:!1,reactions:new cw,rejection:!1,state:Xm,value:void 0})},Ms.prototype=Km(Ls,"then",function(e,t){var r=su(this),i=ou(ow(this,gr));return r.parent=!0,i.ok=Ds(e)?e:!0,i.fail=Ds(t)&&t,i.domain=Cs?du.domain:void 0,r.state===Xm?r.reactions.add(i):lu(function(){pf(i,r)}),i.promise}),Zm=function(){var a=new Ms,e=su(a);this.promise=a,this.resolve=zr(uu,e),this.reject=zr(Kr,e)},sf.f=ou=function(a){return a===gr||a===vw?new Zm(a):mw(a)},!tw&&Ds(Os)&&Yr!==Object.prototype)){ef=Yr.then,pw||Km(Yr,"then",function(e,t){var r=this;return new gr(function(i,s){Jr(ef,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Yr.constructor}catch(a){}Jm&&Jm(Yr,Ls)}ew({global:!0,constructor:!0,wrap:!0,forced:nf},{Promise:gr});rw(gr,Vs,!1,!0);iw(Vs)});var yf=b((JM,Sf)=>{"use strict";var Tw=we(),gf=Tw("iterator"),vf=!1;try{bf=0,hu={next:function(){return{done:!!bf++}},return:function(){vf=!0}},hu[gf]=function(){return this},Array.from(hu,function(){throw 2})}catch(a){}var bf,hu;Sf.exports=function(a,e){try{if(!e&&!vf)return!1}catch(i){return!1}var t=!1;try{var r={};r[gf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var mu=b((XM,Tf)=>{"use strict";var Iw=br(),Ew=yf(),xw=Qr().CONSTRUCTOR;Tf.exports=xw||!Ew(function(a){Iw.all(a).then(void 0,function(){})})});var If=b(()=>{"use strict";var Pw=me(),ww=Ue(),Aw=mt(),kw=Wr(),Rw=$s(),$w=xs(),Lw=mu();Pw({target:"Promise",stat:!0,forced:Lw},{all:function(e){var t=this,r=kw.f(t),i=r.resolve,s=r.reject,n=Rw(function(){var o=Aw(t.resolve),u=[],l=0,c=1;$w(e,function(d){var h=l++,p=!1;c++,ww(o,t,d).then(function(f){p||(p=!0,u[h]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var xf=b(()=>{"use strict";var Mw=me(),Dw=st(),Cw=Qr().CONSTRUCTOR,bu=br(),Ow=Pt(),Vw=pe(),Bw=Hr(),Ef=bu&&bu.prototype;Mw({target:"Promise",proto:!0,forced:Cw,real:!0},{catch:function(a){return this.then(void 0,a)}});!Dw&&Vw(bu)&&(fu=Ow("Promise").prototype.catch,Ef.catch!==fu&&Bw(Ef,"catch",fu,{unsafe:!0}));var fu});var Pf=b(()=>{"use strict";var _w=me(),Nw=Ue(),Fw=mt(),qw=Wr(),Uw=$s(),Hw=xs(),jw=mu();_w({target:"Promise",stat:!0,forced:jw},{race:function(e){var t=this,r=qw.f(t),i=r.reject,s=Uw(function(){var n=Fw(t.resolve);Hw(e,function(o){Nw(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var wf=b(()=>{"use strict";var Gw=me(),Qw=Wr(),Ww=Qr().CONSTRUCTOR;Gw({target:"Promise",stat:!0,forced:Ww},{reject:function(e){var t=Qw.f(this),r=t.reject;return r(e),t.promise}})});var gu=b((oD,Af)=>{"use strict";var Yw=ft(),zw=He(),Kw=Wr();Af.exports=function(a,e){if(Yw(a),zw(e)&&e.constructor===a)return e;var t=Kw.f(a),r=t.resolve;return r(e),t.promise}});var $f=b(()=>{"use strict";var Jw=me(),Xw=Pt(),kf=st(),Zw=br(),Rf=Qr().CONSTRUCTOR,eA=gu(),tA=Xw("Promise"),rA=kf&&!Rf;Jw({target:"Promise",stat:!0,forced:kf||Rf},{resolve:function(e){return eA(rA&&this===tA?Zw:this,e)}})});var Lf=b(()=>{"use strict";ff();If();xf();Pf();wf();$f()});var Of=b(()=>{"use strict";var iA=me(),aA=st(),Bs=br(),sA=Pe(),Df=Pt(),Cf=pe(),nA=Fo(),Mf=gu(),oA=Hr(),Su=Bs&&Bs.prototype,uA=!!Bs&&sA(function(){Su.finally.call({then:function(){}},function(){})});iA({target:"Promise",proto:!0,real:!0,forced:uA},{finally:function(a){var e=nA(this,Df("Promise")),t=Cf(a);return this.then(t?function(r){return Mf(e,a()).then(function(){return r})}:a,t?function(r){return Mf(e,a()).then(function(){throw r})}:a)}});!aA&&Cf(Bs)&&(vu=Df("Promise").prototype.finally,Su.finally!==vu&&oA(Su,"finally",vu,{unsafe:!0}));var vu});var Bf=b((mD,Vf)=>{"use strict";jh();Lf();Of();var lA=Wt();Vf.exports=lA("Promise","finally")});var Nf=b((fD,_f)=>{"use strict";var cA=Bf();_f.exports=cA});var _s=b((bD,Ff)=>{"use strict";var dA=Nf();Ff.exports=dA});var Wf=b(()=>{"use strict";var bA=me(),gA=po().values;bA({target:"Object",stat:!0},{values:function(e){return gA(e)}})});var zf=b((WD,Yf)=>{"use strict";Wf();var vA=Cr();Yf.exports=vA.Object.values});var Jf=b((YD,Kf)=>{"use strict";var SA=zf();Kf.exports=SA});var Ui=b((zD,Xf)=>{"use strict";var yA=Jf();Xf.exports=yA});var rb=b(()=>{"use strict";var xA=me(),PA=Or(),wA=qr(),AA=Ai(),kA=ki();xA({target:"Array",proto:!0},{at:function(e){var t=PA(this),r=wA(t),i=AA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});kA("at")});var ab=b((SC,ib)=>{"use strict";rb();var RA=Wt();ib.exports=RA("Array","at")});var nb=b((yC,sb)=>{"use strict";var $A=ab();sb.exports=$A});var Xr=b((TC,ob)=>{"use strict";var LA=nb();ob.exports=LA});var Vu=b((U0,Ab)=>{"use strict";var UA=lr();Ab.exports=Array.isArray||function(e){return UA(e)==="Array"}});var Rb=b((H0,kb)=>{"use strict";var HA=TypeError,jA=9007199254740991;kb.exports=function(a){if(a>jA)throw HA("Maximum allowed index exceeded");return a}});var Mb=b((j0,Lb)=>{"use strict";var GA=Vu(),QA=qr(),WA=Rb(),YA=Br(),$b=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?YA(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&GA(d)?(h=QA(d),u=$b(a,e,d,h,u,s-1)-1):(WA(u+1),a[u]=d),u++),l++;return u};Lb.exports=$b});var Vb=b((G0,Ob)=>{"use strict";var Db=Vu(),zA=No(),KA=He(),JA=we(),XA=JA("species"),Cb=Array;Ob.exports=function(a){var e;return Db(a)&&(e=a.constructor,zA(e)&&(e===Cb||Db(e.prototype))?e=void 0:KA(e)&&(e=e[XA],e===null&&(e=void 0))),e===void 0?Cb:e}});var _b=b((Q0,Bb)=>{"use strict";var ZA=Vb();Bb.exports=function(a,e){return new(ZA(a))(e===0?0:e)}});var Nb=b(()=>{"use strict";var ek=me(),tk=Mb(),rk=mt(),ik=Or(),ak=qr(),sk=_b();ek({target:"Array",proto:!0},{flatMap:function(e){var t=ik(this),r=ak(t),i;return rk(e),i=sk(t,0),i.length=tk(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Fb=b(()=>{"use strict";var nk=ki();nk("flatMap")});var Ub=b((J0,qb)=>{"use strict";Nb();Fb();var ok=Wt();qb.exports=ok("Array","flatMap")});var jb=b((X0,Hb)=>{"use strict";var uk=Ub();Hb.exports=uk});var Bu=b((Z0,Gb)=>{"use strict";var lk=jb();Gb.exports=lk});var Zi=b((lO,dg)=>{"use strict";var gk=$i(),vk=String;dg.exports=function(a){if(gk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return vk(a)}});var Nu=b((cO,pg)=>{"use strict";pg.exports=`
7
+ \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var fg=b((dO,mg)=>{"use strict";var Sk=ve(),yk=Qt(),Tk=Zi(),qu=Nu(),hg=Sk("".replace),Ik=RegExp("^["+qu+"]+"),Ek=RegExp("(^|[^"+qu+"])["+qu+"]+$"),Fu=function(a){return function(e){var t=Tk(yk(e));return a&1&&(t=hg(t,Ik,"")),a&2&&(t=hg(t,Ek,"$1")),t}};mg.exports={start:Fu(1),end:Fu(2),trim:Fu(3)}});var Sg=b((pO,vg)=>{"use strict";var xk=So().PROPER,Pk=Pe(),bg=Nu(),gg="\u200B\x85\u180E";vg.exports=function(a){return Pk(function(){return!!bg[a]()||gg[a]()!==gg||xk&&bg[a].name!==a})}});var Uu=b((hO,yg)=>{"use strict";var wk=fg().start,Ak=Sg();yg.exports=Ak("trimStart")?function(){return wk(this)}:"".trimStart});var Ig=b(()=>{"use strict";var kk=me(),Tg=Uu();kk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Tg},{trimLeft:Tg})});var xg=b(()=>{"use strict";Ig();var Rk=me(),Eg=Uu();Rk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Eg},{trimStart:Eg})});var wg=b((vO,Pg)=>{"use strict";xg();var $k=Wt();Pg.exports=$k("String","trimLeft")});var kg=b((SO,Ag)=>{"use strict";var Lk=wg();Ag.exports=Lk});var $g=b((yO,Rg)=>{"use strict";var Mk=kg();Rg.exports=Mk});var jg=b(()=>{"use strict"});var Gg=b(()=>{"use strict"});var Wg=b((HB,Qg)=>{"use strict";var Xk=He(),Zk=lr(),eR=we(),tR=eR("match");Qg.exports=function(a){var e;return Xk(a)&&((e=a[tR])!==void 0?!!e:Zk(a)==="RegExp")}});var zg=b((jB,Yg)=>{"use strict";var rR=ft();Yg.exports=function(){var a=rR(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Xg=b((GB,Jg)=>{"use strict";var iR=Ue(),aR=nt(),sR=Ti(),nR=zg(),Kg=RegExp.prototype;Jg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Kg)&&!aR(a,"flags")&&sR(Kg,a)?iR(nR,a):e}});var ev=b((QB,Zg)=>{"use strict";var zu=ve(),oR=Or(),uR=Math.floor,Wu=zu("".charAt),lR=zu("".replace),Yu=zu("".slice),cR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,dR=/\$([$&'`]|\d{1,2})/g;Zg.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=dR;return i!==void 0&&(i=oR(i),u=cR),lR(s,u,function(l,c){var d;switch(Wu(c,0)){case"$":return"$";case"&":return a;case"`":return Yu(e,0,t);case"'":return Yu(e,n);case"<":d=i[Yu(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=uR(h/10);return p===0?l:p<=o?r[p-1]===void 0?Wu(c,1):r[p-1]+Wu(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var iv=b(()=>{"use strict";var pR=me(),hR=Ue(),Ju=ve(),tv=Qt(),mR=pe(),fR=Dr(),bR=Wg(),si=Zi(),gR=Ei(),vR=Xg(),SR=ev(),yR=we(),TR=st(),IR=yR("replace"),ER=TypeError,Ku=Ju("".indexOf),xR=Ju("".replace),rv=Ju("".slice),PR=Math.max;pR({target:"String",proto:!0},{replaceAll:function(e,t){var r=tv(this),i,s,n,o,u,l,c,d,h,p,f=0,g="";if(!fR(e)){if(i=bR(e),i&&(s=si(tv(vR(e))),!~Ku(s,"g")))throw new ER("`.replaceAll` does not allow non-global regexes");if(n=gR(e,IR),n)return hR(n,e,r,t);if(TR&&i)return xR(si(r),e,t)}for(o=si(r),u=si(e),l=mR(t),l||(t=si(t)),c=u.length,d=PR(1,c),h=Ku(o,u);h!==-1;)p=l?si(t(u,h,o)):SR(u,o,h,[],void 0,t),g+=rv(o,f,h)+p,f=h+c,h=h+d>o.length?-1:Ku(o,u,h+d);return f<o.length&&(g+=rv(o,f)),g}})});var sv=b((zB,av)=>{"use strict";jg();Gg();iv();var wR=Wt();av.exports=wR("String","replaceAll")});var ov=b((KB,nv)=>{"use strict";var AR=sv();nv.exports=AR});var lv=b((JB,uv)=>{"use strict";var kR=ov();uv.exports=kR});var dv=b((XB,cv)=>{"use strict";var RR=Ai(),$R=Zi(),LR=Qt(),MR=RangeError;cv.exports=function(e){var t=$R(LR(this)),r="",i=RR(e);if(i<0||i===1/0)throw new MR("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var bv=b((ZB,fv)=>{"use strict";var mv=ve(),DR=so(),pv=Zi(),CR=dv(),OR=Qt(),VR=mv(CR),BR=mv("".slice),_R=Math.ceil,hv=function(a){return function(e,t,r){var i=pv(OR(e)),s=DR(t),n=i.length,o=r===void 0?" ":pv(r),u,l;return s<=n||o===""?i:(u=s-n,l=VR(o,_R(u/o.length)),l.length>u&&(l=BR(l,0,u)),a?i+l:l+i)}};fv.exports={start:hv(!1),end:hv(!0)}});var vv=b((e_,gv)=>{"use strict";var NR=dr();gv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(NR)});var Sv=b(()=>{"use strict";var FR=me(),qR=bv().start,UR=vv();FR({target:"String",proto:!0,forced:UR},{padStart:function(e){return qR(this,e,arguments.length>1?arguments[1]:void 0)}})});var Tv=b((i_,yv)=>{"use strict";Sv();var HR=Wt();yv.exports=HR("String","padStart")});var Ev=b((a_,Iv)=>{"use strict";var jR=Tv();Iv.exports=jR});var Pv=b((s_,xv)=>{"use strict";var GR=Ev();xv.exports=GR});var l$={};OS(l$,{ChromecastState:()=>gi,HttpConnectionType:()=>as,Observable:()=>It.Observable,PlaybackState:()=>$e,Player:()=>Ha,SDK_VERSION:()=>u$,Subject:()=>It.Subject,Subscription:()=>It.Subscription,Surface:()=>ss,VERSION:()=>Rn,ValueSubject:()=>It.ValueSubject,VideoFormat:()=>xt,VideoQuality:()=>It.VideoQuality});module.exports=VS(l$);var Rn="2.0.123-dev.ebdb6ff0.0";var $e=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))($e||{}),xt=(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))(xt||{});var gi=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(gi||{}),as=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(as||{});var ss=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ss||{});var bS=X(bt(),1);var q=require("@vkontakte/videoplayer-shared/es2015");var Qd=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var cs=class{constructor(e){this.connection$=new 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;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,q.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Qd("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.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,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)(aI),(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 c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,q.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,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})}}},aI=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 ml=X(bt(),1),iS=X(Ur(),1),aS=X(Co(),1);var jf=X(_s(),1);var yu=require("@vkontakte/videoplayer-shared/es2015");var Ae=(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,yu.assertNever)(t)}return a},Ns=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:(0,yu.assertNever)(e)}};var R=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var gt=require("@vkontakte/videoplayer-shared/es2015"),j=class{constructor(e){this.transitionStarted$=new gt.Subject;this.transitionEnded$=new gt.Subject;this.transitionUpdated$=new gt.Subject;this.forceChanged$=new gt.Subject;this.stateChangeStarted$=(0,gt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,gt.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,gt.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 qf=require("@vkontakte/videoplayer-shared/es2015"),Uf=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,qf.assertNever)(a)}};var M=require("@vkontakte/videoplayer-shared/es2015");var pA=5,hA=5,mA=500,Hf=7e3,qi=class{constructor(e){this.subscription=new M.Subscription;this.loadMediaTimeoutSubscription=new M.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,M.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,M.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,M.assertNever)(e)}break}default:(0,M.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(Uf(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 M.Subscription;this.subscription.add(e),this.subscription.add((0,M.merge)(this.videoState.stateChangeStarted$.pipe((0,M.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,M.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 M.Subject;e.add(i.pipe((0,M.debounce)(mA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,M.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)>pA)&&i.next(o),s=o})),e.add((0,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,M.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,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,M.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<hA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(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,M.assertNever)(n)}}),t((0,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,M.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,M.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,M.observableFrom)(["init"])).pipe((0,M.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"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(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"),R(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"),R(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"&&R(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];(0,M.assertNonNullable)(c);let d=(0,M.getHighestQuality)(Object.keys(c));(0,M.assertNonNullable)(d);let h=c[d];(0,M.assertNonNullable)(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,M.assertNonNullable)(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,M.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,M.assertNonNullable)(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,M.assertNonNullable)(c),r=Ae(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:M.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,M.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,M.isNonNullable)(o)&&(n.metadata.title=o),(0,M.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,M.timeout)(Hf).subscribe(()=>s(`timeout(${Hf})`)))});(0,jf.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:M.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Cu=X(bt(),1);var xu=require("@vkontakte/videoplayer-shared/es2015");var Gf=require("@vkontakte/videoplayer-shared/es2015"),Qf=a=>{try{a.pause(),a.playbackRate=0,(0,Gf.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Fs=require("@vkontakte/videoplayer-shared/es2015"),Tu=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)}},Iu=window.WeakMap?new WeakMap:new Tu,Eu=window.WeakMap?new WeakMap:new Map,fA=(a,e=20)=>{let t=0;return(0,Fs.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},De=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?(0,xu.clearVideoElement)(t):(t=document.createElement("video"),a.appendChild(t)),Iu.set(t,r);let i=new Fs.Subscription;return i.add(fA(t,e)),Eu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Ce=a=>{let e=Eu.get(a);e==null||e.unsubscribe(),Eu.delete(a);let t=Iu.get(a);Iu.delete(a),t?(0,xu.clearVideoElement)(a):Qf(a)};var Pu=X(Ui(),1),D=require("@vkontakte/videoplayer-shared/es2015");var zt=require("@vkontakte/videoplayer-shared/es2015"),qs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,zt.isNullable)(i),l=new zt.Subscription;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},vt=(a,e,t)=>qs(e,()=>a.loop,r=>{(0,zt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Oe=(a,e,t,r)=>qs(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,zt.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}),Ke=(a,e,t,r)=>qs(e,()=>a.playbackRate,i=>{(0,zt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Kt=qs;var TA=a=>["__",a.language,a.label].join("|"),IA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},wu=class a{constructor(){this.available$=new D.Subject;this.current$=new D.ValueSubject(void 0);this.error$=new D.Subject;this.subscription=new D.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:D.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(Kt(t.internalTextTracks,()=>(0,Pu.default)(this.internalTracks),s=>{(0,D.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,D.isNonNullable)(s)&&(0,D.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,D.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Kt(t.externalTextTracks,()=>(0,Pu.default)(this.externalTracks),s=>{(0,D.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,D.isNonNullable)(s)&&(0,D.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,D.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Kt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Kt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,D.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,D.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,D.merge)((0,D.fromEvent)(e,"addtrack"),(0,D.fromEvent)(e,"removetrack"),(0,D.observableFrom)(["init"])).pipe((0,D.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,D.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,D.merge)((0,D.fromEvent)(e,"change"),(0,D.observableFrom)(["init"])).pipe((0,D.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,D.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,D.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,D.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,D.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,D.isNonNullable)(t.align)&&(i.align=t.align),(0,D.isNonNullable)(t.position)&&(i.position=t.position),(0,D.isNonNullable)(t.size)&&(i.size=t.size),(0,D.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,D.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:TA(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,D.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,D.isNullable)(e)||!IA(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,D.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,D.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)}},Je=wu;var kt=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Zf=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Au=a=>{let e=Zf(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},eb=a=>{let e=Zf(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var O=require("@vkontakte/videoplayer-shared/es2015");var EA=3,tb=(a,e,t=EA)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Ve=a=>{let e=x=>(0,O.fromEvent)(a,x).pipe((0,O.mapTo)(void 0)),r=(0,O.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,O.fromEvent)(a,x))).pipe((0,O.map)(x=>x.type==="ended"?a.readyState<2:a.readyState<3),(0,O.filterChanged)()),i=(0,O.merge)((0,O.fromEvent)(a,"progress"),(0,O.fromEvent)(a,"timeupdate")).pipe((0,O.map)(()=>tb(a.buffered,a.currentTime))),s=O.clientChecker.isSafari?(0,O.combine)({play:e("play").pipe((0,O.once)()),playing:e("playing")}).pipe((0,O.mapTo)(void 0)):e("playing"),n=(0,O.fromEvent)(a,"volumechange").pipe((0,O.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,O.fromEvent)(a,"ratechange").pipe((0,O.map)(()=>a.playbackRate)),u=(0,O.fromEvent)(a,"error").pipe((0,O.filter)(()=>!!(a.error||a.played.length)),(0,O.map)(()=>{var w;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:O.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(w=a.error)!=null?w:void 0}})),l=(0,O.fromEvent)(a,"timeupdate").pipe((0,O.map)(()=>a.currentTime)),c=new O.Subject,d=.3,h;l.subscribe(x=>{a.loop&&(0,O.isNonNullable)(h)&&(0,O.isNonNullable)(x)&&h>=a.duration-d&&x<=d&&c.next(h),h=x});let p=e("pause").pipe((0,O.filter)(()=>!a.error&&h!==a.duration)),f=(0,O.fromEvent)(a,"enterpictureinpicture"),g=(0,O.fromEvent)(a,"leavepictureinpicture"),v=new O.ValueSubject(eb(a));f.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let I=new O.ValueSubject(Au(a));return(0,O.fromEvent)(a,"fullscreenchange").pipe((0,O.map)(()=>Au(a))).subscribe(I),{playing$:s,pause$:p,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,O.fromEvent)(a,"durationchange").pipe((0,O.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:I,enterPip$:f,leavePip$:g}};var Rt=require("@vkontakte/videoplayer-shared/es2015"),Jt=a=>{switch(a){case"mobile":return Rt.VideoQuality.Q_144P;case"lowest":return Rt.VideoQuality.Q_240P;case"low":return Rt.VideoQuality.Q_360P;case"sd":case"medium":return Rt.VideoQuality.Q_480P;case"hd":case"high":return Rt.VideoQuality.Q_720P;case"fullhd":case"full":return Rt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Rt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Rt.VideoQuality.Q_2160P}};var Xt=X(Xr(),1),pb=X(bt(),1),Us=X(Ur(),1),C=require("@vkontakte/videoplayer-shared/es2015");var ku=!1,$t={},ub=a=>{ku=a},lb=()=>{$t={}},cb=a=>{a($t)},Hi=(a,e)=>{var t;ku&&($t.meta=(t=$t.meta)!=null?t:{},$t.meta[a]=e)},Le=class{constructor(e){this.name=e}next(e){var r,i;if(!ku)return;$t.series=(r=$t.series)!=null?r:{};let t=(i=$t.series[this.name])!=null?i:[];t.push([Date.now(),e]),$t.series[this.name]=t}};var MA=new Le("best_bitrate"),hb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Ru=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),ji=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={}}},mb='Assertion "ABR Tracks is empty array" failed',Hs=(a,e,t,r)=>{var u;let i=[...e].sort(Ru(1)),s=[...t].sort(Ru(1)),n=s.filter(l=>(0,C.isNonNullable)(l.bitrate)&&(0,C.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Xt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Xt.default)(s,-1);return o&&(0,pb.default)(n,o)?o:n.length?(0,Xt.default)(n,-1):(0,Xt.default)(s,0)},db=a=>"quality"in a,fb=(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=db(o)?"video":"audio",l=db(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
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:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,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=p||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(!!d&&(0,C.isHigherOrEqual)(P.quality,d))return Q[P.quality]="DroppedFramesLimit",!1;if(!!h&&(0,C.isHigherOrEqual)(P.quality,h))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)(c)&&!c?(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:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},DA=(a,e)=>Math.log(e)/Math.log(a),Zt=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:f})=>{var te,B,ie,H,ne,$;(0,C.assertNotEmptyArray)(a,mb);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,We=0]=r.pixelRatioLogCoefficients,_t=DA(K,Y*P+be)+We;Number.isFinite(_t)&&(g*=_t)}}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,Xt.default)(T,-1))==null?void 0:te.quality,w=(B=(0,Xt.default)(T,0))==null?void 0:B.quality,A=(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)&&w&&(0,C.isHigher)(i.min,w)||(0,C.isNonNullable)(i.max)&&x&&(0,C.isLower)(i.max,x),N=I*hb(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=p||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(!!d&&(0,C.isHigherOrEqual)(P.quality,d))return Q[P.quality]="DroppedFramesLimit",!1;if(!!h&&(0,C.isHigherOrEqual)(P.quality,h))return Q[P.quality]="StallsLimit",!1;let re=A||((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)(c)&&!c?(0,C.isLowerOrEqual)(P.quality,r.backgroundVideoQualityLimit):!0;return!re||!Ie?(Q[P.quality]="FitsQualityLimits",!1):!0})[0];J&&J.bitrate&&MA.next(J.bitrate);let W=(ie=J!=null?J:(0,Xt.default)(T,-1))!=null?ie:a[0];return W.quality!==((H=l==null?void 0:l.last)==null?void 0:H.quality)&&f({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,qs.default)(r!=null?r:{}).map(([P,K])=>`${P}: ${K}`).join(`
16
+ ${(0,Us.default)(r!=null?r:{}).map(([P,K])=>`${P}: ${K}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
@@ -28,24 +28,24 @@
28
28
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
29
29
  droppedVideoMaxQualityLimit: ${d},
30
30
  stallsVideoMaxQualityLimit: ${h},
31
- limitsAreInvalid: ${w},
31
+ limitsAreInvalid: ${A},
32
32
  maxQualityLimit: ${i==null?void 0:i.max},
33
33
  minQualityLimit: ${i==null?void 0:i.min},
34
34
 
35
35
  [limited video tracks]
36
- ${(0,qs.default)(Q).map(([P,K])=>`${P}: ${K}`).join(`
36
+ ${(0,Us.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
- `}),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 c=i.considerPlaybackRate&&(0,C.isNonNullable)(s)?s:1,d=[...t].sort(wu(-1)),h=a.bitrate;(0,C.assertNonNullable)(h);let p=c*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=d.find(T=>(0,C.isNonNullable)(T.bitrate)&&(0,C.isNonNullable)(g==null?void 0:g.bitrate)?v-h>=T.bitrate*p&&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
+ `}),fb(r,f,W,l)},bb=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var I;(0,C.assertNotEmptyArray)(t,mb);let c=i.considerPlaybackRate&&(0,C.isNonNullable)(s)?s:1,d=[...t].sort(Ru(-1)),h=a.bitrate;(0,C.assertNonNullable)(h);let p=c*hb(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,g=Hs(a,e,t,i.minVideoAudioRatio),v=l||r;return(0,C.isNonNullable)(v)&&isFinite(v)&&(f=d.find(T=>(0,C.isNonNullable)(T.bitrate)&&(0,C.isNonNullable)(g==null?void 0:g.bitrate)?v-h>=T.bitrate*p&&T.bitrate>=g.bitrate:!1)),f||(f=g),(f==null?void 0:f.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,qs.default)(i!=null?i:{}).map(([T,x])=>`${T}: ${x}`).join(`
48
+ ${(0,Us.default)(i!=null?i:{}).map(([T,x])=>`${T}: ${x}`).join(`
49
49
  `)}
50
50
 
51
51
  [limit params]
@@ -58,15 +58,15 @@
58
58
  bitrateFactor: ${p},
59
59
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
60
60
 
61
- [selected audio track] ${m==null?void 0:m.id}
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,c,d,h=!1,p="arraybuffer",m=7e3,g=2e3,v=()=>{if(u)return;(0,gt.assertNonNullable)(c);let B=ku(c),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=>(d=B,te),x=()=>(p="json",te),A=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},w=B=>(h=B,te),N=()=>{c=ye(),n=new i,n.open("get",a);let B=0,ie,U=0,ne=()=>((0,gt.assertNonNullable)(c),Math.max(c,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():(d&&d(),e(n.response))}else A()}),n.addEventListener("error",()=>{A()}),h){let $=()=>{(0,gt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(U=ye(),n.removeEventListener("readystatechange",$))};n.addEventListener("readystatechange",$)}return n.responseType=p,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,d&&d()}};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,c=!1,d=()=>{let A=s&&(!c||c===this.rep);return A||t("Not running!"),A},h=(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()},p=(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(!d())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 c={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||d()&&Q.seek(()=>{d()&&(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(!d()||!this.sourceBuffer)return;let Ee,We,_t,xr=Nt=>{window.setTimeout(()=>{d()&&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=>{d()&&p(be(re),(Ie,Ee)=>{if(d()){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=>{d()&&((0,He.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(be(re),!1)))},Er=re=>{d()&&(e.cachedHeader=re,K(re,()=>{oe=!0,Y()}))};s=!0,Q.seek(re=>{if(d()){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):h(e.headerUrl,Er,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},c}_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=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=ye();if(this.chunkRateEstimator.addInterval(h,m,p)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:v}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ku(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ye();d<o&&(n=h),o=d}}}_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),c=(r=Kt(u.name))!=null?r:(0,V.videoSizeToQuality)(u.video),d=u.bitrate/1e3,h=R({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(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,c,d,h,p,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h: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=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let 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,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,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,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},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(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},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,c=ya(u),d=l*dt(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},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,c=!1,d=0;return Sr(a,({tag:h,type:p,value:m,valueSize:g})=>{if(h===21419){let v=ot(m,p);l=ya(v)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+g):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=ot(m,p):h===17545?i=ot(m,p):h===21420&&l===475249515?u=ot(m,p):h===374648427?Sr(m,({tag:v,type:I,value:T})=>v===30321?(c=ot(T,I)===1,!1):!0):s&&n&&(0,Ta.default)(Fg,h)&&(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:c,stereoMode:d,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:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},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})+",c=`^(?:(?<langtag>${`
61
+ [selected audio track] ${f==null?void 0:f.id}
62
+ `}),f&&fb(i,u,f,o)};var Se=a=>new URL(a).hostname;var V=require("@vkontakte/videoplayer-shared/es2015");var vb=X(bt(),1);var gb=a=>{if(a instanceof DOMException&&(0,vb.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"))},Be=(a,e)=>L(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!gb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return gb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});var Ge=require("@vkontakte/videoplayer-shared/es2015");var Sb=X(Ui(),1),St=require("@vkontakte/videoplayer-shared/es2015");function ye(){return(0,St.now)()}function $u(a){return ye()-a}function Lu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function yb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Zr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",f=7e3,g=2e3,v=()=>{if(u)return;(0,St.assertNonNullable)(c);let B=$u(c),ie;if(B<g){ie=g-B,setTimeout(v,ie);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new i,N()},I=B=>(s=B,te),T=B=>(d=B,te),x=()=>(p="json",te),w=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},A=B=>(h=B,te),N=()=>{c=ye(),n=new i,n.open("get",a);let B=0,ie,H=0,ne=()=>((0,St.assertNonNullable)(c),Math.max(c,Math.max(ie||0,H||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",()=>w())),n.addEventListener("load",()=>{if(u)return;(0,St.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,Sb.default)(n.response).length?w():(d&&d(),e(n.response))}else w()}),n.addEventListener("error",()=>{w()}),h){let $=()=>{(0,St.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(H=ye(),n.removeEventListener("readystatechange",$))};n.addEventListener("readystatechange",$)}return n.responseType=p,n.send(),te},te={withBitrateReporting:I,withParallel:A,withJSONResponse:x,withRetryCount:B=>(l=B,te),withRetryInterval:(B,ie)=>((0,St.isNonNullable)(B)&&(g=B),(0,St.isNonNullable)(ie)&&(f=ie),te),withTimeout:B=>(o=B,te),withFinally:T,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return te}var Gi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Tb=X(Ui(),1);var Qi=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=Zr(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,Tb.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 Ib=require("@vkontakte/videoplayer-shared/es2015"),js=1e4,Mu=3;var OA=6e4,VA=10,BA=1,_A=500,Wi=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 Ib.Subject,this.chunkRateEstimator=new Gi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Lu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Lu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ge.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=()=>{yb(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 Qi(Mu,js,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let w=s&&(!c||c===this.rep);return w||t("Not running!"),w},h=(w,A,N)=>{u&&u.abort(),u=Zr(this.urlResolver.resolve(w,!1),A,N,()=>this._retryCallback()).withTimeout(js).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Mu).withFinally(()=>{u=null}).send()},p=(w,A,N)=>{(0,Ge.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),A,N,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=w=>{let A=r.playbackRate;r.playbackRate!==w&&(t(`Playback rate switch: ${A}=>${w}`),r.playbackRate=w)},g=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let N=ye()-1e4,Q=0;for(let J=0;J<this.bufferStates.length;J++){let W=this.bufferStates[J];w=Math.min(w,W.buf),W.ts<N&&Q++}this.bufferStates.splice(0,Q),t(`update playback rate; minBuffer=${w} drop=${Q} jitter=${this.sourceJitter}`);let oe=w-BA;this.sourceJitter>=0?oe-=this.sourceJitter/2:this.sourceJitter-=1,oe>3?f(1.15):oe>1?f(1.1):oe>.3?f(1.05):f(1)}},I=w=>{let A,N=()=>A&&A.start?A.start.length:0,Q=$=>A.start[$]/1e3,oe=$=>A.dur[$]/1e3,J=$=>A.fragIndex+$,W=($,P)=>({chunkIdx:J($),startTS:Q($),dur:oe($),discontinuity:P}),te=()=>{let $=0;if(A&&A.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=A.dur.length-1;for(;be>=0&&(Y-=A.dur[be],!(Y<=0));--be);$=Math.min(be,A.dur.length-1-K),$=Math.max($,0)}return W($,!0)},B=$=>{let P=N();if(!(P<=0)){if((0,Ge.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-A.fragIndex;if(!(P<=0)){if(!$||Y<0||Y-P>VA)return t(`Resync: offset=${Y} bChunks=${P} chunk=`+JSON.stringify($)),te();if(!(Y>=P))return W(K-A.fragIndex,!1)}},H=($,P,K)=>{l&&l.abort(),l=Zr(this.urlResolver.resolve($,!0,this.lowLatency),P,K,()=>this._retryCallback()).withTimeout(js).withRetryCount(Mu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:($,P)=>{H(w,K=>{if(!d())return;A=K;let Y=!!A.lowLatency;Y!==this.lowLatency&&g(Y);let be=0;for(let We=0;We<A.dur.length;++We)be+=A.dur[We];be>0&&((0,Ge.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(be/A.dur.length)),i({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,$(B(P))},()=>this._handleNetworkError())},nextChunk:ie}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ge.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{let{videoElement:A,logger:N}=this.params,Q=I(e.jidxUrl),oe,J,W,te,B=0,ie,H,ne,$=()=>{ie&&(clearTimeout(ie),ie=void 0);let re=Math.max(_A,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ie=B+re,Ee=ye(),Ye=Math.min(1e4,Ie-Ee);B=Ee;let Nt=()=>{l||d()&&Q.seek(()=>{d()&&(B=ye(),P(),$())})};Ye>0?ie=window.setTimeout(()=>{this.paused?$():Nt()},Ye):Nt()},P=()=>{let re;for(;re=Q.nextChunk(te);)te=re,_t(re);let Ie=Q.nextChunk(W);if(Ie){if(W&&Ie.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?$():(T(),this._initPlayerWith(e));return}We(Ie)}else $()},K=(re,Ie)=>{if(!d()||!this.sourceBuffer)return;let Ee,Ye,Nt,Pr=Ft=>{window.setTimeout(()=>{d()&&K(re,Ie)},Ft)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),Pr(100);else{let Ft=ye(),ar=A.currentTime;!this.paused&&A.buffered.length>1&&H===ar&&Ft-ne>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),H!==ar&&(H=ar,ne=Ft);let wr=this._getBufferSizeSec();if(wr>30)N(`Buffered ${wr} seconds; delaying appendBuffer`),Pr(2e3);else try{this.sourceBuffer.appendBuffer(re),this.videoPlayStarted?(this.bufferStates.push({ts:Ft,buf:wr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ie&&Ie()}catch(ci){if(ci.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),Nt=this.sourceBuffer.buffered.length,Nt!==0&&(Ee=this.sourceBuffer.buffered.start(0),Ye=ar,Ye-Ee>4&&this.sourceBuffer.remove(Ee,Ye-3)),Pr(1e3);else throw ci}}},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),We=re=>{d()&&p(be(re),(Ie,Ee)=>{if(d()){if(Ee/=1e3,J=Ie,W=re,n=re.startTS,Ee){let Ye=Math.min(10,re.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ye:Ye}Y()}},()=>this._handleNetworkError())},_t=re=>{d()&&((0,Ge.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(be(re),!1)))},xr=re=>{d()&&(e.cachedHeader=re,K(re,()=>{oe=!0,Y()}))};s=!0,Q.seek(re=>{if(d()){if(B=ye(),!re){$();return}te=re,!(0,Ge.isNullable)(w)||re.startTS>w?We(re):(W=re,P())}},w),e.cachedHeader?xr(e.cachedHeader):h(e.headerUrl,xr,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ge.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,Ge.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ge.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),f=d/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let f=ye();if(this.chunkRateEstimator.addInterval(h,f,p)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:v}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&$u(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ye();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Zr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(js).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Be(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))},OA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Eb=X(Ur(),1),ce=require("@vkontakte/videoplayer-shared/es2015"),Du=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,Eb.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}},Gs=Du;var Qs=require("@vkontakte/videoplayer-shared/es2015"),xb=require("@vkontakte/videoplayer-shared/es2015");var Yi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var NA=(a,e)=>new Qs.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Yi()))},k(k({},r),e));i.observe(a);let s=(0,xb.fromEvent)(document,"visibilitychange").pipe((0,Qs.map)(n=>!document.hidden||Yi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Xe=NA;var FA=["paused","playing","ready"],qA=["paused","playing","ready"],zi=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new j("stopped");this.representations$=new V.ValueSubject([]);this.textTracksManager=new Je;this.droppedFramesManager=new Gs;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new kt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:V.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Jt(u.name))!=null?r:(0,V.videoSizeToQuality)(u.video),d=u.bitrate/1e3,h=k({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(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,Cu.default)(qA,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Cu.default)(FA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Ae(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(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(Ae(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=De(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=Ve(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(vt(this.video,this.params.desiredState.isLooped,t)).add(Oe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ke(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(Xe(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),Ce(this.video)}createLiveDashPlayer(){let e=new Wi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,V.isNonNullable)(t)?t:Zt(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=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(f=e.find(({track:v})=>v.id===s))==null?void 0:f.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(Ae(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Pb=zi;var Wv=X(bt(),1);var yt=(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 U=require("@vkontakte/videoplayer-shared/es2015");var Ws=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ei=class extends Ws{constructor(){super(),this.listeners||Ws.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Ki=class{constructor(){Object.defineProperty(this,"signal",{value:new ei,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&&(Ki.prototype[Symbol.toStringTag]="AbortController",ei.prototype[Symbol.toStringTag]="AbortSignal");function Ys(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Ou(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Ys({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Ji=Ys({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),wb=Ji?Ou({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ut=Ji?wb.fetch:window.fetch,N0=Ji?wb.Request:window.Request,ke=Ji?Ki:window.AbortController,F0=Ji?ei:window.AbortSignal;var ul=X(Bu(),1);var an=X(Xr(),1);var Lt=()=>window.ManagedMediaSource||window.MediaSource,zs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Qb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Wb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Tt=require("@vkontakte/videoplayer-shared/es2015");var Ze=document.createElement("video"),pk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',hk='video/mp4; codecs="hev1.1.6.L93.B0"',ag='video/webm; codecs="vp09.00.10.08"',sg='video/webm; codecs="av01.0.00M.08"',mk='audio/mp4; codecs="mp4a.40.2"',fk='audio/webm; codecs="opus"',Yb,zb,Xi={mms:zs(),mse:Qb(),hls:!!((Yb=Ze.canPlayType)!=null&&Yb.call(Ze,"application/x-mpegurl")||(zb=Ze.canPlayType)!=null&&zb.call(Ze,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Kb,Jb,_e={mp4:!!((Kb=Ze.canPlayType)!=null&&Kb.call(Ze,"video/mp4")),webm:!!((Jb=Ze.canPlayType)!=null&&Jb.call(Ze,"video/webm")),cmaf:!0},Js,Xb,Xs,Zb,Zs,eg,en,tg,tn,rg,rn,ig,Ne={h264:!!((Xb=(Js=Lt())==null?void 0:Js.isTypeSupported)!=null&&Xb.call(Js,pk)),h265:!!((Zb=(Xs=Lt())==null?void 0:Xs.isTypeSupported)!=null&&Zb.call(Xs,hk)),vp9:!!((eg=(Zs=Lt())==null?void 0:Zs.isTypeSupported)!=null&&eg.call(Zs,ag)),av1:!!((tg=(en=Lt())==null?void 0:en.isTypeSupported)!=null&&tg.call(en,sg)),aac:!!((rg=(tn=Lt())==null?void 0:tn.isTypeSupported)!=null&&rg.call(tn,mk)),opus:!!((ig=(rn=Lt())==null?void 0:rn.isTypeSupported)!=null&&ig.call(rn,fk))},ti=(Ne.h264||Ne.h265)&&Ne.aac,vr,bk=()=>L(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(F(k({},a),{video:F(k({},a.video),{contentType:sg})})),window.navigator.mediaCapabilities.decodingInfo(F(k({},a),{video:F(k({},a.video),{contentType:ag})}))]);vr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{bk()}catch(a){console.error(a)}var ri=Xi.hls&&_e.mp4,ng=()=>Object.keys(Ne).filter(a=>Ne[a]),og=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Xi.mse&&(!r||!!window.MediaStreamTrack)||Xi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&_e.mp4&&ti;case"DASH_WEBM":return i&&_e.webm&&Ne.vp9&&Ne.opus;case"DASH_WEBM_AV1":return i&&_e.webm&&Ne.av1&&Ne.opus;case"DASH_STREAMS":return i&&(_e.mp4&&ti||_e.webm&&(Ne.vp9||Ne.av1)&&(Ne.opus||Ne.aac));case"DASH_LIVE":return i&&_e.mp4&&ti;case"DASH_LIVE_CMAF":return i&&_e.mp4&&ti&&_e.cmaf;case"DASH_ONDEMAND":return i&&_e.mp4&&ti;case"HLS":case"HLS_ONDEMAND":return ri||e&&i&&_e.mp4&&ti;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ri;case"MPEG":return _e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Xi.webrtc&&Xi.ws&&Ne.h264&&(_e.mp4||_e.webm);default:return(0,Tt.assertNever)(s)}})},Ks=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return vr?vr[t].smooth?[t,e]:vr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return vr?vr[t].powerEfficient?[t,e]:vr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,Tt.assertNever)(a)}return[e,t]},ug=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ks(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Tt.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",...Ks(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ks(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ks(a),...i,"HLS","HLS_ONDEMAND"];default:(0,Tt.assertNever)(e)}return ri?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},lg=({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=Tt.clientChecker.isMac&&Tt.clientChecker.isSafari;if(Tt.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,Tt.assertNever)(a)}else ri&&!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"]},_u=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],cg=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,an.default)(t.value.split("."),0)}for(let t of a){let r=(0,an.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,an.default)(e.value.split("."),0)};var Lg=X($g(),1),ii=require("@vkontakte/videoplayer-shared/es2015"),Mg=a=>{if(!a)return{id:"EmptyResponse",category:ii.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ii.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,Lg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ii.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:ii.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ii.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var er=(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 sn=X(bt(),1),oi=X(Xr(),1),nn=X(Bu(),1);var Dk=(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)},Ck=a=>window.clearTimeout(a),Dg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Cg=!Dg(window.requestIdleCallback)||!Dg(window.cancelIdleCallback),Hu=Cg?Dk:window.requestIdleCallback,ea=Cg?Ck:window.cancelIdleCallback;var Nv=X(_s(),1);var et=require("@vkontakte/videoplayer-shared/es2015");var Ok=18,Og=!1;try{Og=et.clientChecker.isSafari&&!!et.clientChecker.macVersion&&et.clientChecker.macVersion<=Ok}catch(a){console.error(a)}var ju=class{constructor(e){this.bufferFull$=new et.Subject;this.error$=new et.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:et.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return L(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 L(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 L(this,null,function*(){return new Promise(t=>{let r;Og&&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:et.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,et.assertNever)(t)}}},Vg=ju;var Gu=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 ai=class extends ae{};var ta=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 ra=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 ia=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 aa=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 sa=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var na=class extends ae{constructor(e,t){super(e,t),this.data=this.content}};var Sr=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 oa=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ua=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var la=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 ca=class extends de{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var da=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 pa=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ha=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 ma=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ba=class extends de{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ga=class extends ae{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var va=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 Sa=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 ya=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 Bk={ftyp:ra,moov:ia,mvhd:aa,moof:sa,mdat:na,sidx:Sr,trak:oa,mdia:pa,mfhd:ba,tkhd:ha,traf:ga,tfhd:va,tfdt:Sa,trun:ya,minf:ma,sv3d:ua,st3d:la,prhd:ca,proj:fa,equi:da,uuid:ta,unknown:ai},Mt=class a{constructor(e={}){this.options=k({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=Bk[e];return r?new r(t,new a):new ai(t,new a)}};var tr=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 Nk=new TextDecoder("ascii"),Fk=a=>Nk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",qk=a=>{let e=new Sr(a,new Mt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Uk=(a,e)=>{let r=new Mt().parse(a),i=new tr(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},Hk=a=>{let t=new Mt().parse(a),r=new tr(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},jk=a=>{var i;let t=new Mt().parse(a);return(i=new tr(t).find("sidx"))==null?void 0:i.timescale},Gk=(a,e)=>{let r=new Mt().parse(a),s=new tr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},Qk=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Mt().parse(a),i=new tr(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},Bg={validateData:Fk,parseInit:Qk,getIndexRange:()=>{},parseSegments:qk,parseFeedableSegmentChunk:Uk,getChunkEndTime:Gk,getServerLatencyTimestamps:Hk,getTimescaleFromIndex:jk};var Ia=X(bt(),1),Dt=require("@vkontakte/videoplayer-shared/es2015");var Ng=require("@vkontakte/videoplayer-shared/es2015");var _g={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"}},Fg=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=Ta(a,t),i=r in _g,s=i?_g[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Ta(u),d=l*ht(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},Ta=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*ht(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*ht(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*ht(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},lt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ta(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,Ng.assertNever)(e)}},yr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Fg(r);if(!e(i))return;i.type==="master"&&yr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},qg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Fg(a);return yr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=lt(o,n):s===17026?t=lt(o,n):s===17029&&(r=lt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Ug=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Wk=[231,22612,22743,167,171,163,160,175],Yk=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return yr(a,({tag:h,type:p,value:f,valueSize:g})=>{if(h===21419){let v=lt(f,p);l=Ta(v)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+g):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=lt(f,p):h===17545?i=lt(f,p):h===21420&&l===475249515?u=lt(f,p):h===374648427?yr(f,({tag:v,type:I,value:T})=>v===30321?(c=lt(T,I)===1,!1):!0):s&&n&&(0,Ia.default)(Ug,h)&&(o=!0),!o}),(0,Dt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Dt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Dt.assertNonNullable)(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},zk=a=>{if((0,Dt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Kk=(a,e)=>{let t=!1,r=!1,i=o=>(0,Dt.isNonNullable)(o.time)&&(0,Dt.isNonNullable)(o.position),s=[],n;return yr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=lt(l,u));break;case 183:break;case 241:n&&(n.position=lt(l,u));break;default:t&&(0,Ia.default)(Ug,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Jk=a=>{let e=0,t=!1;try{yr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Ia.default)(Wk,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Ia.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},Hg={validateData:qg,parseInit:Yk,getIndexRange:zk,parseSegments:Kk,parseFeedableSegmentChunk:Jk};var Ea=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Hg;case"mp4":return Bg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Zu=X(lv(),1),$v=X(Ur(),1),Lv=X(Pv(),1),Mv=X(Xr(),1);var wv=X(bt(),1),Xu=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,wv.default)(["6E","7A","F4"],o)}}return!1};var ni=require("@vkontakte/videoplayer-shared/es2015");var Av=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var kv=a=>{var e;try{let t=QR(),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 QR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<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(c,"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,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,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)p=wv(m);else if(g){let xe=wv(g);(0,si.isNonNullable)(xe)&&(p=xe)}else I&&(p=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:p,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)(p)){let rt=parseInt((Gl=ke.getAttribute("duration"))!=null?Gl:"",10)/tt*1e3,Lr=Math.ceil(p/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:p,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:c,liveAvailabilityStartTime:h,duration:p,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),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,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,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Ge(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);(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 c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new 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,c;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(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=vt(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&Hu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=vt(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,an.default)(o,i))d="high";else{let h=(0,ni.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&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(h=>H(R({},h),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,ni.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(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:d,time:{from:h,to:p}},m)=>{let g=h<=r&&p>=r,v=h>r||g||m===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=r+I||p<=r+I;return(d==="none"||d==="partially_ejected"&&v&&T&&this.sourceBuffer&&!(Zt(this.sourceBuffer.buffered,h)&&Zt(this.sourceBuffer.buffered,p)))&&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,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,r="auto"){return 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 c=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,E.now)(),!c)return;let d=new DataView(c),h=Ia(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=h.getChunkEndTime(d,g)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ea(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())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,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,an.default)(e,t.segment)&&this.abortSegment(t.segment)}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 c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ia(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return 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:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,h=c.byte.to-r,p=h-d+1,m=d<i,g=h<=i;if(!m)continue;let v=Ia(u.mime);if(c.status==="downloading"&&g){c.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(I,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,i-d),l.loadedBytes>l.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===p?I:v.parseFeedableSegmentChunk(I);T!=null&&T.byteLength&&(c.status="partially_fed",l.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(l.fedBytes+=T.byteLength,l.fedBytes===p&&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:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Ge(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category: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((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(R({},u.time)),i=n(i);let l=il(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,an.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(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(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var 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 c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let U=new URL(c,location.href);U.searchParams.append("bytes",`${r.from}-${r.to}`),c=U.toString();break}default:(0,Z.assertNever)(t)}this.requestQuic&&(c=Pa(c));let p=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)}p=U.signal}let g=(0,Z.now)();h.log("startRequest",(0,Z.flattenObject)({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let v=yield Rt(c,{priority:s,headers:d,signal:p}).catch(Aa),I=(0,Z.now)();if(!v)return h.error("error",{message:"No response in request"}),h.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 h.error("error",{message:U}),h.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 h.log("endRequest",(0,Z.flattenObject)(ne)),h.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)(p,function($){return me(this,arguments,function*({done:U,value:ne}){if(w===0&&this.lastRequestFirstBytes$.next((0,Z.now)()-g),p.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?(h.error("endRequest",(0,Z.flattenObject)(te)),h.end(),null):(h.log("endRequest",(0,Z.flattenObject)(te)),h.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,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(I=e.indexRange)!=null?I:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let 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,p,m);return{init:p,dataView:new DataView(d),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(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(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,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=$t())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>r(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=ug(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=i.video.some(v=>v.hdr),g=i.video.some(v=>!v.hdr);S.clientChecker.isHDR&&p&&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 h;this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(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 p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new xa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((m,g)=>[...m,...g.representations],[]);this.audioBufferManager=new xa("audio",this.source,p,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(p=>{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 p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...YR.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?vt(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(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 p=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)&&(p=m>p?m:p),W==="live_forward_buffering"||W==="live_with_target_offset"){let te=p-(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"&&(p=0,this.updateLive())})))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.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(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var m;return(m=this.source)==null?void 0:m.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...(0,nl.default)((0,nl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),Ge(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/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 p,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=(p=this.videoBufferManager)==null?void 0:p.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,c=(A=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?A:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&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;
69
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Rv=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,Zu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,$v.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Zu.default)(t,n,(o,u)=>(0,ni.isNullable)(s)?o:(0,ni.isNullable)(u)?s:(0,Lv.default)(s,parseInt(u,10),"0"))}return t},Dv=(a,e)=>{var A,N,Q,oe,J,W,te,B,ie,H,ne,$,P,K,Y,be,We,_t,xr,re,Ie,Ee,Ye,Nt,Pr,Ft,ar,wr,ci,gl,vl,Sl,yl,Tl,Il,El,xl,Pl,wl,Al,kl,Rl,$l,Ll,Ml,Dl,Cl,Ol,Vl,Bl,_l,Nl,Fl,ql,Ul,Hl,jl,Gl,Ql,Wl;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 ja,qt;return(qt=(ja=xe.textContent)==null?void 0:ja.trim())!=null?qt:""}),u=(A=(0,Mv.default)(o,0))!=null?A:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),g=n.getAttribute("duration"),v=s.getElementsByTagName("vk:Attrs")[0],I=v==null?void 0:v.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=Rv(f);else if(g){let xe=Rv(g);(0,ni.isNonNullable)(xe)&&(p=xe)}else I&&(p=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 ja=(oe=xe.getAttribute("id"))!=null?oe:"id"+(T++).toString(10),qt=(J=xe.getAttribute("mimeType"))!=null?J:"",In=(W=xe.getAttribute("codecs"))!=null?W:"",En=(te=xe.getAttribute("contentType"))!=null?te:qt==null?void 0:qt.split("/")[0],gS=(ie=(B=xe.getAttribute("profiles"))==null?void 0:B.split(","))!=null?ie:[],Yl=(ne=kv((H=xe.getAttribute("lang"))!=null?H:""))!=null?ne:{},vS=(K=(P=($=xe.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:P.trim())!=null?K:void 0,SS=xe.querySelectorAll("Representation"),yS=xe.querySelector("SegmentTemplate"),TS=(be=(Y=xe.querySelector("Role"))==null?void 0:Y.getAttribute("value"))!=null?be:void 0,di=En,ge={id:ja,language:Yl.language,isDefault:TS==="main",label:vS,codecs:In,hdr:di==="video"&&Xu(In),mime:qt,representations:[]};for(let ue of SS){let IS=(We=ue.getAttribute("lang"))!=null?We:void 0,ES=(_t=ue.getAttribute("label"))!=null?_t:void 0,xS=(Ie=(re=(xr=ue.querySelector("BaseURL"))==null?void 0:xr.textContent)==null?void 0:re.trim())!=null?Ie:"",Ga=new URL(xS||u,e).toString(),Ar=(Ee=ue.getAttribute("mimeType"))!=null?Ee:qt,Qa=(Nt=(Ye=ue.getAttribute("codecs"))!=null?Ye:In)!=null?Nt:"",Wa;if(En==="text"){let Ut=ue.getAttribute("id")||"",Ya=((Pr=Yl.privateuse)==null?void 0:Pr.includes("x-auto"))||Ut.includes("_auto"),sr=ue.querySelector("SegmentTemplate");if(sr){let pi={representationId:(Ft=ue.getAttribute("id"))!=null?Ft:void 0,bandwidth:(ar=ue.getAttribute("bandwidth"))!=null?ar:void 0},za=parseInt((wr=ue.getAttribute("bandwidth"))!=null?wr:"",10)/1e3,Ka=(gl=parseInt((ci=sr.getAttribute("startNumber"))!=null?ci:"",10))!=null?gl:1,kr=parseInt((vl=sr.getAttribute("timescale"))!=null?vl:"",10),xn=(Sl=sr.querySelectorAll("SegmentTimeline S"))!=null?Sl:[],Rr=sr.getAttribute("media");if(!Rr)continue;let Ja=[],Xa=0,Za="",$r=0,hi=Ka,Re=0;for(let rt of xn){let nr=parseInt((yl=rt.getAttribute("d"))!=null?yl:"",10),ze=parseInt((Tl=rt.getAttribute("r"))!=null?Tl:"",10)||0,Ht=parseInt((Il=rt.getAttribute("t"))!=null?Il:"",10);Re=Number.isFinite(Ht)?Ht:Re;let or=nr/kr*1e3,jt=Re/kr*1e3;for(let dt=0;dt<ze+1;dt++){let Gt=Ct(Rr,F(k({},pi),{segmentNumber:hi.toString(10),segmentTime:(Re+dt*nr).toString(10)})),Lr=(jt!=null?jt:0)+dt*or,fi=Lr+or;hi++,Ja.push({time:{from:Lr,to:fi},url:Gt})}Re+=(ze+1)*nr,Xa+=(ze+1)*or}$r=Re/kr*1e3,Za=Ct(Rr,F(k({},pi),{segmentNumber:hi.toString(10),segmentTime:Re.toString(10)}));let mi={time:{from:$r,to:1/0},url:Za},Et={type:"template",baseUrl:Ga,segmentTemplateUrl:Rr,initUrl:"",totalSegmentsDurationMs:Xa,segments:Ja,nextSegmentBeyondManifest:mi,timescale:kr};Wa={id:Ut,kind:"text",segmentReference:Et,profiles:[],duration:p,bitrate:za,mime:"",codecs:"",width:0,height:0,isAuto:Ya}}else Wa={id:Ut,isAuto:Ya,kind:"text",url:Ga}}else{let Ut=(xl=(El=ue.getAttribute("contentType"))!=null?El:Ar==null?void 0:Ar.split("/")[0])!=null?xl:En,Ya=(wl=(Pl=xe.getAttribute("profiles"))==null?void 0:Pl.split(","))!=null?wl:[],sr=parseInt((Al=ue.getAttribute("width"))!=null?Al:"",10),pi=parseInt((kl=ue.getAttribute("height"))!=null?kl:"",10),za=parseInt((Rl=ue.getAttribute("bandwidth"))!=null?Rl:"",10)/1e3,Ka=($l=ue.getAttribute("frameRate"))!=null?$l:"",kr=(Ll=ue.getAttribute("quality"))!=null?Ll:void 0,xn=Ka?Av(Ka):void 0,Rr=(Ml=ue.getAttribute("id"))!=null?Ml:"id"+(T++).toString(10),Ja=Ut==="video"?`${pi}p`:Ut==="audio"?`${za}Kbps`:Qa,Xa=`${Rr}@${Ja}`,Za=[...x,...gS,...Ya],$r,hi=ue.querySelector("SegmentBase"),Re=(Dl=ue.querySelector("SegmentTemplate"))!=null?Dl:yS;if(hi){let Et=(Ol=(Cl=ue.querySelector("SegmentBase Initialization"))==null?void 0:Cl.getAttribute("range"))!=null?Ol:"",[rt,nr]=Et.split("-").map(Gt=>parseInt(Gt,10)),ze={from:rt,to:nr},Ht=(Vl=ue.querySelector("SegmentBase"))==null?void 0:Vl.getAttribute("indexRange"),[or,jt]=Ht?Ht.split("-").map(Gt=>parseInt(Gt,10)):[],dt=Ht?{from:or,to:jt}:void 0;$r={type:"byteRange",url:Ga,initRange:ze,indexRange:dt}}else if(Re){let Et={representationId:(Bl=ue.getAttribute("id"))!=null?Bl:void 0,bandwidth:(_l=ue.getAttribute("bandwidth"))!=null?_l:void 0},rt=parseInt((Nl=Re.getAttribute("timescale"))!=null?Nl:"",10),nr=(Fl=Re.getAttribute("initialization"))!=null?Fl:"",ze=Re.getAttribute("media"),Ht=(Ul=parseInt((ql=Re.getAttribute("startNumber"))!=null?ql:"",10))!=null?Ul:1,or=Ct(nr,Et);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");let jt=(Hl=Re.querySelectorAll("SegmentTimeline S"))!=null?Hl:[],dt=[],Gt=0,Lr="",fi=0;if(jt.length){let es=Ht,it=0;for(let Mr of jt){let pt=parseInt((jl=Mr.getAttribute("d"))!=null?jl:"",10),ur=parseInt((Gl=Mr.getAttribute("r"))!=null?Gl:"",10)||0,ts=parseInt((Ql=Mr.getAttribute("t"))!=null?Ql:"",10);it=Number.isFinite(ts)?ts:it;let Pn=pt/rt*1e3,wn=it/rt*1e3;for(let rs=0;rs<ur+1;rs++){let wS=Ct(ze,F(k({},Et),{segmentNumber:es.toString(10),segmentTime:(it+rs*pt).toString(10)})),zl=(wn!=null?wn:0)+rs*Pn,AS=zl+Pn;es++,dt.push({time:{from:zl,to:AS},url:wS})}it+=(ur+1)*pt,Gt+=(ur+1)*Pn}fi=it/rt*1e3,Lr=Ct(ze,F(k({},Et),{segmentNumber:es.toString(10),segmentTime:it.toString(10)}))}else if((0,ni.isNonNullable)(p)){let it=parseInt((Wl=Re.getAttribute("duration"))!=null?Wl:"",10)/rt*1e3,Mr=Math.ceil(p/it),pt=0;for(let ur=1;ur<Mr;ur++){let ts=Ct(ze,F(k({},Et),{segmentNumber:ur.toString(10),segmentTime:pt.toString(10)}));dt.push({time:{from:pt,to:pt+it},url:ts}),pt+=it}fi=pt,Lr=Ct(ze,F(k({},Et),{segmentNumber:Mr.toString(10),segmentTime:pt.toString(10)}))}let PS={time:{from:fi,to:1/0},url:Lr};$r={type:"template",baseUrl:Ga,segmentTemplateUrl:ze,initUrl:or,totalSegmentsDurationMs:Gt,segments:dt,nextSegmentBeyondManifest:PS,timescale:rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ut||!Ar)continue;let mi={video:"video",audio:"audio",text:"text"}[Ut];if(!mi)continue;di||(di=mi),Wa={id:Xa,kind:mi,segmentReference:$r,profiles:Za,duration:p,bitrate:za,mime:Ar,codecs:Qa,width:sr,height:pi,fps:xn,quality:kr}}ge.language||(ge.language=IS),ge.label||(ge.label=ES),ge.mime||(ge.mime=Ar),ge.codecs||(ge.codecs=Qa),ge.hdr||(ge.hdr=di==="video"&&Xu(Qa)),ge.representations.push(Wa)}di&&i[di].push(ge)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var rl=X(Xr(),1);var Cv=require("@vkontakte/videoplayer-shared/es2015"),Ov=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Jt(s):void 0)!=null?u:(0,Cv.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Vv=({id:a,bitrate:e})=>({id:a,bitrate:e}),Bv=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),_v=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),il=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,rl.default)(r.split("."),0),isDefault:i}),al=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,rl.default)(i.split("."),0)}),sl=a=>"url"in a,Qe=a=>a.type==="template",xa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Pa=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 ke;this.switchAbortController=new ke;this.destroyAbortController=new ke;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,E.abortable)(this.destroyAbortController.signal,function(e){return fe(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 Vg(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,Gu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=yt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,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 fe(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 kn(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 fe(this,null,function*(){var u,l;let t=(u=(0,nn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Qe(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);(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 c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ke,(0,E.abortable)(this.switchAbortController.signal,function(r,i=!1){return fe(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 ke,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;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(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=yt(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&Gu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=yt(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,sn.default)(o,i))d="high";else{let h=(0,oi.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&yt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,oi.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,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,nn.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,nn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Qe(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>F(k({},h),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,oi.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(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(!Qe(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&&ea&&ea(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ea&&ea(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:h,to:p}},f)=>{let g=h<=r&&p>=r,v=h>r||g||f===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=r+I||p<=r+I;return(d==="none"||d==="partially_ejected"&&v&&T&&this.sourceBuffer&&!(er(this.sourceBuffer.buffered,h)&&er(this.sourceBuffer.buffered,p)))&&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,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,r="auto"){return L(this,null,function*(){Qe(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return L(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 fe(this,null,function*(){let c=(0,E.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,E.now)(),!c)return;let d=new DataView(c),h=Ea(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=h.getChunkEndTime(d,g)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(d);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),xa(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return L(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 fe(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),xa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,oi.default)(e,0).byte.from,to:(0,oi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(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(!Qe(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,sn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return L(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ea(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return L(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,h=c.byte.to-r,p=h-d+1,f=d<i,g=h<=i;if(!f)continue;let v=Ea(u.mime);if(c.status==="downloading"&&g){c.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(I,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,i-d),l.loadedBytes>l.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),T=l.loadedBytes===p?I:v.parseFeedableSegmentChunk(I);T!=null&&T.byteLength&&(c.status="partially_fed",l.feedingBytes+=T.byteLength,(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?(l.fedBytes+=T.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&((0,E.assertNonNullable)(this.sourceBuffer),er(this.sourceBuffer.buffered,e.segment.time.from,100)&&er(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",sl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");(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=Hu(()=>(0,Nv.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return L(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,E.abortable)(this.destroyAbortController.signal,function(){return fe(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,Ea(e.mime),i)).then(o=>L(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Qe(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:E.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return L(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 L(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((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(k({},u.time)),i=n(i);let l=sl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,sn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||(0,E.isNullable)(e)?0:yt(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=Hu(()=>{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(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var wa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Fv=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};var Z=require("@vkontakte/videoplayer-shared/es2015");var qv=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var on=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 ke;this.subscription=new Z.Subscription;this.fetchManifest=(0,Z.abortable)(this.abortAllController.signal,function(e){return fe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=wa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=qv(r));let i=yield ut(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 fe(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 c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let H=new URL(c,location.href);H.searchParams.append("bytes",`${r.from}-${r.to}`),c=H.toString();break}default:(0,Z.assertNever)(t)}this.requestQuic&&(c=wa(c));let p=this.abortAllController.signal,f;if(n){let H=new ke;if(f=(0,Z.merge)((0,Z.fromEvent)(this.abortAllController.signal,"abort"),(0,Z.fromEvent)(n,"abort")).subscribe(()=>{try{H.abort()}catch(ne){Aa(ne)}}),this.abortAllController.signal.aborted||n.aborted)try{H.abort()}catch(ne){Aa(ne)}p=H.signal}let g=(0,Z.now)();h.log("startRequest",(0,Z.flattenObject)({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let v=yield ut(c,{priority:s,headers:d,signal:p}).catch(Aa),I=(0,Z.now)();if(!v)return h.error("error",{message:"No response in request"}),h.end(),f==null||f.unsubscribe(),null;if((B=this.throughputEstimator)==null||B.addRawRtt(I-g),!v.ok||!v.body){f==null||f.unsubscribe();let H=`Fetch error ${v.status}: ${v.statusText}`;return h.error("error",{message:H}),h.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!i&&!o){f==null||f.unsubscribe();let H=(0,Z.now)(),ne={requestStartedAt:g,requestEndedAt:H,duration:H-g};return h.log("endRequest",(0,Z.flattenObject)(ne)),h.end(),v.arrayBuffer()}let[T,x]=v.body.tee(),w=T.getReader();o&&((ie=this.throughputEstimator)==null||ie.trackStream(x,u));let A=0,N=new Uint8Array(0),Q=!1,oe=H=>{f==null||f.unsubscribe(),Q=!0,Aa(H)},J=(0,Z.abortable)(p,function($){return fe(this,arguments,function*({done:H,value:ne}){if(A===0&&this.lastRequestFirstBytes$.next((0,Z.now)()-g),p.aborted){f==null||f.unsubscribe();return}if(!H&&ne){let P=new Uint8Array(N.length+ne.length);P.set(N),P.set(ne,N.length),N=P,A+=ne.byteLength,i==null||i(new DataView(N.buffer),A),yield w==null?void 0:w.read().then(J,oe)}})}.bind(this));yield w==null?void 0:w.read().then(J,oe),f==null||f.unsubscribe();let W=(0,Z.now)(),te={failed:Q,requestStartedAt:g,requestEndedAt:W,duration:W-g};return Q?(h.error("endRequest",(0,Z.flattenObject)(te)),h.end(),null):(h.log("endRequest",(0,Z.flattenObject)(te)),h.end(),N.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,Z.abortable)(this.abortAllController.signal,function(e,t,r){return fe(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,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(I=e.indexRange)!=null?I:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,f.from-n,f.to-f.from+1);else{let T=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let v=t.parseSegments(g,p,f);return{init:p,dataView:new DataView(d),segments:v}})}.bind(this));this.fetchTemplateRepresentation=(0,Z.abortable)(this.abortAllController.signal,function(e,t){return fe(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=>F(k({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=Fv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return L(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(!xa(a))throw a};var Tr=(a,e,t)=>t*e+(1-t)*a,nl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Uv=(a,e,t,r)=>{let i=0,s=t,n=nl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};var ka=require("@vkontakte/videoplayer-shared/es2015");var rr=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new ka.ValueSubject(e.initial),this.debounced$=new ka.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Le(`raw_${t}`),this.smoothedSeries$=new Le(`smoothed_${t}`),this.reportedSeries$=new Le(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=ht(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,ka.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var un=class extends rr{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Tr(this.slow,e,this.params.emaAlphaSlow),this.fast=Tr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ln=class extends rr{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=nl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Tr(this.emaSmoothed,e,this.params.emaAlpha);let r=Uv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var cn=class extends rr{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Tr(this.smoothed,t,this.params.emaAlpha):t}};var Ir=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new un({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ln({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 cn(k({initial:e,label:"liveEdgeDelay"},t))}};var ol=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var dn=require("@vkontakte/videoplayer-shared/es2015");var Ra=class a{constructor(e,t){this.currentRepresentation$=new dn.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,dn.isNullable)(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(F(k({},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&&Qe(t.segmentReference))}};var zR=["timeupdate","progress","play","seeked","stalled","waiting"],KR=["timeupdate","progress","loadeddata","playing","seeked"];var pn=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 ke;this.initManifest=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return fe(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Ae(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 fe(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=Dv(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Mg(e))!=null?n:{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,h,p,f;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((f=(p=Lt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:f})=>r(u,p,f)),d=new Set(c.map(({codecs:p})=>p)),h=cg(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=i.video.some(v=>v.hdr),g=i.video.some(v=>!v.hdr);S.clientChecker.isHDR&&p&&f?i.video=i.video.filter(v=>v.hdr):g&&(i.video=i.video.filter(v=>!v.hdr))}}let s=F(k({},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 fe(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(f=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Wb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&zs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new Pa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((f,g)=>[...f,...g.representations],[]);this.audioBufferManager=new Pa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ra.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ra(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add((0,S.interval)(1e3).subscribe(p=>{var f;if((f=this.element)!=null&&f.paused){let g=Ns(this.manifestUrlString,2);this.manifestUrlString=Ae(this.manifestUrlString,g+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...KR.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?yt(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe((0,S.filterChanged)()).subscribe(f=>ol(this.element,1))),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe((0,S.filter)(({bufferLength:f,isActiveLowLatency:g})=>g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),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:f})=>f),(0,S.map)(f=>k({},f)),(0,S.filterChanged)((f,g)=>g.bufferLength<f.bufferLength),(0,S.map)(({rtt:f,bufferLength:g,segmentServerLatency:v})=>{let I=Ns(this.manifestUrlString,2);return(f/2+g+v+I)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:f,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=f-v,w=1;Math.abs(x)>I&&(w=1+Math.sign(x)*T),ol(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var v,I;let g=0;if(f){let T=((I=(v=this.element)==null?void 0:v.currentTime)!=null?I:0)*1e3;g=Math.min(...this.bufferManagers.map(w=>{var A,N;return(N=(A=w.getLiveSegmentsToLoadState(this.manifest))==null?void 0:A.to)!=null?N:T}))-T}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let p=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(v=>L(this,[v],function*({liveLoadBufferLength:f,bufferLength:g}){if((0,S.assertNonNullable)(this.element),this.isUpdatingLive)return;let I=this.element.playbackRate,T=Ns(this.manifestUrlString,2),x=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,w=Math.min(x,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*I),A=this.tuning.dashCmafLive.normalizedActualBufferOffset*I,N=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*I,Q=isFinite(f)?f: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<w?W="live_forward_buffering":Q<w+N&&(W="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),W==="live_forward_buffering"||W==="live_with_target_offset"){let te=p-(w+A),B=this.normolizeLiveOffset(Math.trunc(T+te/I)),ie=Math.abs(B-T),H;!f||ie<=this.tuning.dashCmafLive.offsetCalculationError?H=T:B>0&&ie>this.tuning.dashCmafLive.offsetCalculationError?H=B:H=0,this.manifestUrlString=Ae(this.manifestUrlString,H,2)}W!=="none"&&W!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:p,someBufferEnded:f})=>p&&f))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...(0,ul.default)((0,ul.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let f=[];return p.duration&&f.push(p.duration),Qe(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/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 on({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Ir.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,k({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return L(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=Ae(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)(...zR.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&&er(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,g,v,I,T,x,w,A,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=(f=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?f: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,c=(w=(x=this.audioBufferManager)==null?void 0:x.getForwardBufferDuration())!=null?w:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&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;(A=this.videoBufferManager)==null||A.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 L(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),er(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 L(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=F(k({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,S.flattenObject)(t)))}}};var hn=class{constructor(e,t){this.fov=e,this.orientation=t}};var mn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/ht(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=k({},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*ht(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var jv=`attribute vec2 a_vertex;
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 Hv=`#ifdef GL_ES
80
+ `;var Gv=`#ifdef GL_ES
81
81
  precision highp float;
82
82
  precision highp int;
83
83
  #else
@@ -120,5 +120,6 @@ void main(void) {
120
120
  // sample using new coordinates
121
121
  gl_FragColor = texture2D(u_texture, tc);
122
122
  }
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,c=t+i,d=e-r,h=t+i;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var 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(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,Te.now)(),h=n&&this.currentStallsCount>=n,p=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,m=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(h||p||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(){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 d=this.player.getStreams();if((0,q.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let m of d.audio){p.push(tl(m));let g=[];for(let v of m.representations){let I=Dv(v);g.push(I),this.audioTracksMap.set(I,{stream:m,representation:v})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(rl(p));let m=[];for(let g of p.representations){let v=Cv(H(R({},g),{streamId:p.id}));v&&(m.push(v),this.videoTracksMap.set(v,{stream:p,representation:g}))}this.videoStreamsMap.set(p,m)}this.params.output.availableVideoStreams$.next(h);for(let p of d.text)for(let m of p.representations){let g=Ov(p,m);this.textTracksMap.set(g,{stream:p,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else 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(),d=this.player.state$.getTransition();if(!(0,Gv.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,m]=h,g=[...this.videoTracksMap.keys()].find(I=>{var T;return((T=this.videoTracksMap.get(I))==null?void 0:T.representation.id)===p.id});(0,q.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")this.player.initRepresentations(p.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(o),m){let I=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,I).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,q.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:p}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(rl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,q.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(tl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.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),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=vt(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),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,c,(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,c,(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(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),T=r?I!=null?I:n:n!=null?n:I,x=g&&fb(T,c,($=this.audioStreamsMap.get(g))!=null?$:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),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(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Me(this.video),this.tracer.end()}};var $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.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((0,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,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(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 c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:z.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),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((c,d)=>{var T,x;let h=d.name||d.height.toString(10),{width:p,height:m}=d,g=(x=Kt((T=d.attrs.QUALITY)!=null?T:""))!=null?x:(0,z.videoSizeToQuality)({width:p,height:m});if(!g)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:h.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:v};return this.trackLevels.set(h,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(oi(this.hls,ut.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),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 h,p,m,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((g=d==null?void 0:d.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 c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.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 c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(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:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,cl.default)(l[1].split(",").map(T=>T.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=ZR(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[T,x]=d.RESOLUTION.split("x").map(A=>parseInt(A,10));T&&x&&(v={width:T,height:x})}let I=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:I,bandwidth:m,size:v,fps:g})}if(c){let d=(0,cl.default)(c[1].split(",").map(g=>g.split("=")).map(([g,v])=>[g,v.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&i.push({type:"internal",id:p,label:m,language:p,url:h,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 c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?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 c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(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,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category: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(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,G.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Se(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((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:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).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:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&i.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=we(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ul(n).then(l=>{var c;if(!(0,G.isNullable)(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if((0,G.isNullable)(d)||!isFinite(d))try{Rt(n).then(h=>h.text()).then(h=>{var m;let p=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:m[1];if(p){let g=new URL(p,n).toString();ul(g).then(v=>{(0,G.isNullable)(v)||this.maxSeekBackTime$.next(v)})}})}catch(h){}}})}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 c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?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,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category: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 p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,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 d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,ee.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!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,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){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,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?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 c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(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(d=>!(0,se.isInvariantQuality)(d.track.quality)&&(0,se.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,se.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=(0,Oa.default)(this.trackUrls).filter(p=>!(0,se.isInvariantQuality)(p.track.quality)&&(0,se.isHigher)(p.track.quality,e)),h=d.length;h&&(t=d[h-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:c})=>`${l}-${c}`)),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),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=H(R({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var _=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=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>O(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,_.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,_.now)()}else n+=d.byteLength;o=(0,_.now)()}else i+=d.byteLength,n+=d.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(h=>JSON.stringify(h,(p,m)=>{let g=typeof m;return(0,fS.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var 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-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}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(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(r=>r.length>0),(0,f.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=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}`;
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 hn(this.params.fov,this.params.orientation),this.cameraRotationManager=new mn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(jv,this.gl.VERTEX_SHADER),r=this.createShader(Gv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,h=t+i;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Te=require("@vkontakte/videoplayer-shared/es2015"),ll=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(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=(0,Te.now)(),h=n&&this.currentStallsCount>=n,p=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(h||p||f)&&(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()}},Qv=ll;var Fe=require("@vkontakte/videoplayer-shared/es2015"),bn=class{constructor(){this.subscription=new Fe.Subscription;this.pipSize$=new Fe.ValueSubject(void 0);this.videoSize$=new Fe.ValueSubject(void 0);this.elementSize$=new Fe.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Fe.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,Fe.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,Fe.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Fe.map)(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Er=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new j("stopped");this.textTracksManager=new Je;this.droppedFramesManager=new Gs;this.stallsManager=new Qv;this.elementSizeManager=new bn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ji;this.audioTrackSwitchHistory=new ji;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"),R(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"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&R(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"&&R(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"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,U.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=De(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 pn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Ve(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:U.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,U.filter)(c=>!!c.length),(0,U.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,U.map)(c=>c.to.state!=="none"),(0,U.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,U.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,U.filter)(U.isNonNullable),(0,U.once)()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe((0,U.map)(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(vt(this.video,t.isLooped,i)),this.subscription.add(Oe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Xe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,U.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(il(f));let g=[];for(let v of f.representations){let I=Vv(v);g.push(I),this.audioTracksMap.set(I,{stream:f,representation:v})}this.audioStreamsMap.set(f,g)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(al(p));let f=[];for(let g of p.representations){let v=Ov(F(k({},g),{streamId:p.id}));v&&(f.push(v),this.videoTracksMap.set(v,{stream:p,representation:g}))}this.videoStreamsMap.set(p,f)}this.params.output.availableVideoStreams$.next(h);for(let p of d.text)for(let f of p.representations){let g=Bv(p,f);this.textTracksMap.set(g,{stream:p,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:U.ErrorCategory.WTF,message:"Switching representations threw",thrown:c});this.subscription.add((0,U.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,U.fromEvent)(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Wv.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,f]=h,g=[...this.videoTracksMap.keys()].find(I=>{var T;return((T=this.videoTracksMap.get(I))==null?void 0:T.representation.id)===p.id});(0,U.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready")this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(o),f){let I=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,I).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,U.filterChanged)()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(al(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,U.filterChanged)()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(il(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe((0,U.map)(({to:c})=>c==="ready"),(0,U.filterChanged)());this.subscription.add((0,U.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,U.merge)(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=(0,U.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var N,Q,oe,J,W,te,B,ie,H,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),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=yt(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(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===(f==null?void 0:f.id)))!=null?te:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let Y=Hs(n,c,(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=Hs(o,c,(H=this.audioStreamsMap.get(g))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(ne=Y==null?void 0:Y.bitrate)!=null?ne:-1/0)}}let I=Zt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),T=r?I!=null?I:n:n!=null?n:I,x=g&&bb(T,c,($=this.audioStreamsMap.get(g))!=null?$:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),w=(P=this.videoTracksMap.get(T))==null?void 0:P.representation,A=x&&((K=this.audioTracksMap.get(x))==null?void 0:K.representation);if(w&&A)return[w,A];if(w&&!A&&this.audioTracksMap.size===0)return[w,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:U.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ce(this.video),this.tracer.end()}};var La=class extends Er{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ir=require("@vkontakte/videoplayer-shared/es2015");var Ma=class extends Er{constructor(e){super(e),this.liveOffset=new kt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe((0,ir.map)(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add((0,ir.combine)({interval:(0,ir.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,ir.combine)({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ir.map)(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=_v(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Yv=X(_s(),1);var z=require("@vkontakte/videoplayer-shared/es2015");var ct={};var ui=(a,e)=>new z.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Da=class{constructor(e){this.subscription=new z.Subscription;this.videoState=new j("initializing");this.textTracksManager=new Je;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"),R(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,z.assertNever)(e)}break;default:(0,z.assertNever)(t)}};this.video=De(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),Ce(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,Yv.default)(import("hls.js").then(i=>{e||(ct.Hls=i.default,ct.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,z.assertNonNullable)(ct.Hls,"hls.js not loaded"),this.hls=new ct.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,z.assertNonNullable)(ct.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=Ve(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(vt(this.video,e.isLooped,r)),this.subscription.add(Oe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ke(this.video,e.playbackRate,i.playbackRateState$,r)),s(Xe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,z.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ui(this.hls,ct.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:z.ErrorCategory.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(ui(this.hls,ct.Events.MANIFEST_PARSED).pipe((0,z.map)(({levels:l})=>l.reduce((c,d)=>{var T,x;let h=d.name||d.height.toString(10),{width:p,height:f}=d,g=(x=Jt((T=d.attrs.QUALITY)!=null?T:""))!=null?x:(0,z.videoSizeToQuality)({width:p,height:f});if(!g)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:h.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:p,height:f},fps:v};return this.trackLevels.set(h,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(ui(this.hls,ct.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",f=d.lang;c.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ui(this.hls,ct.Events.LEVEL_LOADING).pipe((0,z.map)(({url:l})=>Se(l))),t.hostname$),s(ui(this.hls,ct.Events.FRAG_CHANGED),l=>{var h,p,f,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(Kt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ui(this.hls,ct.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(Kt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if((0,z.isNullable)(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(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 L(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Be(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"),R(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"),R(this.params.desiredState.playbackState,"stopped",!0)}};var zv="X-Playback-Duration",cl=a=>L(void 0,null,function*(){var i;let e=yield ut(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(zv)?parseInt(e.headers.get(zv),10):void 0});var G=require("@vkontakte/videoplayer-shared/es2015");var pl=X(Co(),1);var gn=require("@vkontakte/videoplayer-shared/es2015");var t$=a=>{let e=null;if(a.QUALITY&&(e=Jt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,gn.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},r$=(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:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,pl.default)(l[1].split(",").map(T=>T.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=t$(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let g=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[T,x]=d.RESOLUTION.split("x").map(w=>parseInt(w,10));T&&x&&(v={width:T,height:x})}let I=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:I,bandwidth:f,size:v,fps:g})}if(c){let d=(0,pl.default)(c[1].split(",").map(g=>{let v=g.indexOf("=");return[g.substring(0,v),g.substring(v+1)]}).map(([g,v])=>[g,v.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,f=d.NAME;h&&p&&i.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},i$=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),dl=0,Kv=(i,...s)=>L(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield ut(a,r)).text();dl+=1;try{let{qualityManifests:u,textTracks:l}=r$(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(dl<=t.manifestRetryMaxCount)return yield i$((0,gn.getExponentialDelay)(dl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Kv(a,e,t)}return{qualityManifests:[],textTracks:[]}}),vn=Kv;var Me=require("@vkontakte/videoplayer-shared/es2015");var Sn=class{constructor(e,t,r,i){this.subscription=new Me.Subscription;this.abortControllers={destroy:new ke,nextManifest:null};this.numberFormat=new Intl.NumberFormat("ru-RU",{maximumFractionDigits:2,minimumFractionDigits:2,useGrouping:!0});this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Me.ValueSubject(null);this.getCurrentTime$=new Me.ValueSubject(null);this.error$=new Me.Subject;this.logger=new Me.Logger,this.log=this.logger.createComponentLog("LiveTextManager"),this.params={fetchManifestData:r,sourceUrl:i},this.subscription.add(e.pipe((0,Me.throttle)(1e3)).subscribe(s=>{this.processLiveTime(s)})).add(this.logger.log$.subscribe(s=>{console.debug(`%c${s.component}`,"background:#258b6d;",s.message)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return L(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return L(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return L(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString();this.log({message:"[parseTextTracks]"}),this.log({message:i});let n=yield(yield ut(i,{signal:this.abortControllers.destroy.signal})).text();this.log({message:n});let o=this.parsePlaylist(n,i);return this.log({message:JSON.stringify(o,void 0,2)}),{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
125
+ `),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),h=new Date(r.programDateTime).valueOf();r.segmentStartTime=h-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,Me.isNonNullable)(e)&&this.currentTextTrackData){this.log({message:`[processLiveTime] ${e.toFixed(2)}, ${new Date(e).toISOString()}`});let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r){this.log({message:`[processLiveTime] out of bounds (before) ! ${r-e}`});return}if(e>i){this.log({message:`[processLiveTime] out of bounds (after) !' ${e-i}`});return}let s=i-e;this.log({message:`Current segments time left: ${this.numberFormat.format(s)} ms`}),s<4e3&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([F(k({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return L(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ke;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return L(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Me.ErrorCategory.WTF,thrown:t,message:e})}};var Ca=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new j("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new G.ValueSubject([]);this.liveOffset=new kt;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"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?R(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(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"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,G.assertNever)(t)}};var r;this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:G.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,s)=>vn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Sn(this.params.output.liveTime$,this.video,t,this.params.source.url):this.textTracksManager=new Je,t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:G.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:G.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Se(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new G.ValueSubject((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.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=Ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Oe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),s(Xe(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,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(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,G.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Se(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((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:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).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(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ce(this.video)}prepare(){var o,u,l;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:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[h,p]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(h||""));p&&h&&i.searchParams.set(p,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Ae(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),cl(n).then(c=>{var d;if(!(0,G.isNullable)(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,G.isNullable)(h)||!isFinite(h))&&ut(n).then(p=>p.text()).then(p=>{var g;let f=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:g[1];if(f){let v=new URL(f,n).toString();cl(v).then(I=>{(0,G.isNullable)(I)||this.maxSeekBackTime$.next(I)})}}).catch(()=>{})}})}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(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()}generateLiveUrl(){let e=Ae(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};var ee=require("@vkontakte/videoplayer-shared/es2015");var Oa=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new j("stopped");this.textTracksManager=new Je;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"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?R(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),R(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"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,ee.assertNever)(t)}};this.params=e,this.video=De(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),vn(Ae(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks: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,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:ee.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,ee.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(vt(this.video,t.isLooped,r)),this.subscription.add(Oe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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 p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ee.isNonNullable)(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(v=>v.id===f);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(Se(g.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,ee.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!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),Ce(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,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(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 Jv=X(Ur(),1),Va=X(Ui(),1);var se=require("@vkontakte/videoplayer-shared/es2015");var Ba=class{constructor(e){this.subscription=new se.Subscription;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new Je;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(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"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return(0,se.assertNever)(e)}};this.params=e,this.video=De(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Jv.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Va.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:se.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ve(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,se.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(vt(this.video,t.isLooped,r)),this.subscription.add(Oe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),s(Xe(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(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 c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(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),Ce(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=wa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Se(t))}playIfAllowed(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(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,Va.default)(this.trackUrls).find(d=>!(0,se.isInvariantQuality)(d.track.quality)&&(0,se.isLowerOrEqual)(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&(0,se.isHigherOrEqual)(c.quality,u.quality)&&(t=u),!t){let d=(0,Va.default)(this.trackUrls).filter(p=>!(0,se.isInvariantQuality)(p.track.quality)&&(0,se.isHigher)(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Va.default)(this.trackUrls).map(l=>l.track);t=Zt(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 Xv=["stun:videostun.mycdn.me:80"],a$=1e3,s$=3,hl=()=>null,yn=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=hl;this.externalStopCallback=hl;this.externalErrorCallback=hl;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 L(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 L(this,null,function*(){try{let e={iceServers:[{urls:Xv}]};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 L(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return L(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 L(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 L(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),a$)}normalizeOptions(e={}){let t={stunServerList:Xv,maxRetryNumber:s$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var _a=class{constructor(e){this.videoState=new 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"),R(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"),R(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"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(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=De(e.container,e.tuning),this.liveStreamClient=new yn(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),Ce(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=Ve(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Xe(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(Oe(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,R(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(){Be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(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 Na=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared/es2015");var Ot=require("@vkontakte/videoplayer-shared/es2015"),eS=a=>new Ot.Observable(e=>{let t=new Ot.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Ot.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Ot.map)(({type:l})=>l!==void 0)),n=new Ot.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 tt=require("@vkontakte/videoplayer-shared/es2015");function tS(){return new(window.AudioContext||window.webkitAudioContext)}var rS=require("@vkontakte/videoplayer-shared/es2015");var Fa=class Fa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ke;this.subscriptions=new tt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,tt.filter)(s=>!!s.type),(0,tt.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){rS.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,tt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,tt.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,tt.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 L(this,null,function*(){let{volumeMultiplier:t}=this,r=tS();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(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:Fa.errorId,category:tt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Fa.errorId} exception`,thrown:e})}};Fa.errorId="VolumeMultiplierManager";var li=Fa;var n$={chunkDuration:5e3,maxParallelRequests:5},qa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,warning$:new y.Subject,willSeekEvent$:new y.Subject,soundProhibitedEvent$:new y.Subject,seekedEvent$:new y.Subject,loopedEvent$:new y.Subject,endedEvent$:new y.Subject,firstBytesEvent$:new y.Subject,loadedMetadataEvent$:new y.Subject,firstFrameEvent$:new y.Subject,canplay$:new y.Subject,isLive$:new y.ValueSubject(void 0),isLowLatency$:new y.ValueSubject(!1),canChangePlaybackSpeed$:new y.ValueSubject(!0),liveTime$:new y.ValueSubject(void 0),liveBufferTime$:new y.ValueSubject(void 0),liveLatency$:new y.ValueSubject(void 0),availableTextTracks$:new y.ValueSubject([]),currentTextTrack$:new y.ValueSubject(void 0),hostname$:new y.ValueSubject(void 0),httpConnectionType$:new y.ValueSubject(void 0),httpConnectionReused$:new y.ValueSubject(void 0),inPiP$:new y.ValueSubject(!1),inFullscreen$:new y.ValueSubject(!1),element$:new y.ValueSubject(void 0),elementVisible$:new y.ValueSubject(!0),availableSources$:new y.ValueSubject(void 0),is3DVideo$:new y.ValueSubject(!1),playbackState$:new y.ValueSubject(""),getCurrentTime$:new y.ValueSubject(null)};this.subscription=new y.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=og([...lg(this.params.tuning),...ug(this.params.tuning)],this.params.tuning).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,ml.default)(i,l)),...t.filter(l=>(0,ml.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new Na(s);let n=[..._u(!0),..._u(!1)];this.chromecastFormatsIterator=new Na(n.filter(l=>(0,y.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&li.isSupported()&&(this.volumeMultiplierManager=new li(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new La(F(k({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ma(F(k({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ri||!this.params.tuning.useHlsJs?new Oa(F(k({},n),{source:o})):new Da(F(k({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ca(F(k({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ba(F(k({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Pb(F(k({},n),{source:o,config:F(k({},n$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new _a({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new qi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return F(k({},e),{url:r(e.url)})}return(0,aS.default)((0,iS.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new y.Subscription,t=!1,r=0;return e.add((0,y.merge)(this.providerOutput.error$.pipe((0,y.filter)(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),eS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,y.map)(i=>({id:`ProviderHangup:${i}`,category:y.ErrorCategory.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe((0,y.filter)(({to:s})=>s==="playing"),(0,y.once)()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===y.ErrorCategory.NETWORK,u=i.category===y.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=F(k({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var _=require("@vkontakte/videoplayer-shared/es2015");var o$=5e3,sS="one_video_throughput",nS="one_video_rtt",Vt=window.navigator.connection,oS=()=>{let a=Vt==null?void 0:Vt.downlink;if((0,_.isNonNullable)(a)&&a!==10)return a*1e3},uS=()=>{let a=Vt==null?void 0:Vt.rtt;if((0,_.isNonNullable)(a)&&a!==3e3)return a},lS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},fl=class a{constructor(e){this.subscription=new _.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(sS)||(e.useBrowserEstimation?oS():void 0)||o$,r=(s=(i=a.load(nS))!=null?i:e.useBrowserEstimation?uS():void 0)!=null?s:0;if(this.throughput$=new _.ValueSubject(t),this.rtt$=new _.ValueSubject(r),this.rttAdjustedThroughput$=new _.ValueSubject(lS(t,r,e.rttPenaltyRequestSize)),this.throughput=Ir.getSmoothedValue(t,-1,e),this.rtt=Ir.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=oS();u&&this.throughput.next(u);let l=uS();(0,_.isNonNullable)(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add((0,_.fromEvent)(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{_.safeStorage.set(sS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{_.safeStorage.set(nS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,_.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,_.map)(({throughput:n,rtt:o})=>lS(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=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>L(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,(0,_.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,_.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,_.now)()}else n+=d.byteLength;o=(0,_.now)()}else i+=d.byteLength,n+=d.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}},cS=fl;var Ua=require("@vkontakte/videoplayer-shared/es2015");var dS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ua.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ua.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{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,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1},pS=a=>{var e;return F(k({},(0,Ua.fillWithDefault)(a,dS)),{configName:[...(e=a.configName)!=null?e:[],...dS.configName]})};var m=require("@vkontakte/videoplayer-shared/es2015");var Bt=require("@vkontakte/videoplayer-shared/es2015"),bl=({seekState:a,position$:e})=>(0,Bt.merge)(a.stateChangeEnded$.pipe((0,Bt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Bt.filter)(Bt.isNonNullable)),e.pipe((0,Bt.filter)(()=>a.getState().state==="none")));var hS=require("@vkontakte/videoplayer-shared/es2015"),mS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,hS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Tn=require("@vkontakte/videoplayer-shared/es2015"),fS=(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,Tn.filter)(i=>i.length>0),(0,Tn.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ha=class{constructor(e={configName:[]},t=m.Tracer.createRootTracer(!1)){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new 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 m.ValueSubject("stopped"),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),liveLatency$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,autoplaySoundProhibited$:new m.Subject,firstBytes$:new m.Subject,loadedMetadata$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:cb,getCurrentTime$:new m.ValueSubject(null)};if(this.initLogs(),this.tuning=pS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new cs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new cS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new m.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let g=typeof f;return(0,bS.default)(["number","string","boolean"],g)?f:f===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:m.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=Xl(i,["container"]);return this.tracer.log("initVideo",(0,m.flattenObject)(r)),this.domContainer=mS(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new qa({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&&!Yi()?(this.tracer.log("request play from hidden tab"),(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,m.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,m.filter)(r=>r.length>0),(0,m.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,m.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;(0,m.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,m.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>k({type:"external"},t))),this}selectTextTrack(e){var t;return fS(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",k({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,m.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,m.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(F(k({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:m.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,m.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,m.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,m.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(n=>n.destination),(0,m.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,m.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,m.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,m.isInvariantQuality)(u)?1:(0,m.isInvariantQuality)(l)?-1:(0,m.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,m.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,m.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(n=>n.to),(0,m.filterChanged)(),(0,m.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:bl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(bl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,m.map)(n=>({id:n?`No${n}`:"NoProviders",category:m.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,m.once)(),(0,m.map)(n=>n!=null?n:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:n})=>n==="playing"),(0,m.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,m.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,m.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,m.filterChanged)());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add((0,m.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,m.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(r=>r.length>0),(0,m.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Zt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),lb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>ub(r)),this.providerContainer.current$.subscribe(({type:r})=>Hi("provider",r)),e.duration$.subscribe(r=>Hi("duration",r)),e.availableVideoTracks$.pipe((0,m.filter)(r=>!!r.length),(0,m.once)()).subscribe(r=>Hi("tracks",r)),this.events.fatalError$.subscribe(new Le("fatalError")),this.events.managedError$.subscribe(new Le("managedError")),e.position$.subscribe(new Le("position")),e.currentVideoTrack$.pipe((0,m.map)(r=>r==null?void 0:r.quality)).subscribe(new Le("quality")),this.info.currentBuffer$.subscribe(new Le("buffer")),e.isBuffering$.subscribe(new Le("isBuffering"))].forEach(r=>this.subscription.add(r)),Hi("codecs",ng())}initTracerSubscription(){let e=(0,m.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,m.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,m.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,m.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,m.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,m.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,m.filter)(r=>r>0),(0,m.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,m.filter)(r=>r>0),(0,m.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,m.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,m.filter)(r=>r.end>0),(0,m.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,m.filterChanged)())}).pipe((0,m.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,m.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,m.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,m.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,m.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,m.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,m.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,m.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,m.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,m.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,m.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,m.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>L(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:m.ErrorCategory.DOM,message:String(i)})})});this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,m.flattenObject)({quality:t,availableTracks:(0,m.flattenObject)(e),track:(0,m.flattenObject)(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var It=require("@vkontakte/videoplayer-shared/es2015"),u$=`@vkontakte/videoplayer-core@${Rn}`;