@vkontakte/videoplayer-core 2.0.129-dev.d6909beb.0 → 2.0.129-dev.e6caa27d.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 +33 -33
- package/es2015.esm.js +32 -32
- package/es2018.cjs.js +31 -31
- package/es2018.esm.js +28 -28
- package/esnext.cjs.js +26 -26
- package/esnext.esm.js +24 -24
- package/evergreen.esm.js +23 -23
- package/package.json +2 -2
- package/types/player/Player.d.ts +2 -5
- package/types/player/types.d.ts +0 -11
- package/types/providers/DashProvider/baseDashProvider.d.ts +2 -5
- package/types/providers/DashProvider/lib/buffer.d.ts +1 -1
- package/types/providers/DashProvider/lib/fetcher.d.ts +2 -4
- package/types/providers/DashProvider/lib/player.d.ts +5 -8
- package/types/providers/DashProvider/lib/types.d.ts +1 -5
- package/types/providers/ProviderContainer/index.d.ts +0 -3
- package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +2 -4
- package/types/providers/types.d.ts +2 -5
- package/types/providers/utils/HTMLVideoElement/observable.d.ts +2 -0
- package/types/providers/utils/StallsManager.d.ts +2 -1
- package/types/utils/StatefulIterator/index.d.ts +1 -5
- package/types/utils/smoothedValue/baseSmoothedValue.d.ts +0 -3
- package/types/utils/tuningConfig.d.ts +6 -0
package/es2015.cjs.js
CHANGED
|
@@ -1,73 +1,73 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.129-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.129-dev.e6caa27d.0
|
|
3
|
+
* Tue, 25 Mar 2025 06:51:47 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-129/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var NS=Object.create;var yi=Object.defineProperty,FS=Object.defineProperties,qS=Object.getOwnPropertyDescriptor,US=Object.getOwnPropertyDescriptors,HS=Object.getOwnPropertyNames,os=Object.getOwnPropertySymbols,jS=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty,mc=Object.prototype.propertyIsEnumerable;var QS=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var ft=Math.pow,hc=(a,e,t)=>e in a?yi(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,L=(a,e)=>{for(var t in e||(e={}))Mn.call(e,t)&&hc(a,t,e[t]);if(os)for(var t of os(e))mc.call(e,t)&&hc(a,t,e[t]);return a},N=(a,e)=>FS(a,US(e));var fc=(a,e)=>{var t={};for(var r in a)Mn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&os)for(var r of os(a))e.indexOf(r)<0&&mc.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),GS=(a,e)=>{for(var t in e)yi(a,t,{get:e[t],enumerable:!0})},bc=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of HS(e))!Mn.call(a,i)&&i!==t&&yi(a,i,{get:()=>e[i],enumerable:!(r=qS(e,i))||r.enumerable});return a};var Q=(a,e,t)=>(t=a!=null?NS(jS(a)):{},bc(e||!a||!a.__esModule?yi(t,"default",{value:a,enumerable:!0}):t,a)),WS=a=>bc(yi({},"__esModule",{value:!0}),a);var k=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),us=function(a,e){this[0]=a,this[1]=e},Se=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof us,h=c.done;Promise.resolve(d?o[0]:o).then(m=>d?r(n==="return"?n:"next",o[1]?{done:m.done,value:m.value}:m,u,l):u({value:m,done:h})).catch(m=>r("throw",m,u,l))}catch(m){l(m)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[QS("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ve=b((Dn,gc)=>{"use strict";var Ei=function(a){return a&&a.Math===Math&&a};gc.exports=Ei(typeof globalThis=="object"&&globalThis)||Ei(typeof window=="object"&&window)||Ei(typeof self=="object"&&self)||Ei(typeof global=="object"&&global)||Ei(typeof Dn=="object"&&Dn)||function(){return this}()||Function("return this")()});var Ae=b((k$,vc)=>{"use strict";vc.exports=function(a){try{return!!a()}catch(e){return!0}}});var xi=b((L$,Sc)=>{"use strict";var YS=Ae();Sc.exports=!YS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Vn=b(($$,Ec)=>{"use strict";var zS=xi(),Ic=Function.prototype,yc=Ic.apply,Tc=Ic.call;Ec.exports=typeof Reflect=="object"&&Reflect.apply||(zS?Tc.bind(yc):function(){return Tc.apply(yc,arguments)})});var Ee=b((R$,wc)=>{"use strict";var xc=xi(),Pc=Function.prototype,_n=Pc.call,KS=xc&&Pc.bind.bind(_n,_n);wc.exports=xc?KS:function(a){return function(){return _n.apply(a,arguments)}}});var cr=b((M$,kc)=>{"use strict";var Ac=Ee(),XS=Ac({}.toString),JS=Ac("".slice);kc.exports=function(a){return JS(XS(a),8,-1)}});var On=b((C$,Lc)=>{"use strict";var ZS=cr(),ey=Ee();Lc.exports=function(a){if(ZS(a)==="Function")return ey(a)}});var be=b((D$,$c)=>{"use strict";var Bn=typeof document=="object"&&document.all;$c.exports=typeof Bn=="undefined"&&Bn!==void 0?function(a){return typeof a=="function"||a===Bn}:function(a){return typeof a=="function"}});var Ge=b((V$,Rc)=>{"use strict";var ty=Ae();Rc.exports=!ty(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var We=b((_$,Mc)=>{"use strict";var ry=xi(),ds=Function.prototype.call;Mc.exports=ry?ds.bind(ds):function(){return ds.apply(ds,arguments)}});var Nn=b(Vc=>{"use strict";var Cc={}.propertyIsEnumerable,Dc=Object.getOwnPropertyDescriptor,iy=Dc&&!Cc.call({1:2},1);Vc.f=iy?function(e){var t=Dc(this,e);return!!t&&t.enumerable}:Cc});var Pi=b((B$,_c)=>{"use strict";_c.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Bc=b((N$,Oc)=>{"use strict";var ay=Ee(),sy=Ae(),ny=cr(),Fn=Object,oy=ay("".split);Oc.exports=sy(function(){return!Fn("z").propertyIsEnumerable(0)})?function(a){return ny(a)==="String"?oy(a,""):Fn(a)}:Fn});var _r=b((F$,Nc)=>{"use strict";Nc.exports=function(a){return a==null}});var Qt=b((q$,Fc)=>{"use strict";var uy=_r(),ly=TypeError;Fc.exports=function(a){if(uy(a))throw new ly("Can't call method on "+a);return a}});var dr=b((U$,qc)=>{"use strict";var cy=Bc(),dy=Qt();qc.exports=function(a){return cy(dy(a))}});var Ye=b((H$,Uc)=>{"use strict";var py=be();Uc.exports=function(a){return typeof a=="object"?a!==null:py(a)}});var Or=b((j$,Hc)=>{"use strict";Hc.exports={}});var wt=b((Q$,Qc)=>{"use strict";var qn=Or(),Un=ve(),hy=be(),jc=function(a){return hy(a)?a:void 0};Qc.exports=function(a,e){return arguments.length<2?jc(qn[a])||jc(Un[a]):qn[a]&&qn[a][e]||Un[a]&&Un[a][e]}});var wi=b((G$,Gc)=>{"use strict";var my=Ee();Gc.exports=my({}.isPrototypeOf)});var pr=b((W$,zc)=>{"use strict";var fy=ve(),Wc=fy.navigator,Yc=Wc&&Wc.userAgent;zc.exports=Yc?String(Yc):""});var jn=b((Y$,td)=>{"use strict";var ed=ve(),Hn=pr(),Kc=ed.process,Xc=ed.Deno,Jc=Kc&&Kc.versions||Xc&&Xc.version,Zc=Jc&&Jc.v8,nt,ps;Zc&&(nt=Zc.split("."),ps=nt[0]>0&&nt[0]<4?1:+(nt[0]+nt[1]));!ps&&Hn&&(nt=Hn.match(/Edge\/(\d+)/),(!nt||nt[1]>=74)&&(nt=Hn.match(/Chrome\/(\d+)/),nt&&(ps=+nt[1])));td.exports=ps});var Qn=b((z$,id)=>{"use strict";var rd=jn(),by=Ae(),gy=ve(),vy=gy.String;id.exports=!!Object.getOwnPropertySymbols&&!by(function(){var a=Symbol("symbol detection");return!vy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&rd&&rd<41})});var Gn=b((K$,ad)=>{"use strict";var Sy=Qn();ad.exports=Sy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Wn=b((X$,sd)=>{"use strict";var yy=wt(),Ty=be(),Iy=wi(),Ey=Gn(),xy=Object;sd.exports=Ey?function(a){return typeof a=="symbol"}:function(a){var e=yy("Symbol");return Ty(e)&&Iy(e.prototype,xy(a))}});var Ai=b((J$,nd)=>{"use strict";var Py=String;nd.exports=function(a){try{return Py(a)}catch(e){return"Object"}}});var gt=b((Z$,od)=>{"use strict";var wy=be(),Ay=Ai(),ky=TypeError;od.exports=function(a){if(wy(a))return a;throw new ky(Ay(a)+" is not a function")}});var ki=b((eR,ud)=>{"use strict";var Ly=gt(),$y=_r();ud.exports=function(a,e){var t=a[e];return $y(t)?void 0:Ly(t)}});var cd=b((tR,ld)=>{"use strict";var Yn=We(),zn=be(),Kn=Ye(),Ry=TypeError;ld.exports=function(a,e){var t,r;if(e==="string"&&zn(t=a.toString)&&!Kn(r=Yn(t,a))||zn(t=a.valueOf)&&!Kn(r=Yn(t,a))||e!=="string"&&zn(t=a.toString)&&!Kn(r=Yn(t,a)))return r;throw new Ry("Can't convert object to primitive value")}});var ot=b((rR,dd)=>{"use strict";dd.exports=!0});var md=b((iR,hd)=>{"use strict";var pd=ve(),My=Object.defineProperty;hd.exports=function(a,e){try{My(pd,a,{value:e,configurable:!0,writable:!0})}catch(t){pd[a]=e}return e}});var Li=b((aR,gd)=>{"use strict";var Cy=ot(),Dy=ve(),Vy=md(),fd="__core-js_shared__",bd=gd.exports=Dy[fd]||Vy(fd,{});(bd.versions||(bd.versions=[])).push({version:"3.38.0",mode:Cy?"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 Xn=b((sR,Sd)=>{"use strict";var vd=Li();Sd.exports=function(a,e){return vd[a]||(vd[a]=e||{})}});var Br=b((nR,yd)=>{"use strict";var _y=Qt(),Oy=Object;yd.exports=function(a){return Oy(_y(a))}});var ut=b((oR,Td)=>{"use strict";var By=Ee(),Ny=Br(),Fy=By({}.hasOwnProperty);Td.exports=Object.hasOwn||function(e,t){return Fy(Ny(e),t)}});var Jn=b((uR,Id)=>{"use strict";var qy=Ee(),Uy=0,Hy=Math.random(),jy=qy(1 .toString);Id.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+jy(++Uy+Hy,36)}});var ke=b((lR,xd)=>{"use strict";var Qy=ve(),Gy=Xn(),Ed=ut(),Wy=Jn(),Yy=Qn(),zy=Gn(),Nr=Qy.Symbol,Zn=Gy("wks"),Ky=zy?Nr.for||Nr:Nr&&Nr.withoutSetter||Wy;xd.exports=function(a){return Ed(Zn,a)||(Zn[a]=Yy&&Ed(Nr,a)?Nr[a]:Ky("Symbol."+a)),Zn[a]}});var kd=b((cR,Ad)=>{"use strict";var Xy=We(),Pd=Ye(),wd=Wn(),Jy=ki(),Zy=cd(),eT=ke(),tT=TypeError,rT=eT("toPrimitive");Ad.exports=function(a,e){if(!Pd(a)||wd(a))return a;var t=Jy(a,rT),r;if(t){if(e===void 0&&(e="default"),r=Xy(t,a,e),!Pd(r)||wd(r))return r;throw new tT("Can't convert object to primitive value")}return e===void 0&&(e="number"),Zy(a,e)}});var eo=b((dR,Ld)=>{"use strict";var iT=kd(),aT=Wn();Ld.exports=function(a){var e=iT(a,"string");return aT(e)?e:e+""}});var hs=b((pR,Rd)=>{"use strict";var sT=ve(),$d=Ye(),to=sT.document,nT=$d(to)&&$d(to.createElement);Rd.exports=function(a){return nT?to.createElement(a):{}}});var ro=b((hR,Md)=>{"use strict";var oT=Ge(),uT=Ae(),lT=hs();Md.exports=!oT&&!uT(function(){return Object.defineProperty(lT("div"),"a",{get:function(){return 7}}).a!==7})});var Vd=b(Dd=>{"use strict";var cT=Ge(),dT=We(),pT=Nn(),hT=Pi(),mT=dr(),fT=eo(),bT=ut(),gT=ro(),Cd=Object.getOwnPropertyDescriptor;Dd.f=cT?Cd:function(e,t){if(e=mT(e),t=fT(t),gT)try{return Cd(e,t)}catch(r){}if(bT(e,t))return hT(!dT(pT.f,e,t),e[t])}});var io=b((fR,_d)=>{"use strict";var vT=Ae(),ST=be(),yT=/#|\.prototype\./,$i=function(a,e){var t=IT[TT(a)];return t===xT?!0:t===ET?!1:ST(e)?vT(e):!!e},TT=$i.normalize=function(a){return String(a).replace(yT,".").toLowerCase()},IT=$i.data={},ET=$i.NATIVE="N",xT=$i.POLYFILL="P";_d.exports=$i});var Fr=b((bR,Bd)=>{"use strict";var Od=On(),PT=gt(),wT=xi(),AT=Od(Od.bind);Bd.exports=function(a,e){return PT(a),e===void 0?a:wT?AT(a,e):function(){return a.apply(e,arguments)}}});var ao=b((gR,Nd)=>{"use strict";var kT=Ge(),LT=Ae();Nd.exports=kT&<(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var vt=b((vR,Fd)=>{"use strict";var $T=Ye(),RT=String,MT=TypeError;Fd.exports=function(a){if($T(a))return a;throw new MT(RT(a)+" is not an object")}});var hr=b(Ud=>{"use strict";var CT=Ge(),DT=ro(),VT=ao(),ms=vt(),qd=eo(),_T=TypeError,so=Object.defineProperty,OT=Object.getOwnPropertyDescriptor,no="enumerable",oo="configurable",uo="writable";Ud.f=CT?VT?function(e,t,r){if(ms(e),t=qd(t),ms(r),typeof e=="function"&&t==="prototype"&&"value"in r&&uo in r&&!r[uo]){var i=OT(e,t);i&&i[uo]&&(e[t]=r.value,r={configurable:oo in r?r[oo]:i[oo],enumerable:no in r?r[no]:i[no],writable:!1})}return so(e,t,r)}:so:function(e,t,r){if(ms(e),t=qd(t),ms(r),DT)try{return so(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new _T("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var qr=b((yR,Hd)=>{"use strict";var BT=Ge(),NT=hr(),FT=Pi();Hd.exports=BT?function(a,e,t){return NT.f(a,e,FT(1,t))}:function(a,e,t){return a[e]=t,a}});var ye=b((TR,Qd)=>{"use strict";var Ri=ve(),qT=Vn(),UT=On(),HT=be(),jT=Vd().f,QT=io(),Ur=Or(),GT=Fr(),Hr=qr(),jd=ut();Li();var WT=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return qT(a,this,arguments)};return e.prototype=a.prototype,e};Qd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Ri:i?Ri[t]:Ri[t]&&Ri[t].prototype,o=r?Ur:Ur[t]||Hr(Ur,t,{})[t],u=o.prototype,l,c,d,h,m,f,g,v,T;for(h in e)l=QT(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&jd(n,h),f=o[h],c&&(a.dontCallGetSet?(T=jT(n,h),g=T&&T.value):g=n[h]),m=c&&g?g:e[h],!(!l&&!s&&typeof f==typeof m)&&(a.bind&&c?v=GT(m,Ri):a.wrap&&c?v=WT(m):s&&HT(m)?v=UT(m):v=m,(a.sham||m&&m.sham||f&&f.sham)&&Hr(v,"sham",!0),Hr(o,h,v),s&&(d=t+"Prototype",jd(Ur,d)||Hr(Ur,d,{}),Hr(Ur[d],h,m),a.real&&u&&(l||!u[h])&&Hr(u,h,m)))}});var Wd=b((IR,Gd)=>{"use strict";var YT=Math.ceil,zT=Math.floor;Gd.exports=Math.trunc||function(e){var t=+e;return(t>0?zT:YT)(t)}});var Mi=b((ER,Yd)=>{"use strict";var KT=Wd();Yd.exports=function(a){var e=+a;return e!==e||e===0?0:KT(e)}});var Kd=b((xR,zd)=>{"use strict";var XT=Mi(),JT=Math.max,ZT=Math.min;zd.exports=function(a,e){var t=XT(a);return t<0?JT(t+e,0):ZT(t,e)}});var lo=b((PR,Xd)=>{"use strict";var eI=Mi(),tI=Math.min;Xd.exports=function(a){var e=eI(a);return e>0?tI(e,9007199254740991):0}});var jr=b((wR,Jd)=>{"use strict";var rI=lo();Jd.exports=function(a){return rI(a.length)}});var co=b((AR,ep)=>{"use strict";var iI=dr(),aI=Kd(),sI=jr(),Zd=function(a){return function(e,t,r){var i=iI(e),s=sI(i);if(s===0)return!a&&-1;var n=aI(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}};ep.exports={includes:Zd(!0),indexOf:Zd(!1)}});var Ci=b((kR,tp)=>{"use strict";tp.exports=function(){}});var rp=b(()=>{"use strict";var nI=ye(),oI=co().includes,uI=Ae(),lI=Ci(),cI=uI(function(){return!Array(1).includes()});nI({target:"Array",proto:!0,forced:cI},{includes:function(e){return oI(this,e,arguments.length>1?arguments[1]:void 0)}});lI("includes")});var Gt=b((RR,ip)=>{"use strict";var dI=wt();ip.exports=dI});var sp=b((MR,ap)=>{"use strict";rp();var pI=Gt();ap.exports=pI("Array","includes")});var op=b((CR,np)=>{"use strict";var hI=sp();np.exports=hI});var Be=b((DR,up)=>{"use strict";var mI=op();up.exports=mI});var bs=b((QR,dp)=>{"use strict";var bI=Xn(),gI=Jn(),cp=bI("keys");dp.exports=function(a){return cp[a]||(cp[a]=gI(a))}});var hp=b((GR,pp)=>{"use strict";var vI=Ae();pp.exports=!vI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gs=b((WR,fp)=>{"use strict";var SI=ut(),yI=be(),TI=Br(),II=bs(),EI=hp(),mp=II("IE_PROTO"),po=Object,xI=po.prototype;fp.exports=EI?po.getPrototypeOf:function(a){var e=TI(a);if(SI(e,mp))return e[mp];var t=e.constructor;return yI(t)&&e instanceof t?t.prototype:e instanceof po?xI:null}});var vs=b((YR,bp)=>{"use strict";bp.exports={}});var Sp=b((zR,vp)=>{"use strict";var PI=Ee(),ho=ut(),wI=dr(),AI=co().indexOf,kI=vs(),gp=PI([].push);vp.exports=function(a,e){var t=wI(a),r=0,i=[],s;for(s in t)!ho(kI,s)&&ho(t,s)&&gp(i,s);for(;e.length>r;)ho(t,s=e[r++])&&(~AI(i,s)||gp(i,s));return i}});var mo=b((KR,yp)=>{"use strict";yp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var fo=b((XR,Tp)=>{"use strict";var LI=Sp(),$I=mo();Tp.exports=Object.keys||function(e){return LI(e,$I)}});var bo=b((JR,wp)=>{"use strict";var Ep=Ge(),RI=Ae(),xp=Ee(),MI=gs(),CI=fo(),DI=dr(),VI=Nn().f,Pp=xp(VI),_I=xp([].push),OI=Ep&&RI(function(){var a=Object.create(null);return a[2]=2,!Pp(a,2)}),Ip=function(a){return function(e){for(var t=DI(e),r=CI(t),i=OI&&MI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Ep||(i?u in t:Pp(t,u)))&&_I(o,a?[u,t[u]]:t[u]);return o}};wp.exports={entries:Ip(!0),values:Ip(!1)}});var Ap=b(()=>{"use strict";var BI=ye(),NI=bo().entries;BI({target:"Object",stat:!0},{entries:function(e){return NI(e)}})});var Lp=b((tM,kp)=>{"use strict";Ap();var FI=Or();kp.exports=FI.Object.entries});var Rp=b((rM,$p)=>{"use strict";var qI=Lp();$p.exports=qI});var Qr=b((iM,Mp)=>{"use strict";var UI=Rp();Mp.exports=UI});var mr=b((aM,Cp)=>{"use strict";Cp.exports={}});var _p=b((sM,Vp)=>{"use strict";var HI=ve(),jI=be(),Dp=HI.WeakMap;Vp.exports=jI(Dp)&&/native code/.test(String(Dp))});var yo=b((nM,Np)=>{"use strict";var QI=_p(),Bp=ve(),GI=Ye(),WI=qr(),go=ut(),vo=Li(),YI=bs(),zI=vs(),Op="Object already initialized",So=Bp.TypeError,KI=Bp.WeakMap,Ss,Di,ys,XI=function(a){return ys(a)?Di(a):Ss(a,{})},JI=function(a){return function(e){var t;if(!GI(e)||(t=Di(e)).type!==a)throw new So("Incompatible receiver, "+a+" required");return t}};QI||vo.state?(lt=vo.state||(vo.state=new KI),lt.get=lt.get,lt.has=lt.has,lt.set=lt.set,Ss=function(a,e){if(lt.has(a))throw new So(Op);return e.facade=a,lt.set(a,e),e},Di=function(a){return lt.get(a)||{}},ys=function(a){return lt.has(a)}):(fr=YI("state"),zI[fr]=!0,Ss=function(a,e){if(go(a,fr))throw new So(Op);return e.facade=a,WI(a,fr,e),e},Di=function(a){return go(a,fr)?a[fr]:{}},ys=function(a){return go(a,fr)});var lt,fr;Np.exports={set:Ss,get:Di,has:ys,enforce:XI,getterFor:JI}});var Eo=b((oM,qp)=>{"use strict";var To=Ge(),ZI=ut(),Fp=Function.prototype,eE=To&&Object.getOwnPropertyDescriptor,Io=ZI(Fp,"name"),tE=Io&&function(){}.name==="something",rE=Io&&(!To||To&&eE(Fp,"name").configurable);qp.exports={EXISTS:Io,PROPER:tE,CONFIGURABLE:rE}});var Hp=b(Up=>{"use strict";var iE=Ge(),aE=ao(),sE=hr(),nE=vt(),oE=dr(),uE=fo();Up.f=iE&&!aE?Object.defineProperties:function(e,t){nE(e);for(var r=oE(t),i=uE(t),s=i.length,n=0,o;s>n;)sE.f(e,o=i[n++],r[o]);return e}});var xo=b((lM,jp)=>{"use strict";var lE=wt();jp.exports=lE("document","documentElement")});var ko=b((cM,Xp)=>{"use strict";var cE=vt(),dE=Hp(),Qp=mo(),pE=vs(),hE=xo(),mE=hs(),fE=bs(),Gp=">",Wp="<",wo="prototype",Ao="script",zp=fE("IE_PROTO"),Po=function(){},Kp=function(a){return Wp+Ao+Gp+a+Wp+"/"+Ao+Gp},Yp=function(a){a.write(Kp("")),a.close();var e=a.parentWindow.Object;return a=null,e},bE=function(){var a=mE("iframe"),e="java"+Ao+":",t;return a.style.display="none",hE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Kp("document.F=Object")),t.close(),t.F},Ts,Is=function(){try{Ts=new ActiveXObject("htmlfile")}catch(e){}Is=typeof document!="undefined"?document.domain&&Ts?Yp(Ts):bE():Yp(Ts);for(var a=Qp.length;a--;)delete Is[wo][Qp[a]];return Is()};pE[zp]=!0;Xp.exports=Object.create||function(e,t){var r;return e!==null?(Po[wo]=cE(e),r=new Po,Po[wo]=null,r[zp]=e):r=Is(),t===void 0?r:dE.f(r,t)}});var Gr=b((dM,Jp)=>{"use strict";var gE=qr();Jp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:gE(a,e,t),a}});var Mo=b((pM,th)=>{"use strict";var vE=Ae(),SE=be(),yE=Ye(),TE=ko(),Zp=gs(),IE=Gr(),EE=ke(),xE=ot(),Ro=EE("iterator"),eh=!1,At,Lo,$o;[].keys&&($o=[].keys(),"next"in $o?(Lo=Zp(Zp($o)),Lo!==Object.prototype&&(At=Lo)):eh=!0);var PE=!yE(At)||vE(function(){var a={};return At[Ro].call(a)!==a});PE?At={}:xE&&(At=TE(At));SE(At[Ro])||IE(At,Ro,function(){return this});th.exports={IteratorPrototype:At,BUGGY_SAFARI_ITERATORS:eh}});var Es=b((hM,ih)=>{"use strict";var wE=ke(),AE=wE("toStringTag"),rh={};rh[AE]="z";ih.exports=String(rh)==="[object z]"});var Vi=b((mM,ah)=>{"use strict";var kE=Es(),LE=be(),xs=cr(),$E=ke(),RE=$E("toStringTag"),ME=Object,CE=xs(function(){return arguments}())==="Arguments",DE=function(a,e){try{return a[e]}catch(t){}};ah.exports=kE?xs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=DE(e=ME(a),RE))=="string"?t:CE?xs(e):(r=xs(e))==="Object"&&LE(e.callee)?"Arguments":r}});var nh=b((fM,sh)=>{"use strict";var VE=Es(),_E=Vi();sh.exports=VE?{}.toString:function(){return"[object "+_E(this)+"]"}});var _i=b((bM,uh)=>{"use strict";var OE=Es(),BE=hr().f,NE=qr(),FE=ut(),qE=nh(),UE=ke(),oh=UE("toStringTag");uh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(FE(i,oh)||BE(i,oh,{configurable:!0,value:e}),r&&!OE&&NE(i,"toString",qE))}});var ch=b((gM,lh)=>{"use strict";var HE=Mo().IteratorPrototype,jE=ko(),QE=Pi(),GE=_i(),WE=mr(),YE=function(){return this};lh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=jE(HE,{next:QE(+!r,t)}),GE(a,i,!1,!0),WE[i]=YE,a}});var ph=b((vM,dh)=>{"use strict";var zE=Ee(),KE=gt();dh.exports=function(a,e,t){try{return zE(KE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var mh=b((SM,hh)=>{"use strict";var XE=Ye();hh.exports=function(a){return XE(a)||a===null}});var bh=b((yM,fh)=>{"use strict";var JE=mh(),ZE=String,ex=TypeError;fh.exports=function(a){if(JE(a))return a;throw new ex("Can't set "+ZE(a)+" as a prototype")}});var Co=b((TM,gh)=>{"use strict";var tx=ph(),rx=Ye(),ix=Qt(),ax=bh();gh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=tx(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return ix(i),ax(s),rx(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var kh=b((IM,Ah)=>{"use strict";var sx=ye(),nx=We(),Ps=ot(),Ph=Eo(),ox=be(),ux=ch(),vh=gs(),Sh=Co(),lx=_i(),cx=qr(),Do=Gr(),dx=ke(),yh=mr(),wh=Mo(),px=Ph.PROPER,hx=Ph.CONFIGURABLE,Th=wh.IteratorPrototype,ws=wh.BUGGY_SAFARI_ITERATORS,Oi=dx("iterator"),Ih="keys",Bi="values",Eh="entries",xh=function(){return this};Ah.exports=function(a,e,t,r,i,s,n){ux(t,e,r);var o=function(T){if(T===i&&h)return h;if(!ws&&T&&T in c)return c[T];switch(T){case Ih:return function(){return new t(this,T)};case Bi:return function(){return new t(this,T)};case Eh:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Oi]||c["@@iterator"]||i&&c[i],h=!ws&&d||o(i),m=e==="Array"&&c.entries||d,f,g,v;if(m&&(f=vh(m.call(new a)),f!==Object.prototype&&f.next&&(!Ps&&vh(f)!==Th&&(Sh?Sh(f,Th):ox(f[Oi])||Do(f,Oi,xh)),lx(f,u,!0,!0),Ps&&(yh[u]=xh))),px&&i===Bi&&d&&d.name!==Bi&&(!Ps&&hx?cx(c,"name",Bi):(l=!0,h=function(){return nx(d,this)})),i)if(g={values:o(Bi),keys:s?h:o(Ih),entries:o(Eh)},n)for(v in g)(ws||l||!(v in c))&&Do(c,v,g[v]);else sx({target:e,proto:!0,forced:ws||l},g);return(!Ps||n)&&c[Oi]!==h&&Do(c,Oi,h,{name:i}),yh[e]=h,g}});var $h=b((EM,Lh)=>{"use strict";Lh.exports=function(a,e){return{value:a,done:e}}});var _o=b((xM,Vh)=>{"use strict";var mx=dr(),Vo=Ci(),Rh=mr(),Ch=yo(),fx=hr().f,bx=kh(),As=$h(),gx=ot(),vx=Ge(),Dh="Array Iterator",Sx=Ch.set,yx=Ch.getterFor(Dh);Vh.exports=bx(Array,"Array",function(a,e){Sx(this,{type:Dh,target:mx(a),index:0,kind:e})},function(){var a=yx(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,As(void 0,!0);switch(a.kind){case"keys":return As(t,!1);case"values":return As(e[t],!1)}return As([t,e[t]],!1)},"values");var Mh=Rh.Arguments=Rh.Array;Vo("keys");Vo("values");Vo("entries");if(!gx&&vx&&Mh.name!=="values")try{fx(Mh,"name",{value:"values"})}catch(a){}});var Oh=b((PM,_h)=>{"use strict";var Tx=ke(),Ix=mr(),Ex=Tx("iterator"),xx=Array.prototype;_h.exports=function(a){return a!==void 0&&(Ix.Array===a||xx[Ex]===a)}});var Oo=b((wM,Nh)=>{"use strict";var Px=Vi(),Bh=ki(),wx=_r(),Ax=mr(),kx=ke(),Lx=kx("iterator");Nh.exports=function(a){if(!wx(a))return Bh(a,Lx)||Bh(a,"@@iterator")||Ax[Px(a)]}});var qh=b((AM,Fh)=>{"use strict";var $x=We(),Rx=gt(),Mx=vt(),Cx=Ai(),Dx=Oo(),Vx=TypeError;Fh.exports=function(a,e){var t=arguments.length<2?Dx(a):e;if(Rx(t))return Mx($x(t,a));throw new Vx(Cx(a)+" is not iterable")}});var jh=b((kM,Hh)=>{"use strict";var _x=We(),Uh=vt(),Ox=ki();Hh.exports=function(a,e,t){var r,i;Uh(a);try{if(r=Ox(a,"return"),!r){if(e==="throw")throw t;return t}r=_x(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Uh(r),t}});var Ls=b((LM,Yh)=>{"use strict";var Bx=Fr(),Nx=We(),Fx=vt(),qx=Ai(),Ux=Oh(),Hx=jr(),Qh=wi(),jx=qh(),Qx=Oo(),Gh=jh(),Gx=TypeError,ks=function(a,e){this.stopped=a,this.result=e},Wh=ks.prototype;Yh.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=Bx(e,r),l,c,d,h,m,f,g,v=function(I){return l&&Gh(l,"normal",I),new ks(!0,I)},T=function(I){return i?(Fx(I),o?u(I[0],I[1],v):u(I[0],I[1])):o?u(I,v):u(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Qx(a),!c)throw new Gx(qx(a)+" is not iterable");if(Ux(c)){for(d=0,h=Hx(a);h>d;d++)if(m=T(a[d]),m&&Qh(Wh,m))return m;return new ks(!1)}l=jx(a,c)}for(f=s?a.next:l.next;!(g=Nx(f,l)).done;){try{m=T(g.value)}catch(I){Gh(l,"throw",I)}if(typeof m=="object"&&m&&Qh(Wh,m))return m}return new ks(!1)}});var Kh=b(($M,zh)=>{"use strict";var Wx=Ge(),Yx=hr(),zx=Pi();zh.exports=function(a,e,t){Wx?Yx.f(a,e,zx(0,t)):a[e]=t}});var Xh=b(()=>{"use strict";var Kx=ye(),Xx=Ls(),Jx=Kh();Kx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Xx(e,function(r,i){Jx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Zh=b((CM,Jh)=>{"use strict";_o();Xh();var Zx=Or();Jh.exports=Zx.Object.fromEntries});var tm=b((DM,em)=>{"use strict";em.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 im=b(()=>{"use strict";_o();var eP=tm(),tP=ve(),rP=_i(),rm=mr();for($s in eP)rP(tP[$s],$s),rm[$s]=rm.Array;var $s});var sm=b((OM,am)=>{"use strict";var iP=Zh();im();am.exports=iP});var Bo=b((BM,nm)=>{"use strict";var aP=sm();nm.exports=aP});var om=b(()=>{"use strict"});var No=b((qM,um)=>{"use strict";var Ni=ve(),sP=pr(),nP=cr(),Rs=function(a){return sP.slice(0,a.length)===a};um.exports=function(){return Rs("Bun/")?"BUN":Rs("Cloudflare-Workers")?"CLOUDFLARE":Rs("Deno/")?"DENO":Rs("Node.js/")?"NODE":Ni.Bun&&typeof Bun.version=="string"?"BUN":Ni.Deno&&typeof Deno.version=="object"?"DENO":nP(Ni.process)==="process"?"NODE":Ni.window&&Ni.document?"BROWSER":"REST"}()});var Ms=b((UM,lm)=>{"use strict";var oP=No();lm.exports=oP==="NODE"});var dm=b((HM,cm)=>{"use strict";var uP=hr();cm.exports=function(a,e,t){return uP.f(a,e,t)}});var mm=b((jM,hm)=>{"use strict";var lP=wt(),cP=dm(),dP=ke(),pP=Ge(),pm=dP("species");hm.exports=function(a){var e=lP(a);pP&&e&&!e[pm]&&cP(e,pm,{configurable:!0,get:function(){return this}})}});var bm=b((QM,fm)=>{"use strict";var hP=wi(),mP=TypeError;fm.exports=function(a,e){if(hP(e,a))return a;throw new mP("Incorrect invocation")}});var qo=b((GM,gm)=>{"use strict";var fP=Ee(),bP=be(),Fo=Li(),gP=fP(Function.toString);bP(Fo.inspectSource)||(Fo.inspectSource=function(a){return gP(a)});gm.exports=Fo.inspectSource});var Ho=b((WM,Im)=>{"use strict";var vP=Ee(),SP=Ae(),vm=be(),yP=Vi(),TP=wt(),IP=qo(),Sm=function(){},ym=TP("Reflect","construct"),Uo=/^\s*(?:class|function)\b/,EP=vP(Uo.exec),xP=!Uo.test(Sm),Fi=function(e){if(!vm(e))return!1;try{return ym(Sm,[],e),!0}catch(t){return!1}},Tm=function(e){if(!vm(e))return!1;switch(yP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return xP||!!EP(Uo,IP(e))}catch(t){return!0}};Tm.sham=!0;Im.exports=!ym||SP(function(){var a;return Fi(Fi.call)||!Fi(Object)||!Fi(function(){a=!0})||a})?Tm:Fi});var xm=b((YM,Em)=>{"use strict";var PP=Ho(),wP=Ai(),AP=TypeError;Em.exports=function(a){if(PP(a))return a;throw new AP(wP(a)+" is not a constructor")}});var jo=b((zM,wm)=>{"use strict";var Pm=vt(),kP=xm(),LP=_r(),$P=ke(),RP=$P("species");wm.exports=function(a,e){var t=Pm(a).constructor,r;return t===void 0||LP(r=Pm(t)[RP])?e:kP(r)}});var km=b((KM,Am)=>{"use strict";var MP=Ee();Am.exports=MP([].slice)});var $m=b((XM,Lm)=>{"use strict";var CP=TypeError;Lm.exports=function(a,e){if(a<e)throw new CP("Not enough arguments");return a}});var Qo=b((JM,Rm)=>{"use strict";var DP=pr();Rm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(DP)});var eu=b((ZM,Fm)=>{"use strict";var ze=ve(),VP=Vn(),_P=Fr(),Mm=be(),OP=ut(),Nm=Ae(),Cm=xo(),BP=km(),Dm=hs(),NP=$m(),FP=Qo(),qP=Ms(),Xo=ze.setImmediate,Jo=ze.clearImmediate,UP=ze.process,Go=ze.Dispatch,HP=ze.Function,Vm=ze.MessageChannel,jP=ze.String,Wo=0,qi={},_m="onreadystatechange",Ui,br,Yo,zo;Nm(function(){Ui=ze.location});var Zo=function(a){if(OP(qi,a)){var e=qi[a];delete qi[a],e()}},Ko=function(a){return function(){Zo(a)}},Om=function(a){Zo(a.data)},Bm=function(a){ze.postMessage(jP(a),Ui.protocol+"//"+Ui.host)};(!Xo||!Jo)&&(Xo=function(e){NP(arguments.length,1);var t=Mm(e)?e:HP(e),r=BP(arguments,1);return qi[++Wo]=function(){VP(t,void 0,r)},br(Wo),Wo},Jo=function(e){delete qi[e]},qP?br=function(a){UP.nextTick(Ko(a))}:Go&&Go.now?br=function(a){Go.now(Ko(a))}:Vm&&!FP?(Yo=new Vm,zo=Yo.port2,Yo.port1.onmessage=Om,br=_P(zo.postMessage,zo)):ze.addEventListener&&Mm(ze.postMessage)&&!ze.importScripts&&Ui&&Ui.protocol!=="file:"&&!Nm(Bm)?(br=Bm,ze.addEventListener("message",Om,!1)):_m in Dm("script")?br=function(a){Cm.appendChild(Dm("script"))[_m]=function(){Cm.removeChild(this),Zo(a)}}:br=function(a){setTimeout(Ko(a),0)});Fm.exports={set:Xo,clear:Jo}});var Hm=b((eC,Um)=>{"use strict";var qm=ve(),QP=Ge(),GP=Object.getOwnPropertyDescriptor;Um.exports=function(a){if(!QP)return qm[a];var e=GP(qm,a);return e&&e.value}});var tu=b((tC,Qm)=>{"use strict";var jm=function(){this.head=null,this.tail=null};jm.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}}};Qm.exports=jm});var Wm=b((rC,Gm)=>{"use strict";var WP=pr();Gm.exports=/ipad|iphone|ipod/i.test(WP)&&typeof Pebble!="undefined"});var zm=b((iC,Ym)=>{"use strict";var YP=pr();Ym.exports=/web0s(?!.*chrome)/i.test(YP)});var rf=b((aC,tf)=>{"use strict";var Yr=ve(),zP=Hm(),Km=Fr(),ru=eu().set,KP=tu(),XP=Qo(),JP=Wm(),ZP=zm(),iu=Ms(),Xm=Yr.MutationObserver||Yr.WebKitMutationObserver,Jm=Yr.document,Zm=Yr.process,Cs=Yr.Promise,nu=zP("queueMicrotask"),Wr,au,su,Ds,ef;nu||(Hi=new KP,ji=function(){var a,e;for(iu&&(a=Zm.domain)&&a.exit();e=Hi.get();)try{e()}catch(t){throw Hi.head&&Wr(),t}a&&a.enter()},!XP&&!iu&&!ZP&&Xm&&Jm?(au=!0,su=Jm.createTextNode(""),new Xm(ji).observe(su,{characterData:!0}),Wr=function(){su.data=au=!au}):!JP&&Cs&&Cs.resolve?(Ds=Cs.resolve(void 0),Ds.constructor=Cs,ef=Km(Ds.then,Ds),Wr=function(){ef(ji)}):iu?Wr=function(){Zm.nextTick(ji)}:(ru=Km(ru,Yr),Wr=function(){ru(ji)}),nu=function(a){Hi.head||Wr(),Hi.add(a)});var Hi,ji;tf.exports=nu});var sf=b((sC,af)=>{"use strict";af.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Vs=b((nC,nf)=>{"use strict";nf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var gr=b((oC,of)=>{"use strict";var ew=ve();of.exports=ew.Promise});var zr=b((uC,df)=>{"use strict";var tw=ve(),Qi=gr(),rw=be(),iw=io(),aw=qo(),sw=ke(),uf=No(),nw=ot(),ou=jn(),lf=Qi&&Qi.prototype,ow=sw("species"),uu=!1,cf=rw(tw.PromiseRejectionEvent),uw=iw("Promise",function(){var a=aw(Qi),e=a!==String(Qi);if(!e&&ou===66||nw&&!(lf.catch&&lf.finally))return!0;if(!ou||ou<51||!/native code/.test(a)){var t=new Qi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[ow]=r,uu=t.then(function(){})instanceof r,!uu)return!0}return!e&&(uf==="BROWSER"||uf==="DENO")&&!cf});df.exports={CONSTRUCTOR:uw,REJECTION_EVENT:cf,SUBCLASSING:uu}});var Kr=b((lC,hf)=>{"use strict";var pf=gt(),lw=TypeError,cw=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new lw("Bad Promise constructor");e=r,t=i}),this.resolve=pf(e),this.reject=pf(t)};hf.exports.f=function(a){return new cw(a)}});var Mf=b(()=>{"use strict";var dw=ye(),pw=ot(),Ns=Ms(),Wt=ve(),ei=We(),mf=Gr(),ff=Co(),hw=_i(),mw=mm(),fw=gt(),Bs=be(),bw=Ye(),gw=bm(),vw=jo(),yf=eu().set,hu=rf(),Sw=sf(),yw=Vs(),Tw=tu(),Tf=yo(),Fs=gr(),mu=zr(),If=Kr(),qs="Promise",Ef=mu.CONSTRUCTOR,Iw=mu.REJECTION_EVENT,Ew=mu.SUBCLASSING,lu=Tf.getterFor(qs),xw=Tf.set,Xr=Fs&&Fs.prototype,vr=Fs,_s=Xr,xf=Wt.TypeError,cu=Wt.document,fu=Wt.process,du=If.f,Pw=du,ww=!!(cu&&cu.createEvent&&Wt.dispatchEvent),Pf="unhandledrejection",Aw="rejectionhandled",bf=0,wf=1,kw=2,bu=1,Af=2,Os,gf,Lw,vf,kf=function(a){var e;return bw(a)&&Bs(e=a.then)?e:!1},Lf=function(a,e){var t=e.value,r=e.state===wf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Af&&Rw(e),e.rejection=bu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new xf("Promise-chain cycle")):(l=kf(u))?ei(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},$f=function(a,e){a.notified||(a.notified=!0,hu(function(){for(var t=a.reactions,r;r=t.get();)Lf(r,a);a.notified=!1,e&&!a.rejection&&$w(a)}))},Rf=function(a,e,t){var r,i;ww?(r=cu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Wt.dispatchEvent(r)):r={promise:e,reason:t},!Iw&&(i=Wt["on"+a])?i(r):a===Pf&&Sw("Unhandled promise rejection",t)},$w=function(a){ei(yf,Wt,function(){var e=a.facade,t=a.value,r=Sf(a),i;if(r&&(i=yw(function(){Ns?fu.emit("unhandledRejection",t,e):Rf(Pf,e,t)}),a.rejection=Ns||Sf(a)?Af:bu,i.error))throw i.value})},Sf=function(a){return a.rejection!==bu&&!a.parent},Rw=function(a){ei(yf,Wt,function(){var e=a.facade;Ns?fu.emit("rejectionHandled",e):Rf(Aw,e,a.value)})},Jr=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=kw,$f(a,!0))},pu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new xf("Promise can't be resolved itself");var r=kf(e);r?hu(function(){var i={done:!1};try{ei(r,e,Jr(pu,i,a),Jr(Zr,i,a))}catch(s){Zr(i,s,a)}}):(a.value=e,a.state=wf,$f(a,!1))}catch(i){Zr({done:!1},i,a)}}};if(Ef&&(vr=function(e){gw(this,_s),fw(e),ei(Os,this);var t=lu(this);try{e(Jr(pu,t),Jr(Zr,t))}catch(r){Zr(t,r)}},_s=vr.prototype,Os=function(e){xw(this,{type:qs,done:!1,notified:!1,parent:!1,reactions:new Tw,rejection:!1,state:bf,value:void 0})},Os.prototype=mf(_s,"then",function(e,t){var r=lu(this),i=du(vw(this,vr));return r.parent=!0,i.ok=Bs(e)?e:!0,i.fail=Bs(t)&&t,i.domain=Ns?fu.domain:void 0,r.state===bf?r.reactions.add(i):hu(function(){Lf(i,r)}),i.promise}),gf=function(){var a=new Os,e=lu(a);this.promise=a,this.resolve=Jr(pu,e),this.reject=Jr(Zr,e)},If.f=du=function(a){return a===vr||a===Lw?new gf(a):Pw(a)},!pw&&Bs(Fs)&&Xr!==Object.prototype)){vf=Xr.then,Ew||mf(Xr,"then",function(e,t){var r=this;return new vr(function(i,s){ei(vf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Xr.constructor}catch(a){}ff&&ff(Xr,_s)}dw({global:!0,constructor:!0,wrap:!0,forced:Ef},{Promise:vr});hw(vr,qs,!1,!0);mw(qs)});var Of=b((pC,_f)=>{"use strict";var Mw=ke(),Df=Mw("iterator"),Vf=!1;try{Cf=0,gu={next:function(){return{done:!!Cf++}},return:function(){Vf=!0}},gu[Df]=function(){return this},Array.from(gu,function(){throw 2})}catch(a){}var Cf,gu;_f.exports=function(a,e){try{if(!e&&!Vf)return!1}catch(i){return!1}var t=!1;try{var r={};r[Df]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var vu=b((hC,Bf)=>{"use strict";var Cw=gr(),Dw=Of(),Vw=zr().CONSTRUCTOR;Bf.exports=Vw||!Dw(function(a){Cw.all(a).then(void 0,function(){})})});var Nf=b(()=>{"use strict";var _w=ye(),Ow=We(),Bw=gt(),Nw=Kr(),Fw=Vs(),qw=Ls(),Uw=vu();_w({target:"Promise",stat:!0,forced:Uw},{all:function(e){var t=this,r=Nw.f(t),i=r.resolve,s=r.reject,n=Fw(function(){var o=Bw(t.resolve),u=[],l=0,c=1;qw(e,function(d){var h=l++,m=!1;c++,Ow(o,t,d).then(function(f){m||(m=!0,u[h]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var qf=b(()=>{"use strict";var Hw=ye(),jw=ot(),Qw=zr().CONSTRUCTOR,yu=gr(),Gw=wt(),Ww=be(),Yw=Gr(),Ff=yu&&yu.prototype;Hw({target:"Promise",proto:!0,forced:Qw,real:!0},{catch:function(a){return this.then(void 0,a)}});!jw&&Ww(yu)&&(Su=Gw("Promise").prototype.catch,Ff.catch!==Su&&Yw(Ff,"catch",Su,{unsafe:!0}));var Su});var Uf=b(()=>{"use strict";var zw=ye(),Kw=We(),Xw=gt(),Jw=Kr(),Zw=Vs(),eA=Ls(),tA=vu();zw({target:"Promise",stat:!0,forced:tA},{race:function(e){var t=this,r=Jw.f(t),i=r.reject,s=Zw(function(){var n=Xw(t.resolve);eA(e,function(o){Kw(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Hf=b(()=>{"use strict";var rA=ye(),iA=Kr(),aA=zr().CONSTRUCTOR;rA({target:"Promise",stat:!0,forced:aA},{reject:function(e){var t=iA.f(this),r=t.reject;return r(e),t.promise}})});var Tu=b((IC,jf)=>{"use strict";var sA=vt(),nA=Ye(),oA=Kr();jf.exports=function(a,e){if(sA(a),nA(e)&&e.constructor===a)return e;var t=oA.f(a),r=t.resolve;return r(e),t.promise}});var Wf=b(()=>{"use strict";var uA=ye(),lA=wt(),Qf=ot(),cA=gr(),Gf=zr().CONSTRUCTOR,dA=Tu(),pA=lA("Promise"),hA=Qf&&!Gf;uA({target:"Promise",stat:!0,forced:Qf||Gf},{resolve:function(e){return dA(hA&&this===pA?cA:this,e)}})});var Yf=b(()=>{"use strict";Mf();Nf();qf();Uf();Hf();Wf()});var Jf=b(()=>{"use strict";var mA=ye(),fA=ot(),Us=gr(),bA=Ae(),Kf=wt(),Xf=be(),gA=jo(),zf=Tu(),vA=Gr(),Eu=Us&&Us.prototype,SA=!!Us&&bA(function(){Eu.finally.call({then:function(){}},function(){})});mA({target:"Promise",proto:!0,real:!0,forced:SA},{finally:function(a){var e=gA(this,Kf("Promise")),t=Xf(a);return this.then(t?function(r){return zf(e,a()).then(function(){return r})}:a,t?function(r){return zf(e,a()).then(function(){throw r})}:a)}});!fA&&Xf(Us)&&(Iu=Kf("Promise").prototype.finally,Eu.finally!==Iu&&vA(Eu,"finally",Iu,{unsafe:!0}));var Iu});var eb=b((LC,Zf)=>{"use strict";om();Yf();Jf();var yA=Gt();Zf.exports=yA("Promise","finally")});var rb=b(($C,tb)=>{"use strict";var TA=eb();tb.exports=TA});var Hs=b((RC,ib)=>{"use strict";var IA=rb();ib.exports=IA});var cb=b(()=>{"use strict";var AA=ye(),kA=bo().values;AA({target:"Object",stat:!0},{values:function(e){return kA(e)}})});var pb=b((uD,db)=>{"use strict";cb();var LA=Or();db.exports=LA.Object.values});var mb=b((lD,hb)=>{"use strict";var $A=pb();hb.exports=$A});var ti=b((cD,fb)=>{"use strict";var RA=mb();fb.exports=RA});var Ab=b(()=>{"use strict";var qA=ye(),UA=Br(),HA=jr(),jA=Mi(),QA=Ci();qA({target:"Array",proto:!0},{at:function(e){var t=UA(this),r=HA(t),i=jA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});QA("at")});var Lb=b((b0,kb)=>{"use strict";Ab();var GA=Gt();kb.exports=GA("Array","at")});var Rb=b((g0,$b)=>{"use strict";var WA=Lb();$b.exports=WA});var yr=b((v0,Mb)=>{"use strict";var YA=Rb();Mb.exports=YA});var Hu=b((zV,eg)=>{"use strict";var nk=cr();eg.exports=Array.isArray||function(e){return nk(e)==="Array"}});var rg=b((KV,tg)=>{"use strict";var ok=TypeError,uk=9007199254740991;tg.exports=function(a){if(a>uk)throw ok("Maximum allowed index exceeded");return a}});var sg=b((XV,ag)=>{"use strict";var lk=Hu(),ck=jr(),dk=rg(),pk=Fr(),ig=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?pk(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&lk(d)?(h=ck(d),u=ig(a,e,d,h,u,s-1)-1):(dk(u+1),a[u]=d),u++),l++;return u};ag.exports=ig});var lg=b((JV,ug)=>{"use strict";var ng=Hu(),hk=Ho(),mk=Ye(),fk=ke(),bk=fk("species"),og=Array;ug.exports=function(a){var e;return ng(a)&&(e=a.constructor,hk(e)&&(e===og||ng(e.prototype))?e=void 0:mk(e)&&(e=e[bk],e===null&&(e=void 0))),e===void 0?og:e}});var dg=b((ZV,cg)=>{"use strict";var gk=lg();cg.exports=function(a,e){return new(gk(a))(e===0?0:e)}});var pg=b(()=>{"use strict";var vk=ye(),Sk=sg(),yk=gt(),Tk=Br(),Ik=jr(),Ek=dg();vk({target:"Array",proto:!0},{flatMap:function(e){var t=Tk(this),r=Ik(t),i;return yk(e),i=Ek(t,0),i.length=Sk(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var hg=b(()=>{"use strict";var xk=Ci();xk("flatMap")});var fg=b((a_,mg)=>{"use strict";pg();hg();var Pk=Gt();mg.exports=Pk("Array","flatMap")});var gg=b((s_,bg)=>{"use strict";var wk=fg();bg.exports=wk});var ju=b((n_,vg)=>{"use strict";var Ak=gg();vg.exports=Ak});var ia=b((o_,Sg)=>{"use strict";var kk=Vi(),Lk=String;Sg.exports=function(a){if(kk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Lk(a)}});var Qu=b((u_,yg)=>{"use strict";yg.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 Eg=b((l_,Ig)=>{"use strict";var $k=Ee(),Rk=Qt(),Mk=ia(),Wu=Qu(),Tg=$k("".replace),Ck=RegExp("^["+Wu+"]+"),Dk=RegExp("(^|[^"+Wu+"])["+Wu+"]+$"),Gu=function(a){return function(e){var t=Mk(Rk(e));return a&1&&(t=Tg(t,Ck,"")),a&2&&(t=Tg(t,Dk,"$1")),t}};Ig.exports={start:Gu(1),end:Gu(2),trim:Gu(3)}});var Ag=b((c_,wg)=>{"use strict";var Vk=Eo().PROPER,_k=Ae(),xg=Qu(),Pg="\u200B\x85\u180E";wg.exports=function(a){return _k(function(){return!!xg[a]()||Pg[a]()!==Pg||Vk&&xg[a].name!==a})}});var Yu=b((d_,kg)=>{"use strict";var Ok=Eg().start,Bk=Ag();kg.exports=Bk("trimStart")?function(){return Ok(this)}:"".trimStart});var $g=b(()=>{"use strict";var Nk=ye(),Lg=Yu();Nk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Lg},{trimLeft:Lg})});var Mg=b(()=>{"use strict";$g();var Fk=ye(),Rg=Yu();Fk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Rg},{trimStart:Rg})});var Dg=b((b_,Cg)=>{"use strict";Mg();var qk=Gt();Cg.exports=qk("String","trimLeft")});var _g=b((g_,Vg)=>{"use strict";var Uk=Dg();Vg.exports=Uk});var Bg=b((v_,Og)=>{"use strict";var Hk=_g();Og.exports=Hk});var Jg=b(()=>{"use strict"});var Zg=b(()=>{"use strict"});var tv=b((XB,ev)=>{"use strict";var lL=Ye(),cL=cr(),dL=ke(),pL=dL("match");ev.exports=function(a){var e;return lL(a)&&((e=a[pL])!==void 0?!!e:cL(a)==="RegExp")}});var iv=b((JB,rv)=>{"use strict";var hL=vt();rv.exports=function(){var a=hL(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 nv=b((ZB,sv)=>{"use strict";var mL=We(),fL=ut(),bL=wi(),gL=iv(),av=RegExp.prototype;sv.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in av)&&!fL(a,"flags")&&bL(av,a)?mL(gL,a):e}});var uv=b((eN,ov)=>{"use strict";var tl=Ee(),vL=Br(),SL=Math.floor,Zu=tl("".charAt),yL=tl("".replace),el=tl("".slice),TL=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,IL=/\$([$&'`]|\d{1,2})/g;ov.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=IL;return i!==void 0&&(i=vL(i),u=TL),yL(s,u,function(l,c){var d;switch(Zu(c,0)){case"$":return"$";case"&":return a;case"`":return el(e,0,t);case"'":return el(e,n);case"<":d=i[el(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var m=SL(h/10);return m===0?l:m<=o?r[m-1]===void 0?Zu(c,1):r[m-1]+Zu(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var dv=b(()=>{"use strict";var EL=ye(),xL=We(),il=Ee(),lv=Qt(),PL=be(),wL=_r(),AL=tv(),oi=ia(),kL=ki(),LL=nv(),$L=uv(),RL=ke(),ML=ot(),CL=RL("replace"),DL=TypeError,rl=il("".indexOf),VL=il("".replace),cv=il("".slice),_L=Math.max;EL({target:"String",proto:!0},{replaceAll:function(e,t){var r=lv(this),i,s,n,o,u,l,c,d,h,m,f=0,g="";if(!wL(e)){if(i=AL(e),i&&(s=oi(lv(LL(e))),!~rl(s,"g")))throw new DL("`.replaceAll` does not allow non-global regexes");if(n=kL(e,CL),n)return xL(n,e,r,t);if(ML&&i)return VL(oi(r),e,t)}for(o=oi(r),u=oi(e),l=PL(t),l||(t=oi(t)),c=u.length,d=_L(1,c),h=rl(o,u);h!==-1;)m=l?oi(t(u,h,o)):$L(u,o,h,[],void 0,t),g+=cv(o,f,h)+m,f=h+c,h=h+d>o.length?-1:rl(o,u,h+d);return f<o.length&&(g+=cv(o,f)),g}})});var hv=b((iN,pv)=>{"use strict";Jg();Zg();dv();var OL=Gt();pv.exports=OL("String","replaceAll")});var fv=b((aN,mv)=>{"use strict";var BL=hv();mv.exports=BL});var gv=b((sN,bv)=>{"use strict";var NL=fv();bv.exports=NL});var Sv=b((nN,vv)=>{"use strict";var FL=Mi(),qL=ia(),UL=Qt(),HL=RangeError;vv.exports=function(e){var t=qL(UL(this)),r="",i=FL(e);if(i<0||i===1/0)throw new HL("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var xv=b((oN,Ev)=>{"use strict";var Iv=Ee(),jL=lo(),yv=ia(),QL=Sv(),GL=Qt(),WL=Iv(QL),YL=Iv("".slice),zL=Math.ceil,Tv=function(a){return function(e,t,r){var i=yv(GL(e)),s=jL(t),n=i.length,o=r===void 0?" ":yv(r),u,l;return s<=n||o===""?i:(u=s-n,l=WL(o,zL(u/o.length)),l.length>u&&(l=YL(l,0,u)),a?i+l:l+i)}};Ev.exports={start:Tv(!1),end:Tv(!0)}});var wv=b((uN,Pv)=>{"use strict";var KL=pr();Pv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(KL)});var Av=b(()=>{"use strict";var XL=ye(),JL=xv().start,ZL=wv();XL({target:"String",proto:!0,forced:ZL},{padStart:function(e){return JL(this,e,arguments.length>1?arguments[1]:void 0)}})});var Lv=b((dN,kv)=>{"use strict";Av();var e$=Gt();kv.exports=e$("String","padStart")});var Rv=b((pN,$v)=>{"use strict";var t$=Lv();$v.exports=t$});var Cv=b((hN,Mv)=>{"use strict";var r$=Rv();Mv.exports=r$});var x$={};GS(x$,{ChromecastState:()=>Ti,HttpConnectionType:()=>ls,Observable:()=>xt.Observable,PlaybackState:()=>Oe,Player:()=>Wa,PredefinedQualityLimits:()=>Ii,SDK_VERSION:()=>E$,Subject:()=>xt.Subject,Subscription:()=>xt.Subscription,Surface:()=>cs,VERSION:()=>Cn,ValueSubject:()=>xt.ValueSubject,VideoFormat:()=>bt,VideoQuality:()=>xt.VideoQuality,clientChecker:()=>z,isMobile:()=>ri});module.exports=WS(x$);var Cn="2.0.129-dev.d6909beb.0";var Oe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Oe||{}),bt=(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))(bt||{});var Ti=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Ti||{}),ls=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ls||{});var cs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(cs||{}),Ii=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(Ii||{});var RS=Q(Be(),1);var G=require("@vkontakte/videoplayer-shared/es2015");var lp=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 fs=class{constructor(e){this.connection$=new G.ValueSubject(void 0);this.castState$=new G.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new G.Subject;this.realCastState$=new G.ValueSubject("NOT_AVAILABLE");this.subscription=new G.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,G.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||lp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:G.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,G.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,G.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,G.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,G.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,G.assertNever)(i.sessionState)}})).add((0,G.merge)((0,G.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,G.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,G.map)(i=>i.castState)),(0,G.observableFrom)([r.getCastState()])).pipe((0,G.filterChanged)(),(0,G.map)(fI),(0,G.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,G.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,G.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,G.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,G.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:G.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},fI=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,G.assertNever)(a)}};var wl=Q(Be(),1),vS=Q(Qr(),1),SS=Q(Bo(),1);var ob=Q(Hs(),1);var xu=require("@vkontakte/videoplayer-shared/es2015");var Le=(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,xu.assertNever)(t)}return a},js=(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,xu.assertNever)(e)}};var $=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var St=require("@vkontakte/videoplayer-shared/es2015"),Y=class{constructor(e){this.transitionStarted$=new St.Subject;this.transitionEnded$=new St.Subject;this.transitionUpdated$=new St.Subject;this.forceChanged$=new St.Subject;this.stateChangeStarted$=(0,St.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,St.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,St.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 ab=require("@vkontakte/videoplayer-shared/es2015"),sb=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,ab.assertNever)(a)}};var M=require("@vkontakte/videoplayer-shared/es2015");var EA=5,xA=5,PA=500,nb=7e3,Gi=class{constructor(e){this.subscription=new M.Subscription;this.loadMediaTimeoutSubscription=new M.Subscription;this.videoState=new Y("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(sb(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)(PA)).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)>EA)&&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<xA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),$(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"),$(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),$(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"),$(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"),$(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"&&$(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=Le(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)(nb).subscribe(()=>s(`timeout(${nb})`)))});(0,ob.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 qu=Q(Be(),1);var ku=require("@vkontakte/videoplayer-shared/es2015");var ub=require("@vkontakte/videoplayer-shared/es2015"),lb=a=>{try{a.pause(),a.playbackRate=0,(0,ub.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Qs=require("@vkontakte/videoplayer-shared/es2015"),Pu=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)}},wu=window.WeakMap?new WeakMap:new Pu,Au=window.WeakMap?new WeakMap:new Map,wA=(a,e=20)=>{let t=0;return(0,Qs.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ne=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?(0,ku.clearVideoElement)(r):(r=document.createElement("video"),a.appendChild(r)),wu.set(r,i);let s=new Qs.Subscription;return s.add(wA(r,e)),Au.set(r,s),r.setAttribute("crossorigin","anonymous"),r.setAttribute("playsinline","playsinline"),t&&r.setAttribute("x-yandex-pip","false"),r.controls=!1,r.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),r},Fe=a=>{let e=Au.get(a);e==null||e.unsubscribe(),Au.delete(a);let t=wu.get(a);wu.delete(a),t?(0,ku.clearVideoElement)(a):lb(a)};var Lu=Q(ti(),1),C=require("@vkontakte/videoplayer-shared/es2015");var Yt=require("@vkontakte/videoplayer-shared/es2015"),Gs=(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},yt=(a,e,t)=>Gs(e,()=>a.loop,r=>{(0,Yt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),qe=(a,e,t,r)=>Gs(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)=>Gs(e,()=>a.playbackRate,i=>{(0,Yt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),zt=Gs;var MA=a=>["__",a.language,a.label].join("|"),CA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},$u=class a{constructor(e){this.available$=new C.Subject;this.current$=new C.ValueSubject(void 0);this.error$=new C.Subject;this.subscription=new C.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:C.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,Lu.default)(this.internalTracks),s=>{(0,C.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,C.isNonNullable)(s)&&(0,C.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,C.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(zt(t.externalTextTracks,()=>(0,Lu.default)(this.externalTracks),s=>{(0,C.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,C.isNonNullable)(s)&&(0,C.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,C.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,C.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,C.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,C.merge)((0,C.fromEvent)(e,"addtrack"),(0,C.fromEvent)(e,"removetrack"),(0,C.observableFrom)(["init"])).pipe((0,C.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,C.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,C.merge)((0,C.fromEvent)(e,"change"),(0,C.observableFrom)(["init"])).pipe((0,C.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,C.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,C.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,C.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,m;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),(m=o.target)==null||m.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,C.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,C.isNonNullable)(t.align)&&(i.align=t.align),(0,C.isNonNullable)(t.position)&&(i.position=t.position),(0,C.isNonNullable)(t.size)&&(i.size=t.size),(0,C.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,C.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:MA(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,C.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,C.isNullable)(e)||!CA(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,C.assertNonNullable)(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,C.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)}},et=$u;var Sr=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 bb=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},Ru=a=>{let e=bb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},gb=a=>{let e=bb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var D=require("@vkontakte/videoplayer-shared/es2015");var DA=3,vb=(a,e,t=DA)=>{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 Ws=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,r=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,i=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||r||n||u||l||i||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let r=t[1],i=parseInt(r,10);if(isNaN(i))return;this._safariVersion=i}catch(e){console.error(e)}}};var Sb=Q(Be(),1);var ri=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Ys=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Sb.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=ri()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return k(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,r=/iphone/i.test(e)?"iPhone":void 0,i=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||r||i||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let r=t[1].replace(/_/g,".");if(!r)return;let i=parseFloat(r);if(isNaN(i))return;this._iosVersion=i}catch(e){console.error(e)}}};var zs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(r){console.error(r)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(r){console.error(r)}}};var ct=()=>window.ManagedMediaSource||window.MediaSource,Ks=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},yb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Tb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var VA=document.createElement("video"),_A='video/mp4; codecs="avc1.42000a,mp4a.40.2"',OA='video/mp4; codecs="hev1.1.6.L93.B0"',Ib='video/webm; codecs="vp09.00.10.08"',Eb='video/webm; codecs="av01.0.00M.08"',BA='audio/mp4; codecs="mp4a.40.2"',NA='audio/webm; codecs="opus"',xb,FA=()=>k(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(N(L({},a),{video:N(L({},a.video),{contentType:Eb})})),window.navigator.mediaCapabilities.decodingInfo(N(L({},a),{video:N(L({},a.video),{contentType:Ib})}))]);xb={DASH_WEBM_AV1:e,DASH_WEBM:t}});FA().catch(a=>{console.log(VA),console.error(a)});var Xs=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return xb}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,r,i,s,n,o,u,l,c,d,h,m,f,g,v,T,I,x,w;this._video=document.createElement("video");try{this._protocols={mms:Ks(),mse:yb(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(i=(r=this._video).canPlayType)!=null&&i.call(r,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let A=!!((c=(l=ct())==null?void 0:l.isTypeSupported)!=null&&c.call(l,_A)),_=!!((h=(d=ct())==null?void 0:d.isTypeSupported)!=null&&h.call(d,OA)),q=!!((f=(m=ct())==null?void 0:m.isTypeSupported)!=null&&f.call(m,BA));this._codecs={h264:A,h265:_,vp9:!!((v=(g=ct())==null?void 0:g.isTypeSupported)!=null&&v.call(g,Ib)),av1:!!((I=(T=ct())==null?void 0:T.isTypeSupported)!=null&&I.call(T,Eb)),aac:q,opus:!!((w=(x=ct())==null?void 0:x.isTypeSupported)!=null&&w.call(x,NA)),mpeg:(A||_)&&q},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(A){console.error(A)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Pb="audio/mpeg",Js=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,r,i;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Pb))},this._codecs={mp3:!!((i=(r=ct())==null?void 0:r.isTypeSupported)!=null&&i.call(r,Pb))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var wb=require("@vkontakte/videoplayer-shared/es2015");var Mu=class{constructor(){this.isInited$=new wb.ValueSubject(!1);this._displayChecker=new zs,this._deviceChecker=new Ys(this._displayChecker),this._browserChecker=new Ws,this._videoChecker=new Xs(this._deviceChecker,this._browserChecker),this._audioChecker=new Js,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return k(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},z=new Mu;var Ue=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)(()=>vb(a.buffered,a.currentTime))),s=z.browser.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 w;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:(w=a.error)!=null?w: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 m=e("pause").pipe((0,D.filter)(()=>!a.error&&h!==a.duration)),f=(0,D.fromEvent)(a,"enterpictureinpicture"),g=(0,D.fromEvent)(a,"leavepictureinpicture"),v=new D.ValueSubject(gb(a));f.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let T=new D.ValueSubject(Ru(a));return(0,D.fromEvent)(a,"fullscreenchange").pipe((0,D.map)(()=>Ru(a))).subscribe(T),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,D.fromEvent)(a,"durationchange").pipe((0,D.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:v,inFullscreen$:T,enterPip$:f,leavePip$:g}};var Lt=require("@vkontakte/videoplayer-shared/es2015"),Kt=a=>{switch(a){case"mobile":return Lt.VideoQuality.Q_144P;case"lowest":return Lt.VideoQuality.Q_240P;case"low":return Lt.VideoQuality.Q_360P;case"sd":case"medium":return Lt.VideoQuality.Q_480P;case"hd":case"high":return Lt.VideoQuality.Q_720P;case"fullhd":case"full":return Lt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Lt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Lt.VideoQuality.Q_2160P}};var Xt=Q(yr(),1),Bb=Q(Be(),1),Zs=Q(Qr(),1),U=require("@vkontakte/videoplayer-shared/es2015");var Cu=!1,$t={},Cb=a=>{Cu=a},Db=()=>{$t={}},Vb=a=>{a($t)},Wi=(a,e)=>{var t;Cu&&($t.meta=(t=$t.meta)!=null?t:{},$t.meta[a]=e)},De=class{constructor(e){this.name=e}next(e){var r,i;if(!Cu)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 Te=require("@vkontakte/videoplayer-shared/es2015");function Du({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Vu({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&Du({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Yi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return(0,Te.isNullable)(a)||(0,Te.isNonNullable)(a.min)&&(0,Te.isNonNullable)(a.max)&&(0,Te.isLower)(a.max,a.min)||(0,Te.isNonNullable)(a.min)&&e&&(0,Te.isHigher)(a.min,e)||(0,Te.isNonNullable)(a.max)&&t&&(0,Te.isLower)(a.max,t)}function _b({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Yi({limits:{max:a!=null&&a.max?(0,Te.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,Te.videoHeightToQuality)(a.min):void 0},highestAvailableQuality:e?(0,Te.videoHeightToQuality)(e):void 0,lowestAvailableQuality:t?(0,Te.videoHeightToQuality)(t):void 0})}var zA=new De("best_bitrate"),Nb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var _u=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),zi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,U.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Fb='Assertion "ABR Tracks is empty array" failed',en=(a,e,t,r)=>{var u;let i=[...e].sort(_u(1)),s=[...t].sort(_u(1)),n=s.filter(l=>(0,U.isNonNullable)(l.bitrate)&&(0,U.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,Bb.default)(n,o)?o:n.length?(0,Xt.default)(n,-1):(0,Xt.default)(s,0)},Ob=a=>"quality"in a,qb=(a,e,t,r)=>{var n;let i=(0,U.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,U.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,U.now)()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Ob(o)?"video":"audio",l=Ob(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
"use strict";var AS=Object.create;var gr=Object.defineProperty,kS=Object.defineProperties,RS=Object.getOwnPropertyDescriptor,LS=Object.getOwnPropertyDescriptors,$S=Object.getOwnPropertyNames,nc=Object.getOwnPropertySymbols,MS=Object.getPrototypeOf,uc=Object.prototype.hasOwnProperty,DS=Object.prototype.propertyIsEnumerable;var CS=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var ft=Math.pow,oc=(a,e,t)=>e in a?gr(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,$=(a,e)=>{for(var t in e||(e={}))uc.call(e,t)&&oc(a,t,e[t]);if(nc)for(var t of nc(e))DS.call(e,t)&&oc(a,t,e[t]);return a},j=(a,e)=>kS(a,LS(e));var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),VS=(a,e)=>{for(var t in e)gr(a,t,{get:e[t],enumerable:!0})},lc=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $S(e))!uc.call(a,r)&&r!==t&&gr(a,r,{get:()=>e[r],enumerable:!(i=RS(e,r))||i.enumerable});return a};var G=(a,e,t)=>(t=a!=null?AS(MS(a)):{},lc(e||!a||!a.__esModule?gr(t,"default",{value:a,enumerable:!0}):t,a)),OS=a=>lc(gr({},"__esModule",{value:!0}),a);var A=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),as=function(a,e){this[0]=a,this[1]=e},ye=(a,e,t)=>{var i=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof as,m=c.done;Promise.resolve(d?o[0]:o).then(p=>d?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:m})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>s[n]=o=>new Promise((u,l)=>i(n,o,u,l)),s={};return t=t.apply(a,e),s[CS("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var ge=b((Rn,cc)=>{"use strict";var yr=function(a){return a&&a.Math===Math&&a};cc.exports=yr(typeof globalThis=="object"&&globalThis)||yr(typeof window=="object"&&window)||yr(typeof self=="object"&&self)||yr(typeof global=="object"&&global)||yr(typeof Rn=="object"&&Rn)||function(){return this}()||Function("return this")()});var we=b((mL,dc)=>{"use strict";dc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Tr=b((fL,pc)=>{"use strict";var _S=we();pc.exports=!_S(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Ln=b((bL,bc)=>{"use strict";var BS=Tr(),fc=Function.prototype,hc=fc.apply,mc=fc.call;bc.exports=typeof Reflect=="object"&&Reflect.apply||(BS?mc.bind(hc):function(){return mc.apply(hc,arguments)})});var Ee=b((gL,Sc)=>{"use strict";var gc=Tr(),vc=Function.prototype,$n=vc.call,NS=gc&&vc.bind.bind($n,$n);Sc.exports=gc?NS:function(a){return function(){return $n.apply(a,arguments)}}});var li=b((vL,Tc)=>{"use strict";var yc=Ee(),FS=yc({}.toString),qS=yc("".slice);Tc.exports=function(a){return qS(FS(a),8,-1)}});var Mn=b((SL,Ic)=>{"use strict";var US=li(),HS=Ee();Ic.exports=function(a){if(US(a)==="Function")return HS(a)}});var fe=b((yL,Ec)=>{"use strict";var Dn=typeof document=="object"&&document.all;Ec.exports=typeof Dn=="undefined"&&Dn!==void 0?function(a){return typeof a=="function"||a===Dn}:function(a){return typeof a=="function"}});var He=b((TL,xc)=>{"use strict";var jS=we();xc.exports=!jS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var je=b((IL,Pc)=>{"use strict";var QS=Tr(),os=Function.prototype.call;Pc.exports=QS?os.bind(os):function(){return os.apply(os,arguments)}});var Cn=b(kc=>{"use strict";var wc={}.propertyIsEnumerable,Ac=Object.getOwnPropertyDescriptor,GS=Ac&&!wc.call({1:2},1);kc.f=GS?function(e){var t=Ac(this,e);return!!t&&t.enumerable}:wc});var Ir=b((xL,Rc)=>{"use strict";Rc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var $c=b((PL,Lc)=>{"use strict";var WS=Ee(),YS=we(),zS=li(),Vn=Object,KS=WS("".split);Lc.exports=YS(function(){return!Vn("z").propertyIsEnumerable(0)})?function(a){return zS(a)==="String"?KS(a,""):Vn(a)}:Vn});var Ci=b((wL,Mc)=>{"use strict";Mc.exports=function(a){return a==null}});var Ht=b((AL,Dc)=>{"use strict";var XS=Ci(),JS=TypeError;Dc.exports=function(a){if(XS(a))throw new JS("Can't call method on "+a);return a}});var ci=b((kL,Cc)=>{"use strict";var ZS=$c(),ey=Ht();Cc.exports=function(a){return ZS(ey(a))}});var Qe=b((RL,Vc)=>{"use strict";var ty=fe();Vc.exports=function(a){return typeof a=="object"?a!==null:ty(a)}});var Vi=b((LL,Oc)=>{"use strict";Oc.exports={}});var Pt=b(($L,Bc)=>{"use strict";var On=Vi(),_n=ge(),iy=fe(),_c=function(a){return iy(a)?a:void 0};Bc.exports=function(a,e){return arguments.length<2?_c(On[a])||_c(_n[a]):On[a]&&On[a][e]||_n[a]&&_n[a][e]}});var Er=b((ML,Nc)=>{"use strict";var ry=Ee();Nc.exports=ry({}.isPrototypeOf)});var di=b((DL,Uc)=>{"use strict";var ay=ge(),Fc=ay.navigator,qc=Fc&&Fc.userAgent;Uc.exports=qc?String(qc):""});var Nn=b((CL,Yc)=>{"use strict";var Wc=ge(),Bn=di(),Hc=Wc.process,jc=Wc.Deno,Qc=Hc&&Hc.versions||jc&&jc.version,Gc=Qc&&Qc.v8,nt,us;Gc&&(nt=Gc.split("."),us=nt[0]>0&&nt[0]<4?1:+(nt[0]+nt[1]));!us&&Bn&&(nt=Bn.match(/Edge\/(\d+)/),(!nt||nt[1]>=74)&&(nt=Bn.match(/Chrome\/(\d+)/),nt&&(us=+nt[1])));Yc.exports=us});var Fn=b((VL,Kc)=>{"use strict";var zc=Nn(),sy=we(),ny=ge(),oy=ny.String;Kc.exports=!!Object.getOwnPropertySymbols&&!sy(function(){var a=Symbol("symbol detection");return!oy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&zc&&zc<41})});var qn=b((OL,Xc)=>{"use strict";var uy=Fn();Xc.exports=uy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Un=b((_L,Jc)=>{"use strict";var ly=Pt(),cy=fe(),dy=Er(),py=qn(),hy=Object;Jc.exports=py?function(a){return typeof a=="symbol"}:function(a){var e=ly("Symbol");return cy(e)&&dy(e.prototype,hy(a))}});var xr=b((BL,Zc)=>{"use strict";var my=String;Zc.exports=function(a){try{return my(a)}catch(e){return"Object"}}});var gt=b((NL,ed)=>{"use strict";var fy=fe(),by=xr(),gy=TypeError;ed.exports=function(a){if(fy(a))return a;throw new gy(by(a)+" is not a function")}});var Pr=b((FL,td)=>{"use strict";var vy=gt(),Sy=Ci();td.exports=function(a,e){var t=a[e];return Sy(t)?void 0:vy(t)}});var rd=b((qL,id)=>{"use strict";var Hn=je(),jn=fe(),Qn=Qe(),yy=TypeError;id.exports=function(a,e){var t,i;if(e==="string"&&jn(t=a.toString)&&!Qn(i=Hn(t,a))||jn(t=a.valueOf)&&!Qn(i=Hn(t,a))||e!=="string"&&jn(t=a.toString)&&!Qn(i=Hn(t,a)))return i;throw new yy("Can't convert object to primitive value")}});var ot=b((UL,ad)=>{"use strict";ad.exports=!0});var od=b((HL,nd)=>{"use strict";var sd=ge(),Ty=Object.defineProperty;nd.exports=function(a,e){try{Ty(sd,a,{value:e,configurable:!0,writable:!0})}catch(t){sd[a]=e}return e}});var wr=b((jL,cd)=>{"use strict";var Iy=ot(),Ey=ge(),xy=od(),ud="__core-js_shared__",ld=cd.exports=Ey[ud]||xy(ud,{});(ld.versions||(ld.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 Gn=b((QL,pd)=>{"use strict";var dd=wr();pd.exports=function(a,e){return dd[a]||(dd[a]=e||{})}});var Oi=b((GL,hd)=>{"use strict";var Py=Ht(),wy=Object;hd.exports=function(a){return wy(Py(a))}});var ut=b((WL,md)=>{"use strict";var Ay=Ee(),ky=Oi(),Ry=Ay({}.hasOwnProperty);md.exports=Object.hasOwn||function(e,t){return Ry(ky(e),t)}});var Wn=b((YL,fd)=>{"use strict";var Ly=Ee(),$y=0,My=Math.random(),Dy=Ly(1 .toString);fd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Dy(++$y+My,36)}});var Ae=b((zL,gd)=>{"use strict";var Cy=ge(),Vy=Gn(),bd=ut(),Oy=Wn(),_y=Fn(),By=qn(),_i=Cy.Symbol,Yn=Vy("wks"),Ny=By?_i.for||_i:_i&&_i.withoutSetter||Oy;gd.exports=function(a){return bd(Yn,a)||(Yn[a]=_y&&bd(_i,a)?_i[a]:Ny("Symbol."+a)),Yn[a]}});var Td=b((KL,yd)=>{"use strict";var Fy=je(),vd=Qe(),Sd=Un(),qy=Pr(),Uy=rd(),Hy=Ae(),jy=TypeError,Qy=Hy("toPrimitive");yd.exports=function(a,e){if(!vd(a)||Sd(a))return a;var t=qy(a,Qy),i;if(t){if(e===void 0&&(e="default"),i=Fy(t,a,e),!vd(i)||Sd(i))return i;throw new jy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Uy(a,e)}});var zn=b((XL,Id)=>{"use strict";var Gy=Td(),Wy=Un();Id.exports=function(a){var e=Gy(a,"string");return Wy(e)?e:e+""}});var ls=b((JL,xd)=>{"use strict";var Yy=ge(),Ed=Qe(),Kn=Yy.document,zy=Ed(Kn)&&Ed(Kn.createElement);xd.exports=function(a){return zy?Kn.createElement(a):{}}});var Xn=b((ZL,Pd)=>{"use strict";var Ky=He(),Xy=we(),Jy=ls();Pd.exports=!Ky&&!Xy(function(){return Object.defineProperty(Jy("div"),"a",{get:function(){return 7}}).a!==7})});var kd=b(Ad=>{"use strict";var Zy=He(),eT=je(),tT=Cn(),iT=Ir(),rT=ci(),aT=zn(),sT=ut(),nT=Xn(),wd=Object.getOwnPropertyDescriptor;Ad.f=Zy?wd:function(e,t){if(e=rT(e),t=aT(t),nT)try{return wd(e,t)}catch(i){}if(sT(e,t))return iT(!eT(tT.f,e,t),e[t])}});var Jn=b((t$,Rd)=>{"use strict";var oT=we(),uT=fe(),lT=/#|\.prototype\./,Ar=function(a,e){var t=dT[cT(a)];return t===hT?!0:t===pT?!1:uT(e)?oT(e):!!e},cT=Ar.normalize=function(a){return String(a).replace(lT,".").toLowerCase()},dT=Ar.data={},pT=Ar.NATIVE="N",hT=Ar.POLYFILL="P";Rd.exports=Ar});var Bi=b((i$,$d)=>{"use strict";var Ld=Mn(),mT=gt(),fT=Tr(),bT=Ld(Ld.bind);$d.exports=function(a,e){return mT(a),e===void 0?a:fT?bT(a,e):function(){return a.apply(e,arguments)}}});var Zn=b((r$,Md)=>{"use strict";var gT=He(),vT=we();Md.exports=gT&&vT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var vt=b((a$,Dd)=>{"use strict";var ST=Qe(),yT=String,TT=TypeError;Dd.exports=function(a){if(ST(a))return a;throw new TT(yT(a)+" is not an object")}});var pi=b(Vd=>{"use strict";var IT=He(),ET=Xn(),xT=Zn(),cs=vt(),Cd=zn(),PT=TypeError,eo=Object.defineProperty,wT=Object.getOwnPropertyDescriptor,to="enumerable",io="configurable",ro="writable";Vd.f=IT?xT?function(e,t,i){if(cs(e),t=Cd(t),cs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&ro in i&&!i[ro]){var r=wT(e,t);r&&r[ro]&&(e[t]=i.value,i={configurable:io in i?i[io]:r[io],enumerable:to in i?i[to]:r[to],writable:!1})}return eo(e,t,i)}:eo:function(e,t,i){if(cs(e),t=Cd(t),cs(i),ET)try{return eo(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new PT("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ni=b((n$,Od)=>{"use strict";var AT=He(),kT=pi(),RT=Ir();Od.exports=AT?function(a,e,t){return kT.f(a,e,RT(1,t))}:function(a,e,t){return a[e]=t,a}});var Te=b((o$,Bd)=>{"use strict";var kr=ge(),LT=Ln(),$T=Mn(),MT=fe(),DT=kd().f,CT=Jn(),Fi=Vi(),VT=Bi(),qi=Ni(),_d=ut();wr();var OT=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return LT(a,this,arguments)};return e.prototype=a.prototype,e};Bd.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?kr:r?kr[t]:kr[t]&&kr[t].prototype,o=i?Fi:Fi[t]||qi(Fi,t,{})[t],u=o.prototype,l,c,d,m,p,f,g,S,y;for(m in e)l=CT(i?m:t+(r?".":"#")+m,a.forced),c=!l&&n&&_d(n,m),f=o[m],c&&(a.dontCallGetSet?(y=DT(n,m),g=y&&y.value):g=n[m]),p=c&&g?g:e[m],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?S=VT(p,kr):a.wrap&&c?S=OT(p):s&&MT(p)?S=$T(p):S=p,(a.sham||p&&p.sham||f&&f.sham)&&qi(S,"sham",!0),qi(o,m,S),s&&(d=t+"Prototype",_d(Fi,d)||qi(Fi,d,{}),qi(Fi[d],m,p),a.real&&u&&(l||!u[m])&&qi(u,m,p)))}});var Fd=b((u$,Nd)=>{"use strict";var _T=Math.ceil,BT=Math.floor;Nd.exports=Math.trunc||function(e){var t=+e;return(t>0?BT:_T)(t)}});var Rr=b((l$,qd)=>{"use strict";var NT=Fd();qd.exports=function(a){var e=+a;return e!==e||e===0?0:NT(e)}});var Hd=b((c$,Ud)=>{"use strict";var FT=Rr(),qT=Math.max,UT=Math.min;Ud.exports=function(a,e){var t=FT(a);return t<0?qT(t+e,0):UT(t,e)}});var ao=b((d$,jd)=>{"use strict";var HT=Rr(),jT=Math.min;jd.exports=function(a){var e=HT(a);return e>0?jT(e,9007199254740991):0}});var Ui=b((p$,Qd)=>{"use strict";var QT=ao();Qd.exports=function(a){return QT(a.length)}});var so=b((h$,Wd)=>{"use strict";var GT=ci(),WT=Hd(),YT=Ui(),Gd=function(a){return function(e,t,i){var r=GT(e),s=YT(r);if(s===0)return!a&&-1;var n=WT(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Wd.exports={includes:Gd(!0),indexOf:Gd(!1)}});var Lr=b((m$,Yd)=>{"use strict";Yd.exports=function(){}});var zd=b(()=>{"use strict";var zT=Te(),KT=so().includes,XT=we(),JT=Lr(),ZT=XT(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)}});JT("includes")});var jt=b((g$,Kd)=>{"use strict";var eI=Pt();Kd.exports=eI});var Jd=b((v$,Xd)=>{"use strict";zd();var tI=jt();Xd.exports=tI("Array","includes")});var ep=b((S$,Zd)=>{"use strict";var iI=Jd();Zd.exports=iI});var Ke=b((y$,tp)=>{"use strict";var rI=ep();tp.exports=rI});var ps=b(($$,ap)=>{"use strict";var sI=Gn(),nI=Wn(),rp=sI("keys");ap.exports=function(a){return rp[a]||(rp[a]=nI(a))}});var np=b((M$,sp)=>{"use strict";var oI=we();sp.exports=!oI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var hs=b((D$,up)=>{"use strict";var uI=ut(),lI=fe(),cI=Oi(),dI=ps(),pI=np(),op=dI("IE_PROTO"),no=Object,hI=no.prototype;up.exports=pI?no.getPrototypeOf:function(a){var e=cI(a);if(uI(e,op))return e[op];var t=e.constructor;return lI(t)&&e instanceof t?t.prototype:e instanceof no?hI:null}});var ms=b((C$,lp)=>{"use strict";lp.exports={}});var pp=b((V$,dp)=>{"use strict";var mI=Ee(),oo=ut(),fI=ci(),bI=so().indexOf,gI=ms(),cp=mI([].push);dp.exports=function(a,e){var t=fI(a),i=0,r=[],s;for(s in t)!oo(gI,s)&&oo(t,s)&&cp(r,s);for(;e.length>i;)oo(t,s=e[i++])&&(~bI(r,s)||cp(r,s));return r}});var uo=b((O$,hp)=>{"use strict";hp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var lo=b((_$,mp)=>{"use strict";var vI=pp(),SI=uo();mp.exports=Object.keys||function(e){return vI(e,SI)}});var co=b((B$,Sp)=>{"use strict";var bp=He(),yI=we(),gp=Ee(),TI=hs(),II=lo(),EI=ci(),xI=Cn().f,vp=gp(xI),PI=gp([].push),wI=bp&&yI(function(){var a=Object.create(null);return a[2]=2,!vp(a,2)}),fp=function(a){return function(e){for(var t=EI(e),i=II(t),r=wI&&TI(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!bp||(r?u in t:vp(t,u)))&&PI(o,a?[u,t[u]]:t[u]);return o}};Sp.exports={entries:fp(!0),values:fp(!1)}});var yp=b(()=>{"use strict";var AI=Te(),kI=co().entries;AI({target:"Object",stat:!0},{entries:function(e){return kI(e)}})});var Ip=b((q$,Tp)=>{"use strict";yp();var RI=Vi();Tp.exports=RI.Object.entries});var xp=b((U$,Ep)=>{"use strict";var LI=Ip();Ep.exports=LI});var Hi=b((H$,Pp)=>{"use strict";var $I=xp();Pp.exports=$I});var hi=b((j$,wp)=>{"use strict";wp.exports={}});var Rp=b((Q$,kp)=>{"use strict";var MI=ge(),DI=fe(),Ap=MI.WeakMap;kp.exports=DI(Ap)&&/native code/.test(String(Ap))});var fo=b((G$,Mp)=>{"use strict";var CI=Rp(),$p=ge(),VI=Qe(),OI=Ni(),po=ut(),ho=wr(),_I=ps(),BI=ms(),Lp="Object already initialized",mo=$p.TypeError,NI=$p.WeakMap,fs,$r,bs,FI=function(a){return bs(a)?$r(a):fs(a,{})},qI=function(a){return function(e){var t;if(!VI(e)||(t=$r(e)).type!==a)throw new mo("Incompatible receiver, "+a+" required");return t}};CI||ho.state?(lt=ho.state||(ho.state=new NI),lt.get=lt.get,lt.has=lt.has,lt.set=lt.set,fs=function(a,e){if(lt.has(a))throw new mo(Lp);return e.facade=a,lt.set(a,e),e},$r=function(a){return lt.get(a)||{}},bs=function(a){return lt.has(a)}):(mi=_I("state"),BI[mi]=!0,fs=function(a,e){if(po(a,mi))throw new mo(Lp);return e.facade=a,OI(a,mi,e),e},$r=function(a){return po(a,mi)?a[mi]:{}},bs=function(a){return po(a,mi)});var lt,mi;Mp.exports={set:fs,get:$r,has:bs,enforce:FI,getterFor:qI}});var vo=b((W$,Cp)=>{"use strict";var bo=He(),UI=ut(),Dp=Function.prototype,HI=bo&&Object.getOwnPropertyDescriptor,go=UI(Dp,"name"),jI=go&&function(){}.name==="something",QI=go&&(!bo||bo&&HI(Dp,"name").configurable);Cp.exports={EXISTS:go,PROPER:jI,CONFIGURABLE:QI}});var Op=b(Vp=>{"use strict";var GI=He(),WI=Zn(),YI=pi(),zI=vt(),KI=ci(),XI=lo();Vp.f=GI&&!WI?Object.defineProperties:function(e,t){zI(e);for(var i=KI(t),r=XI(t),s=r.length,n=0,o;s>n;)YI.f(e,o=r[n++],i[o]);return e}});var So=b((z$,_p)=>{"use strict";var JI=Pt();_p.exports=JI("document","documentElement")});var Eo=b((K$,jp)=>{"use strict";var ZI=vt(),eE=Op(),Bp=uo(),tE=ms(),iE=So(),rE=ls(),aE=ps(),Np=">",Fp="<",To="prototype",Io="script",Up=aE("IE_PROTO"),yo=function(){},Hp=function(a){return Fp+Io+Np+a+Fp+"/"+Io+Np},qp=function(a){a.write(Hp("")),a.close();var e=a.parentWindow.Object;return a=null,e},sE=function(){var a=rE("iframe"),e="java"+Io+":",t;return a.style.display="none",iE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Hp("document.F=Object")),t.close(),t.F},gs,vs=function(){try{gs=new ActiveXObject("htmlfile")}catch(e){}vs=typeof document!="undefined"?document.domain&&gs?qp(gs):sE():qp(gs);for(var a=Bp.length;a--;)delete vs[To][Bp[a]];return vs()};tE[Up]=!0;jp.exports=Object.create||function(e,t){var i;return e!==null?(yo[To]=ZI(e),i=new yo,yo[To]=null,i[Up]=e):i=vs(),t===void 0?i:eE.f(i,t)}});var ji=b((X$,Qp)=>{"use strict";var nE=Ni();Qp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:nE(a,e,t),a}});var Ao=b((J$,Yp)=>{"use strict";var oE=we(),uE=fe(),lE=Qe(),cE=Eo(),Gp=hs(),dE=ji(),pE=Ae(),hE=ot(),wo=pE("iterator"),Wp=!1,wt,xo,Po;[].keys&&(Po=[].keys(),"next"in Po?(xo=Gp(Gp(Po)),xo!==Object.prototype&&(wt=xo)):Wp=!0);var mE=!lE(wt)||oE(function(){var a={};return wt[wo].call(a)!==a});mE?wt={}:hE&&(wt=cE(wt));uE(wt[wo])||dE(wt,wo,function(){return this});Yp.exports={IteratorPrototype:wt,BUGGY_SAFARI_ITERATORS:Wp}});var Ss=b((Z$,Kp)=>{"use strict";var fE=Ae(),bE=fE("toStringTag"),zp={};zp[bE]="z";Kp.exports=String(zp)==="[object z]"});var Mr=b((eM,Xp)=>{"use strict";var gE=Ss(),vE=fe(),ys=li(),SE=Ae(),yE=SE("toStringTag"),TE=Object,IE=ys(function(){return arguments}())==="Arguments",EE=function(a,e){try{return a[e]}catch(t){}};Xp.exports=gE?ys:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=EE(e=TE(a),yE))=="string"?t:IE?ys(e):(i=ys(e))==="Object"&&vE(e.callee)?"Arguments":i}});var Zp=b((tM,Jp)=>{"use strict";var xE=Ss(),PE=Mr();Jp.exports=xE?{}.toString:function(){return"[object "+PE(this)+"]"}});var Dr=b((iM,th)=>{"use strict";var wE=Ss(),AE=pi().f,kE=Ni(),RE=ut(),LE=Zp(),$E=Ae(),eh=$E("toStringTag");th.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(RE(r,eh)||AE(r,eh,{configurable:!0,value:e}),i&&!wE&&kE(r,"toString",LE))}});var rh=b((rM,ih)=>{"use strict";var ME=Ao().IteratorPrototype,DE=Eo(),CE=Ir(),VE=Dr(),OE=hi(),_E=function(){return this};ih.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=DE(ME,{next:CE(+!i,t)}),VE(a,r,!1,!0),OE[r]=_E,a}});var sh=b((aM,ah)=>{"use strict";var BE=Ee(),NE=gt();ah.exports=function(a,e,t){try{return BE(NE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var oh=b((sM,nh)=>{"use strict";var FE=Qe();nh.exports=function(a){return FE(a)||a===null}});var lh=b((nM,uh)=>{"use strict";var qE=oh(),UE=String,HE=TypeError;uh.exports=function(a){if(qE(a))return a;throw new HE("Can't set "+UE(a)+" as a prototype")}});var ko=b((oM,ch)=>{"use strict";var jE=sh(),QE=Qe(),GE=Ht(),WE=lh();ch.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(i){}return function(r,s){return GE(r),WE(s),QE(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Th=b((uM,yh)=>{"use strict";var YE=Te(),zE=je(),Ts=ot(),vh=vo(),KE=fe(),XE=rh(),dh=hs(),ph=ko(),JE=Dr(),ZE=Ni(),Ro=ji(),ex=Ae(),hh=hi(),Sh=Ao(),tx=vh.PROPER,ix=vh.CONFIGURABLE,mh=Sh.IteratorPrototype,Is=Sh.BUGGY_SAFARI_ITERATORS,Cr=ex("iterator"),fh="keys",Vr="values",bh="entries",gh=function(){return this};yh.exports=function(a,e,t,i,r,s,n){XE(t,e,i);var o=function(y){if(y===r&&m)return m;if(!Is&&y&&y in c)return c[y];switch(y){case fh:return function(){return new t(this,y)};case Vr:return function(){return new t(this,y)};case bh:return function(){return new t(this,y)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Cr]||c["@@iterator"]||r&&c[r],m=!Is&&d||o(r),p=e==="Array"&&c.entries||d,f,g,S;if(p&&(f=dh(p.call(new a)),f!==Object.prototype&&f.next&&(!Ts&&dh(f)!==mh&&(ph?ph(f,mh):KE(f[Cr])||Ro(f,Cr,gh)),JE(f,u,!0,!0),Ts&&(hh[u]=gh))),tx&&r===Vr&&d&&d.name!==Vr&&(!Ts&&ix?ZE(c,"name",Vr):(l=!0,m=function(){return zE(d,this)})),r)if(g={values:o(Vr),keys:s?m:o(fh),entries:o(bh)},n)for(S in g)(Is||l||!(S in c))&&Ro(c,S,g[S]);else YE({target:e,proto:!0,forced:Is||l},g);return(!Ts||n)&&c[Cr]!==m&&Ro(c,Cr,m,{name:r}),hh[e]=m,g}});var Eh=b((lM,Ih)=>{"use strict";Ih.exports=function(a,e){return{value:a,done:e}}});var $o=b((cM,kh)=>{"use strict";var rx=ci(),Lo=Lr(),xh=hi(),wh=fo(),ax=pi().f,sx=Th(),Es=Eh(),nx=ot(),ox=He(),Ah="Array Iterator",ux=wh.set,lx=wh.getterFor(Ah);kh.exports=sx(Array,"Array",function(a,e){ux(this,{type:Ah,target:rx(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,Es(void 0,!0);switch(a.kind){case"keys":return Es(t,!1);case"values":return Es(e[t],!1)}return Es([t,e[t]],!1)},"values");var Ph=xh.Arguments=xh.Array;Lo("keys");Lo("values");Lo("entries");if(!nx&&ox&&Ph.name!=="values")try{ax(Ph,"name",{value:"values"})}catch(a){}});var Lh=b((dM,Rh)=>{"use strict";var cx=Ae(),dx=hi(),px=cx("iterator"),hx=Array.prototype;Rh.exports=function(a){return a!==void 0&&(dx.Array===a||hx[px]===a)}});var Mo=b((pM,Mh)=>{"use strict";var mx=Mr(),$h=Pr(),fx=Ci(),bx=hi(),gx=Ae(),vx=gx("iterator");Mh.exports=function(a){if(!fx(a))return $h(a,vx)||$h(a,"@@iterator")||bx[mx(a)]}});var Ch=b((hM,Dh)=>{"use strict";var Sx=je(),yx=gt(),Tx=vt(),Ix=xr(),Ex=Mo(),xx=TypeError;Dh.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 _h=b((mM,Oh)=>{"use strict";var Px=je(),Vh=vt(),wx=Pr();Oh.exports=function(a,e,t){var i,r;Vh(a);try{if(i=wx(a,"return"),!i){if(e==="throw")throw t;return t}i=Px(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Vh(i),t}});var Ps=b((fM,qh)=>{"use strict";var Ax=Bi(),kx=je(),Rx=vt(),Lx=xr(),$x=Lh(),Mx=Ui(),Bh=Er(),Dx=Ch(),Cx=Mo(),Nh=_h(),Vx=TypeError,xs=function(a,e){this.stopped=a,this.result=e},Fh=xs.prototype;qh.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Ax(e,i),l,c,d,m,p,f,g,S=function(I){return l&&Nh(l,"normal",I),new xs(!0,I)},y=function(I){return r?(Rx(I),o?u(I[0],I[1],S):u(I[0],I[1])):o?u(I,S):u(I)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Cx(a),!c)throw new Vx(Lx(a)+" is not iterable");if($x(c)){for(d=0,m=Mx(a);m>d;d++)if(p=y(a[d]),p&&Bh(Fh,p))return p;return new xs(!1)}l=Dx(a,c)}for(f=s?a.next:l.next;!(g=kx(f,l)).done;){try{p=y(g.value)}catch(I){Nh(l,"throw",I)}if(typeof p=="object"&&p&&Bh(Fh,p))return p}return new xs(!1)}});var Hh=b((bM,Uh)=>{"use strict";var Ox=He(),_x=pi(),Bx=Ir();Uh.exports=function(a,e,t){Ox?_x.f(a,e,Bx(0,t)):a[e]=t}});var jh=b(()=>{"use strict";var Nx=Te(),Fx=Ps(),qx=Hh();Nx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Fx(e,function(i,r){qx(t,i,r)},{AS_ENTRIES:!0}),t}})});var Gh=b((SM,Qh)=>{"use strict";$o();jh();var Ux=Vi();Qh.exports=Ux.Object.fromEntries});var Yh=b((yM,Wh)=>{"use strict";Wh.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 Kh=b(()=>{"use strict";$o();var Hx=Yh(),jx=ge(),Qx=Dr(),zh=hi();for(ws in Hx)Qx(jx[ws],ws),zh[ws]=zh.Array;var ws});var Jh=b((EM,Xh)=>{"use strict";var Gx=Gh();Kh();Xh.exports=Gx});var Do=b((xM,Zh)=>{"use strict";var Wx=Jh();Zh.exports=Wx});var em=b(()=>{"use strict"});var Co=b((AM,tm)=>{"use strict";var Or=ge(),Yx=di(),zx=li(),As=function(a){return Yx.slice(0,a.length)===a};tm.exports=function(){return As("Bun/")?"BUN":As("Cloudflare-Workers")?"CLOUDFLARE":As("Deno/")?"DENO":As("Node.js/")?"NODE":Or.Bun&&typeof Bun.version=="string"?"BUN":Or.Deno&&typeof Deno.version=="object"?"DENO":zx(Or.process)==="process"?"NODE":Or.window&&Or.document?"BROWSER":"REST"}()});var ks=b((kM,im)=>{"use strict";var Kx=Co();im.exports=Kx==="NODE"});var am=b((RM,rm)=>{"use strict";var Xx=pi();rm.exports=function(a,e,t){return Xx.f(a,e,t)}});var om=b((LM,nm)=>{"use strict";var Jx=Pt(),Zx=am(),eP=Ae(),tP=He(),sm=eP("species");nm.exports=function(a){var e=Jx(a);tP&&e&&!e[sm]&&Zx(e,sm,{configurable:!0,get:function(){return this}})}});var lm=b(($M,um)=>{"use strict";var iP=Er(),rP=TypeError;um.exports=function(a,e){if(iP(e,a))return a;throw new rP("Incorrect invocation")}});var Oo=b((MM,cm)=>{"use strict";var aP=Ee(),sP=fe(),Vo=wr(),nP=aP(Function.toString);sP(Vo.inspectSource)||(Vo.inspectSource=function(a){return nP(a)});cm.exports=Vo.inspectSource});var Bo=b((DM,fm)=>{"use strict";var oP=Ee(),uP=we(),dm=fe(),lP=Mr(),cP=Pt(),dP=Oo(),pm=function(){},hm=cP("Reflect","construct"),_o=/^\s*(?:class|function)\b/,pP=oP(_o.exec),hP=!_o.test(pm),_r=function(e){if(!dm(e))return!1;try{return hm(pm,[],e),!0}catch(t){return!1}},mm=function(e){if(!dm(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}};mm.sham=!0;fm.exports=!hm||uP(function(){var a;return _r(_r.call)||!_r(Object)||!_r(function(){a=!0})||a})?mm:_r});var gm=b((CM,bm)=>{"use strict";var mP=Bo(),fP=xr(),bP=TypeError;bm.exports=function(a){if(mP(a))return a;throw new bP(fP(a)+" is not a constructor")}});var No=b((VM,Sm)=>{"use strict";var vm=vt(),gP=gm(),vP=Ci(),SP=Ae(),yP=SP("species");Sm.exports=function(a,e){var t=vm(a).constructor,i;return t===void 0||vP(i=vm(t)[yP])?e:gP(i)}});var Tm=b((OM,ym)=>{"use strict";var TP=Ee();ym.exports=TP([].slice)});var Em=b((_M,Im)=>{"use strict";var IP=TypeError;Im.exports=function(a,e){if(a<e)throw new IP("Not enough arguments");return a}});var Fo=b((BM,xm)=>{"use strict";var EP=di();xm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(EP)});var zo=b((NM,Dm)=>{"use strict";var Ge=ge(),xP=Ln(),PP=Bi(),Pm=fe(),wP=ut(),Mm=we(),wm=So(),AP=Tm(),Am=ls(),kP=Em(),RP=Fo(),LP=ks(),Go=Ge.setImmediate,Wo=Ge.clearImmediate,$P=Ge.process,qo=Ge.Dispatch,MP=Ge.Function,km=Ge.MessageChannel,DP=Ge.String,Uo=0,Br={},Rm="onreadystatechange",Nr,fi,Ho,jo;Mm(function(){Nr=Ge.location});var Yo=function(a){if(wP(Br,a)){var e=Br[a];delete Br[a],e()}},Qo=function(a){return function(){Yo(a)}},Lm=function(a){Yo(a.data)},$m=function(a){Ge.postMessage(DP(a),Nr.protocol+"//"+Nr.host)};(!Go||!Wo)&&(Go=function(e){kP(arguments.length,1);var t=Pm(e)?e:MP(e),i=AP(arguments,1);return Br[++Uo]=function(){xP(t,void 0,i)},fi(Uo),Uo},Wo=function(e){delete Br[e]},LP?fi=function(a){$P.nextTick(Qo(a))}:qo&&qo.now?fi=function(a){qo.now(Qo(a))}:km&&!RP?(Ho=new km,jo=Ho.port2,Ho.port1.onmessage=Lm,fi=PP(jo.postMessage,jo)):Ge.addEventListener&&Pm(Ge.postMessage)&&!Ge.importScripts&&Nr&&Nr.protocol!=="file:"&&!Mm($m)?(fi=$m,Ge.addEventListener("message",Lm,!1)):Rm in Am("script")?fi=function(a){wm.appendChild(Am("script"))[Rm]=function(){wm.removeChild(this),Yo(a)}}:fi=function(a){setTimeout(Qo(a),0)});Dm.exports={set:Go,clear:Wo}});var Om=b((FM,Vm)=>{"use strict";var Cm=ge(),CP=He(),VP=Object.getOwnPropertyDescriptor;Vm.exports=function(a){if(!CP)return Cm[a];var e=VP(Cm,a);return e&&e.value}});var Ko=b((qM,Bm)=>{"use strict";var _m=function(){this.head=null,this.tail=null};_m.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}}};Bm.exports=_m});var Fm=b((UM,Nm)=>{"use strict";var OP=di();Nm.exports=/ipad|iphone|ipod/i.test(OP)&&typeof Pebble!="undefined"});var Um=b((HM,qm)=>{"use strict";var _P=di();qm.exports=/web0s(?!.*chrome)/i.test(_P)});var zm=b((jM,Ym)=>{"use strict";var Gi=ge(),BP=Om(),Hm=Bi(),Xo=zo().set,NP=Ko(),FP=Fo(),qP=Fm(),UP=Um(),Jo=ks(),jm=Gi.MutationObserver||Gi.WebKitMutationObserver,Qm=Gi.document,Gm=Gi.process,Rs=Gi.Promise,tu=BP("queueMicrotask"),Qi,Zo,eu,Ls,Wm;tu||(Fr=new NP,qr=function(){var a,e;for(Jo&&(a=Gm.domain)&&a.exit();e=Fr.get();)try{e()}catch(t){throw Fr.head&&Qi(),t}a&&a.enter()},!FP&&!Jo&&!UP&&jm&&Qm?(Zo=!0,eu=Qm.createTextNode(""),new jm(qr).observe(eu,{characterData:!0}),Qi=function(){eu.data=Zo=!Zo}):!qP&&Rs&&Rs.resolve?(Ls=Rs.resolve(void 0),Ls.constructor=Rs,Wm=Hm(Ls.then,Ls),Qi=function(){Wm(qr)}):Jo?Qi=function(){Gm.nextTick(qr)}:(Xo=Hm(Xo,Gi),Qi=function(){Xo(qr)}),tu=function(a){Fr.head||Qi(),Fr.add(a)});var Fr,qr;Ym.exports=tu});var Xm=b((QM,Km)=>{"use strict";Km.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var $s=b((GM,Jm)=>{"use strict";Jm.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var bi=b((WM,Zm)=>{"use strict";var HP=ge();Zm.exports=HP.Promise});var Wi=b((YM,af)=>{"use strict";var jP=ge(),Ur=bi(),QP=fe(),GP=Jn(),WP=Oo(),YP=Ae(),ef=Co(),zP=ot(),iu=Nn(),tf=Ur&&Ur.prototype,KP=YP("species"),ru=!1,rf=QP(jP.PromiseRejectionEvent),XP=GP("Promise",function(){var a=WP(Ur),e=a!==String(Ur);if(!e&&iu===66||zP&&!(tf.catch&&tf.finally))return!0;if(!iu||iu<51||!/native code/.test(a)){var t=new Ur(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[KP]=i,ru=t.then(function(){})instanceof i,!ru)return!0}return!e&&(ef==="BROWSER"||ef==="DENO")&&!rf});af.exports={CONSTRUCTOR:XP,REJECTION_EVENT:rf,SUBCLASSING:ru}});var Yi=b((zM,nf)=>{"use strict";var sf=gt(),JP=TypeError,ZP=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new JP("Bad Promise constructor");e=i,t=r}),this.resolve=sf(e),this.reject=sf(t)};nf.exports.f=function(a){return new ZP(a)}});var Pf=b(()=>{"use strict";var ew=Te(),tw=ot(),Vs=ks(),Qt=ge(),Ji=je(),of=ji(),uf=ko(),iw=Dr(),rw=om(),aw=gt(),Cs=fe(),sw=Qe(),nw=lm(),ow=No(),hf=zo().set,uu=zm(),uw=Xm(),lw=$s(),cw=Ko(),mf=fo(),Os=bi(),lu=Wi(),ff=Yi(),_s="Promise",bf=lu.CONSTRUCTOR,dw=lu.REJECTION_EVENT,pw=lu.SUBCLASSING,au=mf.getterFor(_s),hw=mf.set,zi=Os&&Os.prototype,gi=Os,Ms=zi,gf=Qt.TypeError,su=Qt.document,cu=Qt.process,nu=ff.f,mw=nu,fw=!!(su&&su.createEvent&&Qt.dispatchEvent),vf="unhandledrejection",bw="rejectionhandled",lf=0,Sf=1,gw=2,du=1,yf=2,Ds,cf,vw,df,Tf=function(a){var e;return sw(a)&&Cs(e=a.then)?e:!1},If=function(a,e){var t=e.value,i=e.state===Sf,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===yf&&yw(e),e.rejection=du),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new gf("Promise-chain cycle")):(l=Tf(u))?Ji(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Ef=function(a,e){a.notified||(a.notified=!0,uu(function(){for(var t=a.reactions,i;i=t.get();)If(i,a);a.notified=!1,e&&!a.rejection&&Sw(a)}))},xf=function(a,e,t){var i,r;fw?(i=su.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Qt.dispatchEvent(i)):i={promise:e,reason:t},!dw&&(r=Qt["on"+a])?r(i):a===vf&&uw("Unhandled promise rejection",t)},Sw=function(a){Ji(hf,Qt,function(){var e=a.facade,t=a.value,i=pf(a),r;if(i&&(r=lw(function(){Vs?cu.emit("unhandledRejection",t,e):xf(vf,e,t)}),a.rejection=Vs||pf(a)?yf:du,r.error))throw r.value})},pf=function(a){return a.rejection!==du&&!a.parent},yw=function(a){Ji(hf,Qt,function(){var e=a.facade;Vs?cu.emit("rejectionHandled",e):xf(bw,e,a.value)})},Ki=function(a,e,t){return function(i){a(e,i,t)}},Xi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=gw,Ef(a,!0))},ou=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new gf("Promise can't be resolved itself");var i=Tf(e);i?uu(function(){var r={done:!1};try{Ji(i,e,Ki(ou,r,a),Ki(Xi,r,a))}catch(s){Xi(r,s,a)}}):(a.value=e,a.state=Sf,Ef(a,!1))}catch(r){Xi({done:!1},r,a)}}};if(bf&&(gi=function(e){nw(this,Ms),aw(e),Ji(Ds,this);var t=au(this);try{e(Ki(ou,t),Ki(Xi,t))}catch(i){Xi(t,i)}},Ms=gi.prototype,Ds=function(e){hw(this,{type:_s,done:!1,notified:!1,parent:!1,reactions:new cw,rejection:!1,state:lf,value:void 0})},Ds.prototype=of(Ms,"then",function(e,t){var i=au(this),r=nu(ow(this,gi));return i.parent=!0,r.ok=Cs(e)?e:!0,r.fail=Cs(t)&&t,r.domain=Vs?cu.domain:void 0,i.state===lf?i.reactions.add(r):uu(function(){If(r,i)}),r.promise}),cf=function(){var a=new Ds,e=au(a);this.promise=a,this.resolve=Ki(ou,e),this.reject=Ki(Xi,e)},ff.f=nu=function(a){return a===gi||a===vw?new cf(a):mw(a)},!tw&&Cs(Os)&&zi!==Object.prototype)){df=zi.then,pw||of(zi,"then",function(e,t){var i=this;return new gi(function(r,s){Ji(df,i,r,s)}).then(e,t)},{unsafe:!0});try{delete zi.constructor}catch(a){}uf&&uf(zi,Ms)}ew({global:!0,constructor:!0,wrap:!0,forced:bf},{Promise:gi});iw(gi,_s,!1,!0);rw(_s)});var Lf=b((JM,Rf)=>{"use strict";var Tw=Ae(),Af=Tw("iterator"),kf=!1;try{wf=0,pu={next:function(){return{done:!!wf++}},return:function(){kf=!0}},pu[Af]=function(){return this},Array.from(pu,function(){throw 2})}catch(a){}var wf,pu;Rf.exports=function(a,e){try{if(!e&&!kf)return!1}catch(r){return!1}var t=!1;try{var i={};i[Af]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var hu=b((ZM,$f)=>{"use strict";var Iw=bi(),Ew=Lf(),xw=Wi().CONSTRUCTOR;$f.exports=xw||!Ew(function(a){Iw.all(a).then(void 0,function(){})})});var Mf=b(()=>{"use strict";var Pw=Te(),ww=je(),Aw=gt(),kw=Yi(),Rw=$s(),Lw=Ps(),$w=hu();Pw({target:"Promise",stat:!0,forced:$w},{all:function(e){var t=this,i=kw.f(t),r=i.resolve,s=i.reject,n=Rw(function(){var o=Aw(t.resolve),u=[],l=0,c=1;Lw(e,function(d){var m=l++,p=!1;c++,ww(o,t,d).then(function(f){p||(p=!0,u[m]=f,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var Cf=b(()=>{"use strict";var Mw=Te(),Dw=ot(),Cw=Wi().CONSTRUCTOR,fu=bi(),Vw=Pt(),Ow=fe(),_w=ji(),Df=fu&&fu.prototype;Mw({target:"Promise",proto:!0,forced:Cw,real:!0},{catch:function(a){return this.then(void 0,a)}});!Dw&&Ow(fu)&&(mu=Vw("Promise").prototype.catch,Df.catch!==mu&&_w(Df,"catch",mu,{unsafe:!0}));var mu});var Vf=b(()=>{"use strict";var Bw=Te(),Nw=je(),Fw=gt(),qw=Yi(),Uw=$s(),Hw=Ps(),jw=hu();Bw({target:"Promise",stat:!0,forced:jw},{race:function(e){var t=this,i=qw.f(t),r=i.reject,s=Uw(function(){var n=Fw(t.resolve);Hw(e,function(o){Nw(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Of=b(()=>{"use strict";var Qw=Te(),Gw=Yi(),Ww=Wi().CONSTRUCTOR;Qw({target:"Promise",stat:!0,forced:Ww},{reject:function(e){var t=Gw.f(this),i=t.reject;return i(e),t.promise}})});var bu=b((uD,_f)=>{"use strict";var Yw=vt(),zw=Qe(),Kw=Yi();_f.exports=function(a,e){if(Yw(a),zw(e)&&e.constructor===a)return e;var t=Kw.f(a),i=t.resolve;return i(e),t.promise}});var Ff=b(()=>{"use strict";var Xw=Te(),Jw=Pt(),Bf=ot(),Zw=bi(),Nf=Wi().CONSTRUCTOR,eA=bu(),tA=Jw("Promise"),iA=Bf&&!Nf;Xw({target:"Promise",stat:!0,forced:Bf||Nf},{resolve:function(e){return eA(iA&&this===tA?Zw:this,e)}})});var qf=b(()=>{"use strict";Pf();Mf();Cf();Vf();Of();Ff()});var Qf=b(()=>{"use strict";var rA=Te(),aA=ot(),Bs=bi(),sA=we(),Hf=Pt(),jf=fe(),nA=No(),Uf=bu(),oA=ji(),vu=Bs&&Bs.prototype,uA=!!Bs&&sA(function(){vu.finally.call({then:function(){}},function(){})});rA({target:"Promise",proto:!0,real:!0,forced:uA},{finally:function(a){var e=nA(this,Hf("Promise")),t=jf(a);return this.then(t?function(i){return Uf(e,a()).then(function(){return i})}:a,t?function(i){return Uf(e,a()).then(function(){throw i})}:a)}});!aA&&jf(Bs)&&(gu=Hf("Promise").prototype.finally,vu.finally!==gu&&oA(vu,"finally",gu,{unsafe:!0}));var gu});var Wf=b((fD,Gf)=>{"use strict";em();qf();Qf();var lA=jt();Gf.exports=lA("Promise","finally")});var zf=b((bD,Yf)=>{"use strict";var cA=Wf();Yf.exports=cA});var Ns=b((gD,Kf)=>{"use strict";var dA=zf();Kf.exports=dA});var rb=b(()=>{"use strict";var bA=Te(),gA=co().values;bA({target:"Object",stat:!0},{values:function(e){return gA(e)}})});var sb=b((YD,ab)=>{"use strict";rb();var vA=Vi();ab.exports=vA.Object.values});var ob=b((zD,nb)=>{"use strict";var SA=sb();nb.exports=SA});var Zi=b((KD,ub)=>{"use strict";var yA=ob();ub.exports=yA});var yb=b(()=>{"use strict";var LA=Te(),$A=Oi(),MA=Ui(),DA=Rr(),CA=Lr();LA({target:"Array",proto:!0},{at:function(e){var t=$A(this),i=MA(t),r=DA(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});CA("at")});var Ib=b((r0,Tb)=>{"use strict";yb();var VA=jt();Tb.exports=VA("Array","at")});var xb=b((a0,Eb)=>{"use strict";var OA=Ib();Eb.exports=OA});var zt=b((s0,Pb)=>{"use strict";var _A=xb();Pb.exports=_A});var _u=b((CV,jb)=>{"use strict";var YA=li();jb.exports=Array.isArray||function(e){return YA(e)==="Array"}});var Gb=b((VV,Qb)=>{"use strict";var zA=TypeError,KA=9007199254740991;Qb.exports=function(a){if(a>KA)throw zA("Maximum allowed index exceeded");return a}});var zb=b((OV,Yb)=>{"use strict";var XA=_u(),JA=Ui(),ZA=Gb(),ek=Bi(),Wb=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?ek(n,o):!1,d,m;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&XA(d)?(m=JA(d),u=Wb(a,e,d,m,u,s-1)-1):(ZA(u+1),a[u]=d),u++),l++;return u};Yb.exports=Wb});var Zb=b((_V,Jb)=>{"use strict";var Kb=_u(),tk=Bo(),ik=Qe(),rk=Ae(),ak=rk("species"),Xb=Array;Jb.exports=function(a){var e;return Kb(a)&&(e=a.constructor,tk(e)&&(e===Xb||Kb(e.prototype))?e=void 0:ik(e)&&(e=e[ak],e===null&&(e=void 0))),e===void 0?Xb:e}});var tg=b((BV,eg)=>{"use strict";var sk=Zb();eg.exports=function(a,e){return new(sk(a))(e===0?0:e)}});var ig=b(()=>{"use strict";var nk=Te(),ok=zb(),uk=gt(),lk=Oi(),ck=Ui(),dk=tg();nk({target:"Array",proto:!0},{flatMap:function(e){var t=lk(this),i=ck(t),r;return uk(e),r=dk(t,0),r.length=ok(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var rg=b(()=>{"use strict";var pk=Lr();pk("flatMap")});var sg=b((HV,ag)=>{"use strict";ig();rg();var hk=jt();ag.exports=hk("Array","flatMap")});var og=b((jV,ng)=>{"use strict";var mk=sg();ng.exports=mk});var Bu=b((QV,ug)=>{"use strict";var fk=og();ug.exports=fk});var Zr=b((GV,lg)=>{"use strict";var bk=Mr(),gk=String;lg.exports=function(a){if(bk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return gk(a)}});var Nu=b((WV,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((YV,pg)=>{"use strict";var vk=Ee(),Sk=Ht(),yk=Zr(),qu=Nu(),dg=vk("".replace),Tk=RegExp("^["+qu+"]+"),Ik=RegExp("(^|[^"+qu+"])["+qu+"]+$"),Fu=function(a){return function(e){var t=yk(Sk(e));return a&1&&(t=dg(t,Tk,"")),a&2&&(t=dg(t,Ik,"$1")),t}};pg.exports={start:Fu(1),end:Fu(2),trim:Fu(3)}});var gg=b((zV,bg)=>{"use strict";var Ek=vo().PROPER,xk=we(),mg=Nu(),fg="\u200B\x85\u180E";bg.exports=function(a){return xk(function(){return!!mg[a]()||fg[a]()!==fg||Ek&&mg[a].name!==a})}});var Uu=b((KV,vg)=>{"use strict";var Pk=hg().start,wk=gg();vg.exports=wk("trimStart")?function(){return Pk(this)}:"".trimStart});var yg=b(()=>{"use strict";var Ak=Te(),Sg=Uu();Ak({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Sg},{trimLeft:Sg})});var Ig=b(()=>{"use strict";yg();var kk=Te(),Tg=Uu();kk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Tg},{trimStart:Tg})});var xg=b((tO,Eg)=>{"use strict";Ig();var Rk=jt();Eg.exports=Rk("String","trimLeft")});var wg=b((iO,Pg)=>{"use strict";var Lk=xg();Pg.exports=Lk});var kg=b((rO,Ag)=>{"use strict";var $k=wg();Ag.exports=$k});var Ug=b(()=>{"use strict"});var Hg=b(()=>{"use strict"});var Qg=b((OB,jg)=>{"use strict";var Xk=Qe(),Jk=li(),Zk=Ae(),eR=Zk("match");jg.exports=function(a){var e;return Xk(a)&&((e=a[eR])!==void 0?!!e:Jk(a)==="RegExp")}});var Wg=b((_B,Gg)=>{"use strict";var tR=vt();Gg.exports=function(){var a=tR(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((BB,zg)=>{"use strict";var iR=je(),rR=ut(),aR=Er(),sR=Wg(),Yg=RegExp.prototype;zg.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Yg)&&!rR(a,"flags")&&aR(Yg,a)?iR(sR,a):e}});var Jg=b((NB,Xg)=>{"use strict";var zu=Ee(),nR=Oi(),oR=Math.floor,Wu=zu("".charAt),uR=zu("".replace),Yu=zu("".slice),lR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,cR=/\$([$&'`]|\d{1,2})/g;Xg.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=cR;return r!==void 0&&(r=nR(r),u=lR),uR(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=r[Yu(c,1,-1)];break;default:var m=+c;if(m===0)return l;if(m>o){var p=oR(m/10);return p===0?l:p<=o?i[p-1]===void 0?Wu(c,1):i[p-1]+Wu(c,1):l}d=i[m-1]}return d===void 0?"":d})}});var tv=b(()=>{"use strict";var dR=Te(),pR=je(),Xu=Ee(),Zg=Ht(),hR=fe(),mR=Ci(),fR=Qg(),nr=Zr(),bR=Pr(),gR=Kg(),vR=Jg(),SR=Ae(),yR=ot(),TR=SR("replace"),IR=TypeError,Ku=Xu("".indexOf),ER=Xu("".replace),ev=Xu("".slice),xR=Math.max;dR({target:"String",proto:!0},{replaceAll:function(e,t){var i=Zg(this),r,s,n,o,u,l,c,d,m,p,f=0,g="";if(!mR(e)){if(r=fR(e),r&&(s=nr(Zg(gR(e))),!~Ku(s,"g")))throw new IR("`.replaceAll` does not allow non-global regexes");if(n=bR(e,TR),n)return pR(n,e,i,t);if(yR&&r)return ER(nr(i),e,t)}for(o=nr(i),u=nr(e),l=hR(t),l||(t=nr(t)),c=u.length,d=xR(1,c),m=Ku(o,u);m!==-1;)p=l?nr(t(u,m,o)):vR(u,o,m,[],void 0,t),g+=ev(o,f,m)+p,f=m+c,m=m+d>o.length?-1:Ku(o,u,m+d);return f<o.length&&(g+=ev(o,f)),g}})});var rv=b((UB,iv)=>{"use strict";Ug();Hg();tv();var PR=jt();iv.exports=PR("String","replaceAll")});var sv=b((HB,av)=>{"use strict";var wR=rv();av.exports=wR});var ov=b((jB,nv)=>{"use strict";var AR=sv();nv.exports=AR});var lv=b((QB,uv)=>{"use strict";var kR=Rr(),RR=Zr(),LR=Ht(),$R=RangeError;uv.exports=function(e){var t=RR(LR(this)),i="",r=kR(e);if(r<0||r===1/0)throw new $R("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var mv=b((GB,hv)=>{"use strict";var pv=Ee(),MR=ao(),cv=Zr(),DR=lv(),CR=Ht(),VR=pv(DR),OR=pv("".slice),_R=Math.ceil,dv=function(a){return function(e,t,i){var r=cv(CR(e)),s=MR(t),n=r.length,o=i===void 0?" ":cv(i),u,l;return s<=n||o===""?r:(u=s-n,l=VR(o,_R(u/o.length)),l.length>u&&(l=OR(l,0,u)),a?r+l:l+r)}};hv.exports={start:dv(!1),end:dv(!0)}});var bv=b((WB,fv)=>{"use strict";var BR=di();fv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(BR)});var gv=b(()=>{"use strict";var NR=Te(),FR=mv().start,qR=bv();NR({target:"String",proto:!0,forced:qR},{padStart:function(e){return FR(this,e,arguments.length>1?arguments[1]:void 0)}})});var Sv=b((KB,vv)=>{"use strict";gv();var UR=jt();vv.exports=UR("String","padStart")});var Tv=b((XB,yv)=>{"use strict";var HR=Sv();yv.exports=HR});var Ev=b((JB,Iv)=>{"use strict";var jR=Tv();Iv.exports=jR});var cL={};VS(cL,{ChromecastState:()=>vr,HttpConnectionType:()=>ss,Observable:()=>Et.Observable,PlaybackState:()=>Oe,Player:()=>ja,PredefinedQualityLimits:()=>Sr,SDK_VERSION:()=>lL,Subject:()=>Et.Subject,Subscription:()=>Et.Subscription,Surface:()=>ns,VERSION:()=>kn,ValueSubject:()=>Et.ValueSubject,VideoFormat:()=>bt,VideoQuality:()=>Et.VideoQuality,clientChecker:()=>ee,isMobile:()=>er});module.exports=OS(cL);var kn="2.0.129-dev.e6caa27d.0";var Oe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Oe||{}),bt=(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))(bt||{});var vr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(vr||{}),ss=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ss||{});var ns=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ns||{}),Sr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Sr||{});var SS=G(Ke(),1);var Q=require("@vkontakte/videoplayer-shared/es2015");var ip=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ds=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 i=(0,Q.isNonNullable)((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||ip("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 i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(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),i=cast.framework.CastContext.getInstance();this.subscription.add((0,Q.fromEvent)(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,Q.assertNever)(r.sessionState)}})).add((0,Q.merge)((0,Q.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,Q.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,Q.map)(r=>r.castState)),(0,Q.observableFrom)([i.getCastState()])).pipe((0,Q.filterChanged)(),(0,Q.map)(aI),(0,Q.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=(0,Q.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=i.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(r==="CONNECTED"?(0,Q.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category: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 Sl=G(Ke(),1),nS=G(Hi(),1),oS=G(Do(),1);var eb=G(Ns(),1);var Su=require("@vkontakte/videoplayer-shared/es2015");var ke=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Su.assertNever)(t)}return a},Fs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:(0,Su.assertNever)(e)}};var L=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var St=require("@vkontakte/videoplayer-shared/es2015"),Y=class{constructor(e){this.transitionStarted$=new St.Subject;this.transitionEnded$=new St.Subject;this.transitionUpdated$=new St.Subject;this.forceChanged$=new St.Subject;this.stateChangeStarted$=(0,St.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,St.merge)(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||(0,St.isNonNullable)(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};var Xf=require("@vkontakte/videoplayer-shared/es2015"),Jf=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,Xf.assertNever)(a)}};var V=require("@vkontakte/videoplayer-shared/es2015");var pA=5,hA=5,mA=500,Zf=7e3,Hr=class{constructor(e){this.subscription=new V.Subscription;this.loadMediaTimeoutSubscription=new V.Subscription;this.videoState=new Y("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,V.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,V.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,V.assertNever)(e)}break}default:(0,V.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Jf(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 V.Subscription;this.subscription.add(e),this.subscription.add((0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,V.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new V.Subject;e.add(r.pipe((0,V.debounce)(mA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,V.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)&&r.next(o),s=o})),e.add((0,V.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,V.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,V.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,V.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<hA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(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,V.assertNever)(n)}}),t((0,V.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,V.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,V.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),L(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),L(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"),L(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"&&L(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];(0,V.assertNonNullable)(c);let d=(0,V.getHighestQuality)(Object.keys(c));(0,V.assertNonNullable)(d);let m=c[d];(0,V.assertNonNullable)(m),i=m,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,V.assertNonNullable)(c),i=c.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];(0,V.assertNonNullable)(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];(0,V.assertNonNullable)(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];(0,V.assertNonNullable)(c),i=ke(c.url),r="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:V.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,V.assertNever)(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,V.isNonNullable)(o)&&(n.metadata.title=o),(0,V.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,V.timeout)(Zf).subscribe(()=>s(`timeout(${Zf})`)))});(0,eb.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:V.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Vu=G(Ke(),1);var Eu=require("@vkontakte/videoplayer-shared/es2015");var tb=require("@vkontakte/videoplayer-shared/es2015"),ib=a=>{try{a.pause(),a.playbackRate=0,(0,tb.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var qs=require("@vkontakte/videoplayer-shared/es2015"),yu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Tu=window.WeakMap?new WeakMap:new yu,Iu=window.WeakMap?new WeakMap:new Map,fA=(a,e=20)=>{let t=0;return(0,qs.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},_e=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,Eu.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),Tu.set(i,r);let s=new qs.Subscription;return s.add(fA(i,e)),Iu.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Be=a=>{let e=Iu.get(a);e==null||e.unsubscribe(),Iu.delete(a);let t=Tu.get(a);Tu.delete(a),t?(0,Eu.clearVideoElement)(a):ib(a)};var xu=G(Zi(),1),O=require("@vkontakte/videoplayer-shared/es2015");var Gt=require("@vkontakte/videoplayer-shared/es2015"),Us=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Gt.isNullable)(r),l=new Gt.Subscription;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},yt=(a,e,t)=>Us(e,()=>a.loop,i=>{(0,Gt.isNonNullable)(i)&&(a.loop=i)},{onError:t}),Ne=(a,e,t,i)=>Us(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,Gt.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Xe=(a,e,t,i)=>Us(e,()=>a.playbackRate,r=>{(0,Gt.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Wt=Us;var TA=a=>["__",a.language,a.label].join("|"),IA=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Pu=class a{constructor(e){this.available$=new O.Subject;this.current$=new O.ValueSubject(void 0);this.error$=new O.Subject;this.subscription=new O.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:O.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Wt(t.internalTextTracks,()=>(0,xu.default)(this.internalTracks),s=>{(0,O.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,O.isNonNullable)(s)&&(0,O.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,O.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Wt(t.externalTextTracks,()=>(0,xu.default)(this.externalTracks),s=>{(0,O.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,O.isNonNullable)(s)&&(0,O.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,O.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Wt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Wt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,O.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,O.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,O.merge)((0,O.fromEvent)(e,"addtrack"),(0,O.fromEvent)(e,"removetrack"),(0,O.observableFrom)(["init"])).pipe((0,O.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,O.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,O.merge)((0,O.fromEvent)(e,"change"),(0,O.observableFrom)(["init"])).pipe((0,O.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,O.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,O.filterChanged)()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add((0,O.fromEvent)(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,m,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((m=(d=o.target)==null?void 0:d.cues)!=null?m:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add((0,O.fromEvent)(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;(0,O.isNonNullable)(t.align)&&(r.align=t.align),(0,O.isNonNullable)(t.position)&&(r.position=t.position),(0,O.isNonNullable)(t.size)&&(r.size=t.size),(0,O.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,O.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:i}=e,r=e.id?e.id:TA(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,O.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,O.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,O.assertNonNullable)(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){(0,O.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Je=Pu;var vi=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 lb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},wu=a=>{let e=lb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},cb=a=>{let e=lb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var R=require("@vkontakte/videoplayer-shared/es2015");var EA=3,db=(a,e,t=EA)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Hs=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var pb=G(Ke(),1);var er=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var js=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,pb.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=er()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return A(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Qs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var ct=()=>window.ManagedMediaSource||window.MediaSource,Gs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},hb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},mb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var xA=document.createElement("video"),PA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',wA='video/mp4; codecs="hev1.1.6.L93.B0"',fb='video/webm; codecs="vp09.00.10.08"',bb='video/webm; codecs="av01.0.00M.08"',AA='audio/mp4; codecs="mp4a.40.2"',kA='audio/webm; codecs="opus"',gb,RA=()=>A(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(j($({},a),{video:j($({},a.video),{contentType:bb})})),window.navigator.mediaCapabilities.decodingInfo(j($({},a),{video:j($({},a.video),{contentType:fb})}))]);gb={DASH_WEBM_AV1:e,DASH_WEBM:t}});RA().catch(a=>{console.log(xA),console.error(a)});var Ws=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return gb}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,m,p,f,g,S,y,I,x,w;this._video=document.createElement("video");try{this._protocols={mms:Gs(),mse:hb(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let P=!!((c=(l=ct())==null?void 0:l.isTypeSupported)!=null&&c.call(l,PA)),B=!!((m=(d=ct())==null?void 0:d.isTypeSupported)!=null&&m.call(d,wA)),H=!!((f=(p=ct())==null?void 0:p.isTypeSupported)!=null&&f.call(p,AA));this._codecs={h264:P,h265:B,vp9:!!((S=(g=ct())==null?void 0:g.isTypeSupported)!=null&&S.call(g,fb)),av1:!!((I=(y=ct())==null?void 0:y.isTypeSupported)!=null&&I.call(y,bb)),aac:H,opus:!!((w=(x=ct())==null?void 0:x.isTypeSupported)!=null&&w.call(x,kA)),mpeg:(P||B)&&H},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(P){console.error(P)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var vb="audio/mpeg",Ys=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,vb))},this._codecs={mp3:!!((r=(i=ct())==null?void 0:i.isTypeSupported)!=null&&r.call(i,vb))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};var Sb=require("@vkontakte/videoplayer-shared/es2015");var Au=class{constructor(){this.isInited$=new Sb.ValueSubject(!1);this._displayChecker=new Qs,this._deviceChecker=new js(this._displayChecker),this._browserChecker=new Hs,this._videoChecker=new Ws(this._deviceChecker,this._browserChecker),this._audioChecker=new Ys,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return A(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},ee=new Au;var Fe=a=>{let e=D=>(0,R.fromEvent)(a,D).pipe((0,R.mapTo)(void 0)),t=new R.Subscription,i=()=>t.unsubscribe(),s=(0,R.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(D=>(0,R.fromEvent)(a,D))).pipe((0,R.map)(D=>D.type==="ended"?a.readyState<2:a.readyState<3),(0,R.filterChanged)()),n=(0,R.merge)((0,R.fromEvent)(a,"progress"),(0,R.fromEvent)(a,"timeupdate")).pipe((0,R.map)(()=>db(a.buffered,a.currentTime))),o=ee.browser.isSafari?(0,R.combine)({play:e("play").pipe((0,R.once)()),playing:e("playing")}).pipe((0,R.mapTo)(void 0)):e("playing"),u=(0,R.fromEvent)(a,"volumechange").pipe((0,R.map)(()=>({muted:a.muted,volume:a.volume}))),l=(0,R.fromEvent)(a,"ratechange").pipe((0,R.map)(()=>a.playbackRate)),c=(0,R.fromEvent)(a,"error").pipe((0,R.filter)(()=>!!(a.error||a.played.length)),(0,R.map)(()=>{var N;let D=a.error;return{id:D?`MediaError#${D.code}`:"HtmlVideoError",category:R.ErrorCategory.VIDEO_PIPELINE,message:D?D.message:"Error event from HTML video element",thrown:(N=a.error)!=null?N:void 0}})),d=(0,R.fromEvent)(a,"timeupdate").pipe((0,R.map)(()=>a.currentTime)),m=new R.Subject,p=.3,f;t.add(d.subscribe(D=>{a.loop&&(0,R.isNonNullable)(f)&&(0,R.isNonNullable)(D)&&f>=a.duration-p&&D<=p&&m.next(f),f=D}));let g=e("pause").pipe((0,R.filter)(()=>!a.error&&f!==a.duration)),S=(0,R.fromEvent)(a,"enterpictureinpicture"),y=(0,R.fromEvent)(a,"leavepictureinpicture"),I=new R.ValueSubject(cb(a));t.add(S.subscribe(()=>I.next(!0))),t.add(y.subscribe(()=>I.next(!1)));let x=new R.ValueSubject(wu(a)),w=(0,R.fromEvent)(a,"fullscreenchange");t.add(w.pipe((0,R.map)(()=>wu(a))).subscribe(x));let P=.1,B=1e3,H=(0,R.fromEvent)(a,"timeupdate").pipe((0,R.filter)(D=>a.duration-a.currentTime<P)),se=(0,R.merge)(H.pipe((0,R.filter)(D=>!a.loop)),(0,R.fromEvent)(a,"ended")).pipe((0,R.throttle)(B),(0,R.mapTo)(void 0)),Z=H.pipe((0,R.filter)(D=>a.loop));return{playing$:o,pause$:g,canplay$:e("canplay"),ended$:se,looped$:m,loopExpected$:Z,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:(0,R.fromEvent)(a,"durationchange").pipe((0,R.map)(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:I,inFullscreen$:x,enterPip$:S,leavePip$:y,destroy:i}};var kt=require("@vkontakte/videoplayer-shared/es2015"),Yt=a=>{switch(a){case"mobile":return kt.VideoQuality.Q_144P;case"lowest":return kt.VideoQuality.Q_240P;case"low":return kt.VideoQuality.Q_360P;case"sd":case"medium":return kt.VideoQuality.Q_480P;case"hd":case"high":return kt.VideoQuality.Q_720P;case"fullhd":case"full":return kt.VideoQuality.Q_1080P;case"quadhd":case"quad":return kt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return kt.VideoQuality.Q_2160P}};var Kt=G(zt(),1),kb=G(Ke(),1),zs=G(Hi(),1),F=require("@vkontakte/videoplayer-shared/es2015");var Ie=require("@vkontakte/videoplayer-shared/es2015");function ku({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Ru({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&ku({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function jr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return(0,Ie.isNullable)(a)||(0,Ie.isNonNullable)(a.min)&&(0,Ie.isNonNullable)(a.max)&&(0,Ie.isLower)(a.max,a.min)||(0,Ie.isNonNullable)(a.min)&&e&&(0,Ie.isHigher)(a.min,e)||(0,Ie.isNonNullable)(a.max)&&t&&(0,Ie.isLower)(a.max,t)}function wb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return jr({limits:{max:a!=null&&a.max?(0,Ie.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,Ie.videoHeightToQuality)(a.min):void 0},highestAvailableQuality:e?(0,Ie.videoHeightToQuality)(e):void 0,lowestAvailableQuality:t?(0,Ie.videoHeightToQuality)(t):void 0})}var Rb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Lu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Qr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,F.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Lb='Assertion "ABR Tracks is empty array" failed',Ks=(a,e,t,i)=>{var u;let r=[...e].sort(Lu(1)),s=[...t].sort(Lu(1)),n=s.filter(l=>(0,F.isNonNullable)(l.bitrate)&&(0,F.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Kt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Kt.default)(s,-1);return o&&(0,kb.default)(n,o)?o:n.length?(0,Kt.default)(n,-1):(0,Kt.default)(s,0)},Ab=a=>"quality"in a,$b=(a,e,t,i)=>{var n;let r=(0,F.isNonNullable)((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&(0,F.isNonNullable)(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,F.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Ab(o)?"video":"audio",l=Ab(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},BA=(a,e)=>Math.log(e)/Math.log(a),NA=({tuning:a,container:e,limits:t})=>{let i=a.containerSizeFactor;if(a.usePixelRatio&&ee.display.pixelRatio){let r=ee.display.pixelRatio;if(a.pixelRatioMultiplier)i*=a.pixelRatioMultiplier*(r-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=BA(s,n*r+o)+u;Number.isFinite(l)&&(i*=l)}}return Ru({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(i*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*i,height:e.height*i}:void 0,containerSizeFactor:i}},Xt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:m,stallsPredictedThroughput:p,abrLogger:f})=>{var ne,ue,Le,C,K;(0,F.assertNotEmptyArray)(a,Lb);let{containerSizeFactor:g,containerSizeLimit:S}=NA({container:e,tuning:i,limits:r}),y=i.considerPlaybackRate&&(0,F.isNonNullable)(o)?o:1,I=a.filter(k=>!(0,F.isInvariantQuality)(k.quality)).sort((k,J)=>(0,F.isHigher)(k.quality,J.quality)?-1:1),x=(ne=(0,Kt.default)(I,-1))==null?void 0:ne.quality,w=(ue=(0,Kt.default)(I,0))==null?void 0:ue.quality,P=jr({limits:r,lowestAvailableQuality:x,highestAvailableQuality:w}),B=y*Rb(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),H={},Z=I.filter(k=>{let J=!0;if(S)if(k.size)J=k.size.width<=S.width&&k.size.height<=S.height;else{let it=S&&(0,F.videoSizeToQuality)(S);J=it?(0,F.isLowerOrEqual)(k.quality,it):!0}if(!J)return H[k.quality]="FitsContainer",!1;let W=p||t,tt=(0,F.isNonNullable)(W)&&isFinite(W)&&(0,F.isNonNullable)(k.bitrate)?W-s>=k.bitrate*B:!0,Vt=Ru({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&(r==null?void 0:r.min)===k.quality;if(!tt&&!Vt)return H[k.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,F.isNonNullable)(i.minBufferToSwitchUp)&&u&&!(0,F.isInvariantQuality)(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&(0,F.isHigher)(k.quality,u.quality))return H[k.quality]="Buffer",!1;if(!!d&&(0,F.isHigherOrEqual)(k.quality,d)&&!Vt)return H[k.quality]="DroppedFramesLimit",!1;if(!!m&&(0,F.isHigherOrEqual)(k.quality,m)&&!Vt)return H[k.quality]="StallsLimit",!1;let Me=P||((0,F.isNullable)(r==null?void 0:r.max)||(0,F.isLowerOrEqual)(k.quality,r.max))&&((0,F.isNullable)(r==null?void 0:r.min)||(0,F.isHigherOrEqual)(k.quality,r.min)),Ve=(0,F.isNonNullable)(c)&&!c?(0,F.isLowerOrEqual)(k.quality,i.backgroundVideoQualityLimit):!0;return!Me||!Ve?(H[k.quality]="FitsQualityLimits",!1):!0})[0],D=(Le=Z!=null?Z:(0,Kt.default)(I,-1))!=null?Le:a[0],N=l==null?void 0:l.last,M=$b(i,f,D,l);return(0,F.isNonNullable)(l)&&M.quality!==(N==null?void 0:N.quality)&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(
|
|
12
|
+
${a.map(k=>{var J,W;return`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate}, size: ${(J=k.size)==null?void 0:J.width}:${(W=k.size)==null?void 0:W.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,zs.default)(i!=null?i:{}).map(([k,J])=>`${k}: ${J}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${g},
|
|
21
|
-
containerSizeLimit: ${(
|
|
21
|
+
containerSizeLimit: ${(C=S==null?void 0:S.width)!=null?C:0} x ${(K=S==null?void 0:S.height)!=null?K:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
|
-
stallsPredictedThroughput: ${
|
|
23
|
+
stallsPredictedThroughput: ${p},
|
|
24
24
|
reserve: ${s},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${y},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
29
|
-
minBufferToSwitchUp: ${
|
|
28
|
+
bitrateFactor: ${B},
|
|
29
|
+
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
30
|
droppedVideoMaxQualityLimit: ${d},
|
|
31
|
-
stallsVideoMaxQualityLimit: ${
|
|
32
|
-
limitsAreInvalid: ${
|
|
33
|
-
maxQualityLimit: ${
|
|
34
|
-
minQualityLimit: ${
|
|
31
|
+
stallsVideoMaxQualityLimit: ${m},
|
|
32
|
+
limitsAreInvalid: ${P},
|
|
33
|
+
maxQualityLimit: ${r==null?void 0:r.max},
|
|
34
|
+
minQualityLimit: ${r==null?void 0:r.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,zs.default)(H).map(([k,J])=>`${k}: ${J}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${Z==null?void 0:Z.quality}
|
|
41
|
+
[selected video track] ${M==null?void 0:M.quality}
|
|
42
|
+
`}),M},Mb=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,F.assertNotEmptyArray)(t,Lb);let c=r.considerPlaybackRate&&(0,F.isNonNullable)(s)?s:1,d=[...t].sort(Lu(-1)),m=a.bitrate;(0,F.assertNonNullable)(m);let p=c*Rb(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,g=Ks(a,e,t,r.minVideoAudioRatio),S=l||i;(0,F.isNonNullable)(S)&&isFinite(S)&&(f=d.find(x=>(0,F.isNonNullable)(x.bitrate)&&(0,F.isNonNullable)(g==null?void 0:g.bitrate)?S-m>=x.bitrate*p&&x.bitrate>=g.bitrate:!1)),f||(f=g);let y=o==null?void 0:o.last,I=f&&$b(r,u,f,o);return(0,F.isNonNullable)(o)&&(I==null?void 0:I.bitrate)!==(y==null?void 0:y.bitrate)&&u({message:`
|
|
43
43
|
[AUDIO TRACKS ABR]
|
|
44
44
|
[available audio tracks]
|
|
45
|
-
${t.map(
|
|
45
|
+
${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,zs.default)(r!=null?r:{}).map(([x,w])=>`${x}: ${w}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
|
-
estimatedThroughput: ${
|
|
53
|
+
estimatedThroughput: ${i},
|
|
54
54
|
stallsPredictedThroughput: ${l},
|
|
55
|
-
reserve: ${
|
|
55
|
+
reserve: ${m},
|
|
56
56
|
playbackRate: ${s},
|
|
57
57
|
playbackRateFactor: ${c},
|
|
58
58
|
forwardBufferHealth: ${n},
|
|
59
|
-
bitrateFactor: ${
|
|
60
|
-
minBufferToSwitchUp: ${
|
|
59
|
+
bitrateFactor: ${p},
|
|
60
|
+
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
61
61
|
|
|
62
|
-
[selected audio track] ${
|
|
63
|
-
`}),f&&qb(i,u,f,o)};var xe=a=>new URL(a).hostname;var V=require("@vkontakte/videoplayer-shared/es2015");var Yb=Q(yr(),1);var jb=Q(Be(),1);var Hb=a=>{if(a instanceof DOMException&&(0,jb.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"))},He=(a,e)=>k(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Hb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Hb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});var Ke=require("@vkontakte/videoplayer-shared/es2015");var Qb=Q(ti(),1),Tt=require("@vkontakte/videoplayer-shared/es2015");function Pe(){return(0,Tt.now)()}function Ou(a){return Pe()-a}function Bu(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 Gb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ii(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,m="arraybuffer",f=7e3,g=2e3,v=()=>{if(u)return;(0,Tt.assertNonNullable)(c);let B=Ou(c),ie;if(B<g){ie=g-B,setTimeout(v,ie);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new i,_()},T=B=>(s=B,re),I=B=>(d=B,re),x=()=>(m="json",re),w=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},A=B=>(h=B,re),_=()=>{c=Pe(),n=new i,n.open("get",a);let B=0,ie,J=0,oe=()=>((0,Tt.assertNonNullable)(c),Math.max(c,Math.max(ie||0,J||0)));if(s&&n.addEventListener("progress",R=>{let P=Pe();s.updateChunk&&R.loaded>B&&(s.updateChunk(oe(),R.loaded-B),B=R.loaded,ie=P)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;(0,Tt.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){let{response:P,responseType:W}=n,se=P==null?void 0:P.byteLength;if(typeof se=="number"&&s){let Z=se-B;Z&&s.updateChunk&&s.updateChunk(oe(),Z)}W==="json"&&(!P||!(0,Qb.default)(P).length)?w():(d&&d(),e(P))}else w()}),n.addEventListener("error",()=>{w()}),h){let R=()=>{(0,Tt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(J=Pe(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=m,n.send(),re},re={withBitrateReporting:T,withParallel:A,withJSONResponse:x,withRetryCount:B=>(l=B,re),withRetryInterval:(B,ie)=>((0,Tt.isNonNullable)(B)&&(g=B),(0,Tt.isNonNullable)(ie)&&(f=ie),re),withTimeout:B=>(o=B,re),withFinally:I,send:_,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return re}var Ki=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 Wb=Q(ti(),1);var Xi=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=Pe(),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=Pe()-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=ii(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=Pe()}_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=Pe();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,Wb.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 zb=require("@vkontakte/videoplayer-shared/es2015");var tn=1e4,Nu=3;var ZA=6e4,ek=10,tk=1,rk=500,Ji=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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 zb.Subject,this.chunkRateEstimator=new Ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Bu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=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=Bu(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*(z.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!_b({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Yb.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(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,Ke.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=()=>{Gb(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 Xi(Nu,tn,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,_)=>{u&&u.abort(),u=ii(this.urlResolver.resolve(w,!1),A,_,()=>this._retryCallback()).withTimeout(tn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Nu).withFinally(()=>{u=null}).send()},m=(w,A,_)=>{(0,Ke.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),A,_,()=>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 _=Pe()-1e4,q=0;for(let j=0;j<this.bufferStates.length;j++){let te=this.bufferStates[j];w=Math.min(w,te.buf),te.ts<_&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${w} drop=${q} jitter=${this.sourceJitter}`);let pe=w-tk;this.sourceJitter>=0?pe-=this.sourceJitter/2:this.sourceJitter-=1,pe>3?f(1.15):pe>1?f(1.1):pe>.3?f(1.05):f(1)}},T=w=>{let A,_=()=>A&&A.start?A.start.length:0,q=R=>A.start[R]/1e3,pe=R=>A.dur[R]/1e3,j=R=>A.fragIndex+R,te=(R,P)=>({chunkIdx:j(R),startTS:q(R),dur:pe(R),discontinuity:P}),re=()=>{let R=0;if(A&&A.dur){let P=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,se=P;this.sourceJitter>1&&(se+=this.sourceJitter-1);let Z=A.dur.length-1;for(;Z>=0&&(se-=A.dur[Z],!(se<=0));--Z);R=Math.min(Z,A.dur.length-1-W),R=Math.max(R,0)}return te(R,!0)},B=R=>{let P=_();if(!(P<=0)){if((0,Ke.isNonNullable)(R)){for(let W=0;W<P;W++)if(q(W)>R)return te(W)}return re()}},ie=R=>{let P=_(),W=R?R.chunkIdx+1:0,se=W-A.fragIndex;if(!(P<=0)){if(!R||se<0||se-P>ek)return t(`Resync: offset=${se} bChunks=${P} chunk=`+JSON.stringify(R)),re();if(!(se>=P))return te(W-A.fragIndex,!1)}},J=(R,P,W)=>{l&&l.abort(),l=ii(this.urlResolver.resolve(R,!0,this.lowLatency),P,W,()=>this._retryCallback()).withTimeout(tn).withRetryCount(Nu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,P)=>{J(w,W=>{if(!d())return;A=W;let se=!!A.lowLatency;se!==this.lowLatency&&g(se);let Z=0;for(let Qe=0;Qe<A.dur.length;++Qe)Z+=A.dur[Qe];Z>0&&((0,Ke.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/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,R(B(P))},()=>this._handleNetworkError())},nextChunk:ie}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ke.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{let{videoElement:A,logger:_}=this.params,q=T(e.jidxUrl),pe,j,te,re,B=0,ie,J,oe,R=()=>{ie&&(clearTimeout(ie),ie=void 0);let ne=Math.max(rk,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),we=B+ne,Re=Pe(),Me=Math.min(1e4,we-Re);B=Re;let Ot=()=>{l||d()&&q.seek(()=>{d()&&(B=Pe(),P(),R())})};Me>0?ie=window.setTimeout(()=>{this.paused?R():Ot()},Me):Ot()},P=()=>{let ne;for(;ne=q.nextChunk(re);)re=ne,pi(ne);let we=q.nextChunk(te);if(we){if(te&&we.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?R():(I(),this._initPlayerWith(e));return}Qe(we)}else R()},W=(ne,we)=>{if(!d()||!this.sourceBuffer)return;let Re,Me,Ot,kr=Bt=>{window.setTimeout(()=>{d()&&W(ne,we)},Bt)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),kr(100);else{let Bt=Pe(),ir=A.currentTime;!this.paused&&A.buffered.length>1&&J===ir&&Bt-oe>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),J!==ir&&(J=ir,oe=Bt);let Lr=this._getBufferSizeSec();if(Lr>30)_(`Buffered ${Lr} seconds; delaying appendBuffer`),kr(2e3);else try{this.sourceBuffer.appendBuffer(ne),this.videoPlayStarted?(this.bufferStates.push({ts:Bt,buf:Lr}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),we&&we()}catch(hi){if(hi.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),Ot=this.sourceBuffer.buffered.length,Ot!==0&&(Re=this.sourceBuffer.buffered.start(0),Me=ir,Me-Re>4&&this.sourceBuffer.remove(Re,Me-3)),kr(1e3);else throw hi}}},se=()=>{j&&pe&&(_([`Appending chunk, sz=${j.byteLength}:`,JSON.stringify(te)]),W(j,function(){j=null,P()}))},Z=ne=>e.fragUrlTemplate.replace("%%id%%",ne.chunkIdx),Qe=ne=>{d()&&m(Z(ne),(we,Re)=>{if(d()){if(Re/=1e3,j=we,te=ne,n=ne.startTS,Re){let Me=Math.min(10,ne.dur/Re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Me:Me}se()}},()=>this._handleNetworkError())},pi=ne=>{d()&&((0,Ke.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(ne),!1)))},Ar=ne=>{d()&&(e.cachedHeader=ne,W(ne,()=>{pe=!0,se()}))};s=!0,q.seek(ne=>{if(d()){if(B=Pe(),!ne){R();return}re=ne,!(0,Ke.isNullable)(w)||ne.startTS>w?Qe(ne):(te=ne,P())}},w),e.cachedHeader?Ar(e.cachedHeader):h(e.headerUrl,Ar,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ke.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,Ke.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ke.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(m=this._getBufferSizeSec(),f=d/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; 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,m)=>{let f=Pe();if(this.chunkRateEstimator.addInterval(h,f,m)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,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&&Ou(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let m=s.updateChunk(d,h);return m&&l(),m},notifySwitch:d=>{let h=Pe();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ii(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(tn).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;He(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)=>{var c,d;u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,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))},ZA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Kb=Q(Qr(),1),fe=require("@vkontakte/videoplayer-shared/es2015"),Fu=class{constructor(){this.onDroopedVideoFramesLimit$=new fe.Subject;this.subscription=new fe.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new fe.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,fe.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,fe.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,fe.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,fe.interval)(this.droppedFramesChecker.checkTime).pipe((0,fe.filter)(()=>this.playing),(0,fe.filter)(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,fe.debounce)(this.droppedFramesChecker.checkTime)),r=(0,fe.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,Kb.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,fe.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}},rn=Fu;var an=require("@vkontakte/videoplayer-shared/es2015"),Xb=require("@vkontakte/videoplayer-shared/es2015");var Zi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var ik=(a,e)=>new an.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Zi()))},L(L({},r),e));i.observe(a);let s=(0,Xb.fromEvent)(document,"visibilitychange").pipe((0,an.map)(n=>!document.hidden||Zi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),tt=ik;var ak=["paused","playing","ready"],sk=["paused","playing","ready"],ea=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new Y("stopped");this.representations$=new V.ValueSubject([]);this.droppedFramesManager=new rn;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new Sr;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=L({},u.video);if(!c)continue;let m={id:l,quality:c,bitrate:d,size:h};o.push({track:m,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,qu.default)(sk,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,qu.default)(ak,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Le(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(Le(this.params.source.url,u))}return;default:return(0,V.assertNever)(e)}};this.textTracksManager=new et(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:V.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,V.merge)(this.videoState.stateChangeStarted$.pipe((0,V.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,V.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Ne(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(xe(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=Ue(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(yt(this.video,this.params.desiredState.isLooped,t)).add(qe(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(tt(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&(0,V.videoQualityToHeight)(i),min:s&&(0,V.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:i,min:s})})).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),Fe(this.video)}createLiveDashPlayer(){let e=new Ji({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,m,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:Jt(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(m=this.params.desiredState.videoTrack.getState())==null?void 0:m.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(Le(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Jb=ea;var uS=Q(Be(),1);var It=(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 H=require("@vkontakte/videoplayer-shared/es2015");var sn=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}},ai=class extends sn{constructor(){super(),this.listeners||sn.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)}},ta=class{constructor(){Object.defineProperty(this,"signal",{value:new ai,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&&(ta.prototype[Symbol.toStringTag]="AbortController",ai.prototype[Symbol.toStringTag]="AbortSignal");function nn(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 Uu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!nn({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(m){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((m,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 ra=nn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Zb=ra?Uu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Et=ra?Zb.fetch:window.fetch,GV=ra?Zb.Request:window.Request,$e=ra?ta:window.AbortController,WV=ra?ai:window.AbortSignal;var aS=Q(Be(),1),Sl=Q(ju(),1);var Ng=Q(Bg(),1),si=require("@vkontakte/videoplayer-shared/es2015"),Fg=a=>{if(!a)return{id:"EmptyResponse",category:si.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:si.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,Ng.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:si.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:si.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:si.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var 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 on=Q(Be(),1),ui=Q(yr(),1),un=Q(ju(),1);var jk=(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)},Qk=a=>window.clearTimeout(a),qg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Ug=!qg(window.requestIdleCallback)||!qg(window.cancelIdleCallback),zu=Ug?jk:window.requestIdleCallback,aa=Ug?Qk:window.cancelIdleCallback;var Yv=Q(Hs(),1);var er=require("@vkontakte/videoplayer-shared/es2015");var Gk=18,Hg=!1;try{Hg=z.browser.isSafari&&!!z.browser.safariVersion&&z.browser.safariVersion<=Gk}catch(a){console.error(a)}var Ku=class{constructor(e){this.bufferFull$=new er.Subject;this.error$=new er.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:er.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return k(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return k(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return k(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};Hg&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:er.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,er.assertNever)(t)}}},jg=Ku;var Xu=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 ee=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)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ni=class extends ee{};var sa=class extends ee{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 na=class extends ee{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 oa=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ce=class extends ee{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ua=class extends ce{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 la=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ca=class extends ee{constructor(e,t){super(e,t),this.data=this.content}};var Tr=class extends ce{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 da=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends ce{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 ma=class extends ce{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var fa=class extends ce{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ba=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends ce{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 va=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends ce{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ta=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends ce{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 Ea=class extends ce{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 xa=class extends ce{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 Pa=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends ce{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Aa=class extends ee{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Yk={ftyp:na,moov:oa,mvhd:ua,moof:la,mdat:ca,sidx:Tr,trak:da,mdia:ba,mfhd:ya,tkhd:ga,traf:Ta,tfhd:Ia,tfdt:Ea,trun:xa,minf:va,sv3d:pa,st3d:ha,prhd:ma,proj:Sa,equi:fa,uuid:sa,stbl:Pa,stsd:wa,avc1:Aa,unknown:ni},Rt=class a{constructor(e={}){this.options=L({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=Yk[e];return r?new r(t,new a):new ni(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 Kk=new TextDecoder("ascii"),Xk=a=>Kk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Jk=a=>{let e=new Tr(a,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Zk=(a,e)=>{let r=new Rt().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)},eL=a=>{let t=new Rt().parse(a),r=new tr(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},tL=a=>{var i;let t=new Rt().parse(a);return(i=new tr(t).find("sidx"))==null?void 0:i.timescale},rL=(a,e)=>{let r=new Rt().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},iL=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Rt().parse(a),i=new 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},Qg={validateData:Xk,parseInit:iL,getIndexRange:()=>{},parseSegments:Jk,parseFeedableSegmentChunk:Zk,getChunkEndTime:rL,getServerLatencyTimestamps:eL,getTimescaleFromIndex:tL};var La=Q(Be(),1),Mt=require("@vkontakte/videoplayer-shared/es2015");var Wg=require("@vkontakte/videoplayer-shared/es2015");var Gg={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"}},Yg=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=ka(a,t),i=r in Gg,s=i?Gg[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=ka(u),d=l*ft(2,(o-1)*8)+c,h=t+o,m;return h+d>a.byteLength?m=new DataView(a.buffer,a.byteOffset+h):m=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:m,valueSize:d}},ka=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*ft(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*ft(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*ft(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},dt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ka(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,Wg.assertNever)(e)}},Ir=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Yg(r);if(!e(i))return;i.type==="master"&&Ir(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},zg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Yg(a);return Ir(i.value,({tag:s,type:n,value:o})=>(s===17143?e=dt(o,n):s===17026?t=dt(o,n):s===17029&&(r=dt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Kg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],aL=[231,22612,22743,167,171,163,160,175],sL=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Ir(a,({tag:h,type:m,value:f,valueSize:g})=>{if(h===21419){let v=dt(f,m);l=ka(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=dt(f,m):h===17545?i=dt(f,m):h===21420&&l===475249515?u=dt(f,m):h===374648427?Ir(f,({tag:v,type:T,value:I})=>v===30321?(c=dt(I,T)===1,!1):!0):s&&n&&(0,La.default)(Kg,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}}}},nL=a=>{if((0,Mt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},oL=(a,e)=>{let t=!1,r=!1,i=o=>(0,Mt.isNonNullable)(o.time)&&(0,Mt.isNonNullable)(o.position),s=[],n;return Ir(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=dt(l,u));break;case 183:break;case 241:n&&(n.position=dt(l,u));break;default:t&&(0,La.default)(Kg,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}}})},uL=a=>{let e=0,t=!1;try{Ir(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,La.default)(aL,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,La.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},Xg={validateData:zg,parseInit:sL,getIndexRange:nL,parseSegments:oL,parseFeedableSegmentChunk:uL};var $a=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Xg;case"mp4":return Qg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var cl=Q(gv(),1),Hv=Q(Qr(),1),jv=Q(Cv(),1),Qv=Q(yr(),1),dl=Q(ti(),1);var Dv=Q(Be(),1),al=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,Dv.default)(["6E","7A","F4"],o)}}return!1};var Ma=require("@vkontakte/videoplayer-shared/es2015");var Vv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var _v=a=>{var e;try{let t=i$(),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 i$(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
62
|
+
[selected audio track] ${I==null?void 0:I.id}
|
|
63
|
+
`}),I};var xe=a=>new URL(a).hostname;var _=require("@vkontakte/videoplayer-shared/es2015");var Bb=G(zt(),1);var Cb=G(Ke(),1);var Db=a=>{if(a instanceof DOMException&&(0,Cb.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"))},qe=(a,e)=>A(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!Db(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return Db(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});var We=require("@vkontakte/videoplayer-shared/es2015");var Vb=G(Zi(),1),Tt=require("@vkontakte/videoplayer-shared/es2015");function Pe(){return(0,Tt.now)()}function $u(a){return Pe()-a}function Mu(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ob(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function tr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,m=!1,p="arraybuffer",f=7e3,g=2e3,S=()=>{if(u)return;(0,Tt.assertNonNullable)(c);let M=$u(c),ne;if(M<g){ne=g-M,setTimeout(S,ne);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new r,B()},y=M=>(s=M,N),I=M=>(d=M,N),x=()=>(p="json",N),w=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,d&&d(),t&&t()}},P=M=>(m=M,N),B=()=>{c=Pe(),n=new r,n.open("get",a);let M=0,ne,ue=0,Le=()=>((0,Tt.assertNonNullable)(c),Math.max(c,Math.max(ne||0,ue||0)));if(s&&n.addEventListener("progress",C=>{let K=Pe();s.updateChunk&&C.loaded>M&&(s.updateChunk(Le(),C.loaded-M),M=C.loaded,ne=K)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;(0,Tt.assertNonNullable)(n);let C=n.status;if(C>=200&&C<300){let{response:K,responseType:k}=n,J=K==null?void 0:K.byteLength;if(typeof J=="number"&&s){let W=J-M;W&&s.updateChunk&&s.updateChunk(Le(),W)}k==="json"&&(!K||!(0,Vb.default)(K).length)?w():(d&&d(),e(K))}else w()}),n.addEventListener("error",()=>{w()}),m){let C=()=>{(0,Tt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ue=Pe(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=p,n.send(),N},N={withBitrateReporting:y,withParallel:P,withJSONResponse:x,withRetryCount:M=>(l=M,N),withRetryInterval:(M,ne)=>((0,Tt.isNonNullable)(M)&&(g=M),(0,Tt.isNonNullable)(ne)&&(f=ne),N),withTimeout:M=>(o=M,N),withFinally:I,send:B,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return N}var Gr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var _b=G(Zi(),1);var Wr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Pe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=Pe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=tr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Pe()}_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=Pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,_b.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Nb=require("@vkontakte/videoplayer-shared/es2015");var Xs=1e4,Du=3;var qA=6e4,UA=10,HA=1,jA=500,Yr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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 Nb.Subject,this.chunkRateEstimator=new Gr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Mu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Mu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(ee.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!wb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Bb.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,We.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ob(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Wr(Du,Xs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let w=s&&(!c||c===this.rep);return w||t("Not running!"),w},m=(w,P,B)=>{u&&u.abort(),u=tr(this.urlResolver.resolve(w,!1),P,B,()=>this._retryCallback()).withTimeout(Xs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Du).withFinally(()=>{u=null}).send()},p=(w,P,B)=>{(0,We.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),P,B,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=w=>{let P=i.playbackRate;i.playbackRate!==w&&(t(`Playback rate switch: ${P}=>${w}`),i.playbackRate=w)},g=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let B=Pe()-1e4,H=0;for(let Z=0;Z<this.bufferStates.length;Z++){let D=this.bufferStates[Z];w=Math.min(w,D.buf),D.ts<B&&H++}this.bufferStates.splice(0,H),t(`update playback rate; minBuffer=${w} drop=${H} jitter=${this.sourceJitter}`);let se=w-HA;this.sourceJitter>=0?se-=this.sourceJitter/2:this.sourceJitter-=1,se>3?f(1.15):se>1?f(1.1):se>.3?f(1.05):f(1)}},y=w=>{let P,B=()=>P&&P.start?P.start.length:0,H=C=>P.start[C]/1e3,se=C=>P.dur[C]/1e3,Z=C=>P.fragIndex+C,D=(C,K)=>({chunkIdx:Z(C),startTS:H(C),dur:se(C),discontinuity:K}),N=()=>{let C=0;if(P&&P.dur){let K=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,k=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=K;this.sourceJitter>1&&(J+=this.sourceJitter-1);let W=P.dur.length-1;for(;W>=0&&(J-=P.dur[W],!(J<=0));--W);C=Math.min(W,P.dur.length-1-k),C=Math.max(C,0)}return D(C,!0)},M=C=>{let K=B();if(!(K<=0)){if((0,We.isNonNullable)(C)){for(let k=0;k<K;k++)if(H(k)>C)return D(k)}return N()}},ne=C=>{let K=B(),k=C?C.chunkIdx+1:0,J=k-P.fragIndex;if(!(K<=0)){if(!C||J<0||J-K>UA)return t(`Resync: offset=${J} bChunks=${K} chunk=`+JSON.stringify(C)),N();if(!(J>=K))return D(k-P.fragIndex,!1)}},ue=(C,K,k)=>{l&&l.abort(),l=tr(this.urlResolver.resolve(C,!0,this.lowLatency),K,k,()=>this._retryCallback()).withTimeout(Xs).withRetryCount(Du).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(C,K)=>{ue(w,k=>{if(!d())return;P=k;let J=!!P.lowLatency;J!==this.lowLatency&&g(J);let W=0;for(let tt=0;tt<P.dur.length;++tt)W+=P.dur[tt];W>0&&((0,We.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(W/P.dur.length)),r({name:"index",zeroTime:P.zeroTime,shiftDuration:P.shiftDuration}),this.sourceJitter=P.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,P.jitter/1e3)):1,C(M(K))},()=>this._handleNetworkError())},nextChunk:ne}},I=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,We.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{let{videoElement:P,logger:B}=this.params,H=y(e.jidxUrl),se,Z,D,N,M=0,ne,ue,Le,C=()=>{ne&&(clearTimeout(ne),ne=void 0);let ae=Math.max(jA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),$e=M+ae,Me=Pe(),Ve=Math.min(1e4,$e-Me);M=Me;let it=()=>{l||d()&&H.seek(()=>{d()&&(M=Pe(),K(),C())})};Ve>0?ne=window.setTimeout(()=>{this.paused?C():it()},Ve):it()},K=()=>{let ae;for(;ae=H.nextChunk(N);)N=ae,Vt(ae);let $e=H.nextChunk(D);if($e){if(D&&$e.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?C():(I(),this._initPlayerWith(e));return}tt($e)}else C()},k=(ae,$e)=>{if(!d()||!this.sourceBuffer)return;let Me,Ve,it,wi=Ot=>{window.setTimeout(()=>{d()&&k(ae,$e)},Ot)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),wi(100);else{let Ot=Pe(),ii=P.currentTime;!this.paused&&P.buffered.length>1&&ue===ii&&Ot-Le>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),ue!==ii&&(ue=ii,Le=Ot);let Ai=this._getBufferSizeSec();if(Ai>30)B(`Buffered ${Ai} seconds; delaying appendBuffer`),wi(2e3);else try{this.sourceBuffer.appendBuffer(ae),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:Ai}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),$e&&$e()}catch(cr){if(cr.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),it=this.sourceBuffer.buffered.length,it!==0&&(Me=this.sourceBuffer.buffered.start(0),Ve=ii,Ve-Me>4&&this.sourceBuffer.remove(Me,Ve-3)),wi(1e3);else throw cr}}},J=()=>{Z&&se&&(B([`Appending chunk, sz=${Z.byteLength}:`,JSON.stringify(D)]),k(Z,function(){Z=null,K()}))},W=ae=>e.fragUrlTemplate.replace("%%id%%",ae.chunkIdx),tt=ae=>{d()&&p(W(ae),($e,Me)=>{if(d()){if(Me/=1e3,Z=$e,D=ae,n=ae.startTS,Me){let Ve=Math.min(10,ae.dur/Me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ve:Ve}J()}},()=>this._handleNetworkError())},Vt=ae=>{d()&&((0,We.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(W(ae),!1)))},Pi=ae=>{d()&&(e.cachedHeader=ae,k(ae,()=>{se=!0,J()}))};s=!0,H.seek(ae=>{if(d()){if(M=Pe(),!ae){C();return}N=ae,!(0,We.isNullable)(w)||ae.startTS>w?tt(ae):(D=ae,K())}},w),e.cachedHeader?Pi(e.cachedHeader):m(e.headerUrl,Pi,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,We.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,We.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,We.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let m,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}m=this._selectQuality(d),m?this._switchToQuality(m):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(m,p)=>{let f=Pe();if(this.chunkRateEstimator.addInterval(m,f,p)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-m,speed:S}),!0}},get:()=>{let m=this.chunkRateEstimator.getBitRate();return m?m*.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;i(d)}u=this.autoQuality};return{updateChunk:(d,m)=>{let p=s.updateChunk(d,m);return p&&l(),p},notifySwitch:d=>{let m=Pe();d<o&&(n=m),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=tr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Xs).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;qe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},qA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Fb=G(Hi(),1),me=require("@vkontakte/videoplayer-shared/es2015"),Cu=class{constructor(){this.onDroopedVideoFramesLimit$=new me.Subject;this.subscription=new me.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new me.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,me.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,me.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,me.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,me.interval)(this.droppedFramesChecker.checkTime).pipe((0,me.filter)(()=>this.playing),(0,me.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,me.debounce)(this.droppedFramesChecker.checkTime)),i=(0,me.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Fb.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,me.isLower)(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Js=Cu;var Zs=require("@vkontakte/videoplayer-shared/es2015"),qb=require("@vkontakte/videoplayer-shared/es2015");var zr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var QA=(a,e)=>new Zs.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||zr()))},$($({},i),e));r.observe(a);let s=(0,qb.fromEvent)(document,"visibilitychange").pipe((0,Zs.map)(n=>!document.hidden||zr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Ze=QA;var GA=["paused","playing","ready"],WA=["paused","playing","ready"],Kr=class{constructor(e){this.subscription=new _.Subscription;this.videoState=new Y("stopped");this.representations$=new _.ValueSubject([]);this.droppedFramesManager=new Js;this.maxSeekBackTime$=new _.ValueSubject(1/0);this.zeroTime$=new _.ValueSubject(void 0);this.liveOffset=new vi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:_.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=(i=Yt(u.name))!=null?i:(0,_.videoSizeToQuality)(u.video),d=u.bitrate/1e3,m=$({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:m};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,_.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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Vu.default)(WA,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Vu.default)(GA,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ke(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ke(this.params.source.url,u))}return;default:return(0,_.assertNever)(e)}};this.textTracksManager=new Je(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:_.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,_.merge)(this.videoState.stateChangeStarted$.pipe((0,_.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,_.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=_e(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(xe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Fe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,_.map)(r=>r.map(({track:s})=>s)),(0,_.filter)(r=>!!r.length),(0,_.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,_.filterChanged)(),(0,_.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,_.combine)({zeroTime:this.zeroTime$.pipe((0,_.filter)(_.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(yt(this.video,this.params.desiredState.isLooped,t)).add(Ne(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Xe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ze(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&(0,_.videoQualityToHeight)(r),min:s&&(0,_.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,_.assertNever)(r.to)}},t)).add((0,_.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,_.observableFrom)(["init"])).pipe((0,_.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),Be(this.video)}createLiveDashPlayer(){let e=new Yr({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,m,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(),i=(m=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?m:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,_.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=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let g=(f=e.find(({track:S})=>S.id===s))==null?void 0:f.representation;(0,_.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;(0,_.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(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ke(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Ub=Kr;var Kv=G(Ke(),1);var ir=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var U=require("@vkontakte/videoplayer-shared/es2015");var en=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},rr=class extends en{constructor(){super(),this.listeners||en.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)}},Xr=class{constructor(){Object.defineProperty(this,"signal",{value:new rr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Xr.prototype[Symbol.toStringTag]="AbortController",rr.prototype[Symbol.toStringTag]="AbortSignal");function tn(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:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!tn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let m=new t(l,c);return d&&Object.defineProperty(m,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),m},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 m=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([m,n(u,l)])}return n(u,l)},Request:s}}var Jr=tn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Hb=Jr?Ou({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,It=Jr?Hb.fetch:window.fetch,$V=Jr?Hb.Request:window.Request,Re=Jr?Xr:window.AbortController,MV=Jr?rr:window.AbortSignal;var pl=G(Bu(),1);var Rg=G(kg(),1),ar=require("@vkontakte/videoplayer-shared/es2015"),Lg=a=>{if(!a)return{id:"EmptyResponse",category:ar.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ar.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:ar.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:ar.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ar.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var Jt=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared/es2015");var rn=G(Ke(),1),or=G(zt(),1),an=G(Bu(),1);var Mk=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Dk=a=>window.clearTimeout(a),$g=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Mg=!$g(window.requestIdleCallback)||!$g(window.cancelIdleCallback),Hu=Mg?Mk:window.requestIdleCallback,ea=Mg?Dk:window.cancelIdleCallback;var Bv=G(Ns(),1);var Zt=require("@vkontakte/videoplayer-shared/es2015");var Ck=18,Dg=!1;try{Dg=ee.browser.isSafari&&!!ee.browser.safariVersion&&ee.browser.safariVersion<=Ck}catch(a){console.error(a)}var ju=class{constructor(e){this.bufferFull$=new Zt.Subject;this.error$=new Zt.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Zt.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return A(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return A(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return A(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Dg&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Zt.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,Zt.assertNever)(t)}}},Cg=ju;var Qu=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var E=require("@vkontakte/videoplayer-shared/es2015");var te=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var sr=class extends te{};var ta=class extends te{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ia=class extends te{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var ra=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ce=class extends te{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var aa=class extends ce{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 te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var na=class extends te{constructor(e,t){super(e,t),this.data=this.content}};var Si=class extends ce{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var oa=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var la=class extends ce{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 ce{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var da=class extends ce{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 te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends ce{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ma=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends ce{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ga=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends ce{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 ce{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ya=class extends ce{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Ta=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends ce{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Ea=class extends te{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Ok={ftyp:ia,moov:ra,mvhd:aa,moof:sa,mdat:na,sidx:Si,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,stbl:Ta,stsd:Ia,avc1:Ea,unknown:sr},Rt=class a{constructor(e={}){this.options=$({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=Ok[e];return i?new i(t,new a):new sr(t,new a)}};var ei=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var Bk=new TextDecoder("ascii"),Nk=a=>Bk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Fk=a=>{let e=new Si(a,new Rt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},qk=(a,e)=>{let i=new Rt().parse(a),r=new ei(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},Uk=a=>{let t=new Rt().parse(a),i=new ei(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},Hk=a=>{var r;let t=new Rt().parse(a);return(r=new ei(t).find("sidx"))==null?void 0:r.timescale},jk=(a,e)=>{let i=new Rt().parse(a),s=new ei(i).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,m)=>d+m,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}}},i=new Rt().parse(a),r=new ei(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Vg={validateData:Nk,parseInit:Qk,getIndexRange:()=>{},parseSegments:Fk,parseFeedableSegmentChunk:qk,getChunkEndTime:jk,getServerLatencyTimestamps:Uk,getTimescaleFromIndex:Hk};var Pa=G(Ke(),1),Lt=require("@vkontakte/videoplayer-shared/es2015");var _g=require("@vkontakte/videoplayer-shared/es2015");var Og={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Bg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=xa(a,t),r=i in Og,s=r?Og[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=xa(u),d=l*ft(2,(o-1)*8)+c,m=t+o,p;return m+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+m):p=new DataView(a.buffer,a.byteOffset+m,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:m,tagSize:m+d,value:p,valueSize:d}},xa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*ft(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*ft(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*ft(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},dt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return xa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,_g.assertNever)(e)}},yi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Bg(i);if(!e(r))return;r.type==="master"&&yi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Ng=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Bg(a);return yi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=dt(o,n):s===17026?t=dt(o,n):s===17029&&(i=dt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=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],Wk=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return yi(a,({tag:m,type:p,value:f,valueSize:g})=>{if(m===21419){let S=dt(f,p);l=xa(S)}else m!==21420&&(l=void 0);return m===408125543?(e=f.byteOffset,t=f.byteOffset+g):m===357149030?s=!0:m===290298740?n=!0:m===2807729?i=dt(f,p):m===17545?r=dt(f,p):m===21420&&l===475249515?u=dt(f,p):m===374648427?yi(f,({tag:S,type:y,value:I})=>S===30321?(c=dt(I,y)===1,!1):!0):s&&n&&(0,Pa.default)(Fg,m)&&(o=!0),!o}),(0,Lt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Lt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Lt.assertNonNullable)(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Yk=a=>{if((0,Lt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},zk=(a,e)=>{let t=!1,i=!1,r=o=>(0,Lt.isNonNullable)(o.time)&&(0,Lt.isNonNullable)(o.position),s=[],n;return yi(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=dt(l,u));break;case 183:break;case 241:n&&(n.position=dt(l,u));break;default:t&&(0,Pa.default)(Fg,o)&&(i=!0)}return!(t&&i)}),n&&r(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}}})},Kk=a=>{let e=0,t=!1;try{yi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Pa.default)(Gk,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,Pa.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},qg={validateData:Ng,parseInit:Wk,getIndexRange:Yk,parseSegments:zk,parseFeedableSegmentChunk:Kk};var wa=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return qg;case"mp4":return Vg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var al=G(ov(),1),Dv=G(Hi(),1),Cv=G(Ev(),1),Vv=G(zt(),1),sl=G(Zi(),1);var xv=G(Ke(),1),Ju=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,xv.default)(["6E","7A","F4"],o)}}return!1};var ka=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 wv=a=>{var e;try{let t=QR(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function QR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
64
64
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
65
65
|
(-(?<script>[a-z]{4}))?
|
|
66
66
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
67
67
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
68
68
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
69
69
|
(?:-(?<privateuse>(?:${e})))?
|
|
70
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var nl=Q(yr(),1);var Ov=require("@vkontakte/videoplayer-shared/es2015"),Bv=({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,Ov.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Nv=({id:a,bitrate:e})=>({id:a,bitrate:e}),Fv=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),qv=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ol=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,nl.default)(r.split("."),0),isDefault:i}),ul=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,nl.default)(i.split("."),0)}),ll=a=>"url"in a,Ve=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Uv=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},Ct=(a,e)=>{let t=a;t=(0,cl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Hv.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,cl.default)(t,n,(o,u)=>(0,Ma.isNullable)(s)?o:(0,Ma.isNullable)(u)?s:(0,jv.default)(s,parseInt(u,10),"0"))}return t},Gv=(a,e)=>{var j,te,re,B,ie,J,oe,R,P,W,se,Z,Qe,pi,Ar,ne,we,Re,Me,Ot,kr,Bt,ir,Lr,hi,Ll,$l,Rl,Ml,Cl,Dl,Vl,_l,Ol,Bl,Nl,Fl,ql,Ul,Hl,jl,Ql,Gl,Wl,Yl,zl,Kl,Xl,Jl,Zl,ec,tc,rc,ic,ac,sc,nc,oc,uc,lc,cc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(it=>{var le,ar;return(ar=(le=it.textContent)==null?void 0:le.trim())!=null?ar:""}),o=(j=(0,Qv.default)(n,0))!=null?j:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],h=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,v;u&&(v={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:m==="yes",streamIsUnpublished:f==="yes"});let T,I=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],w=x.reduce((it,le)=>N(L({},it),{[le.id]:le.children}),{}),A=x.reduce((it,le)=>N(L({},it),{[le.id]:le.getAttribute("duration")}),{});I?T=Uv(I):(0,dl.default)(A).filter(it=>it).length&&!u?T=(0,dl.default)(A).reduce((it,le)=>{var ar;return it+((ar=Uv(le))!=null?ar:0)},0):g&&(T=parseInt(g,10));let _=0,q=(re=(te=s.getAttribute("profiles"))==null?void 0:te.split(","))!=null?re:[];for(let it of x.map(le=>le.id))for(let le of w[it]){let ar=(B=le.getAttribute("id"))!=null?B:"id"+(_++).toString(10),mi=(ie=le.getAttribute("mimeType"))!=null?ie:"",An=(J=le.getAttribute("codecs"))!=null?J:"",kn=(oe=le.getAttribute("contentType"))!=null?oe:mi==null?void 0:mi.split("/")[0],MS=(P=(R=le.getAttribute("profiles"))==null?void 0:R.split(","))!=null?P:[],dc=(se=_v((W=le.getAttribute("lang"))!=null?W:""))!=null?se:{},Ya=(pi=(Qe=(Z=le.querySelector("Label"))==null?void 0:Z.textContent)==null?void 0:Qe.trim())!=null?pi:void 0,CS=le.querySelectorAll("Representation"),DS=le.querySelector("SegmentTemplate"),VS=(ne=(Ar=le.querySelector("Role"))==null?void 0:Ar.getAttribute("value"))!=null?ne:void 0,$r=kn,ge={id:ar,language:dc.language,isDefault:VS==="main",label:Ya,codecs:An,hdr:$r==="video"&&al(An),mime:mi,representations:[]};for(let ue of CS){let Nt=(we=ue.getAttribute("lang"))!=null?we:void 0,fi=(Me=(Re=Ya!=null?Ya:le.getAttribute("label"))!=null?Re:ue.getAttribute("label"))!=null?Me:void 0,za=(Bt=(kr=(Ot=ue.querySelector("BaseURL"))==null?void 0:Ot.textContent)==null?void 0:kr.trim())!=null?Bt:"",sr=new URL(za||o,e).toString(),Ft=(ir=ue.getAttribute("mimeType"))!=null?ir:mi,Ka=(hi=(Lr=ue.getAttribute("codecs"))!=null?Lr:An)!=null?hi:"",Xa;if(kn==="text"){let qt=ue.getAttribute("id")||"",Ja=((Ll=dc.privateuse)==null?void 0:Ll.includes("x-auto"))||qt.includes("_auto"),nr=ue.querySelector("SegmentTemplate");if(nr){let bi={representationId:($l=ue.getAttribute("id"))!=null?$l:void 0,bandwidth:(Rl=ue.getAttribute("bandwidth"))!=null?Rl:void 0},Za=parseInt((Ml=ue.getAttribute("bandwidth"))!=null?Ml:"",10)/1e3,es=(Dl=parseInt((Cl=nr.getAttribute("startNumber"))!=null?Cl:"",10))!=null?Dl:1,Rr=parseInt((Vl=nr.getAttribute("timescale"))!=null?Vl:"",10),Ln=(_l=nr.querySelectorAll("SegmentTimeline S"))!=null?_l:[],Mr=nr.getAttribute("media");if(!Mr)continue;let ts=[],rs=0,is="",Cr=0,gi=es,Ce=0;for(let at of Ln){let or=parseInt((Ol=at.getAttribute("d"))!=null?Ol:"",10),Je=parseInt((Bl=at.getAttribute("r"))!=null?Bl:"",10)||0,Ut=parseInt((Nl=at.getAttribute("t"))!=null?Nl:"",10);Ce=Number.isFinite(Ut)?Ut:Ce;let ur=or/Rr*1e3,Ht=Ce/Rr*1e3;for(let ht=0;ht<Je+1;ht++){let jt=Ct(Mr,N(L({},bi),{segmentNumber:gi.toString(10),segmentTime:(Ce+ht*or).toString(10)})),Dr=(Ht!=null?Ht:0)+ht*ur,Si=Dr+ur;gi++,ts.push({time:{from:Dr,to:Si},url:jt})}Ce+=(Je+1)*or,rs+=(Je+1)*ur}Cr=Ce/Rr*1e3,is=Ct(Mr,N(L({},bi),{segmentNumber:gi.toString(10),segmentTime:Ce.toString(10)}));let vi={time:{from:Cr,to:1/0},url:is},Pt={type:"template",baseUrl:sr,segmentTemplateUrl:Mr,initUrl:"",totalSegmentsDurationMs:rs,segments:ts,nextSegmentBeyondManifest:vi,timescale:Rr};Xa={id:qt,kind:"text",segmentReference:Pt,profiles:[],duration:T,bitrate:Za,mime:"",codecs:"",width:0,height:0,isAuto:Ja}}else Xa={id:qt,isAuto:Ja,kind:"text",url:sr}}else{let qt=(ql=(Fl=ue.getAttribute("contentType"))!=null?Fl:Ft==null?void 0:Ft.split("/")[0])!=null?ql:kn,Ja=(Hl=(Ul=le.getAttribute("profiles"))==null?void 0:Ul.split(","))!=null?Hl:[],nr=parseInt((jl=ue.getAttribute("width"))!=null?jl:"",10),bi=parseInt((Ql=ue.getAttribute("height"))!=null?Ql:"",10),Za=parseInt((Gl=ue.getAttribute("bandwidth"))!=null?Gl:"",10)/1e3,es=(Wl=ue.getAttribute("frameRate"))!=null?Wl:"",Rr=(Yl=ue.getAttribute("quality"))!=null?Yl:void 0,Ln=es?Vv(es):void 0,Mr=(zl=ue.getAttribute("id"))!=null?zl:"id"+(_++).toString(10),ts=qt==="video"?`${bi}p`:qt==="audio"?`${Za}Kbps`:Ka,rs=`${Mr}@${ts}`,is=[...q,...MS,...Ja],Cr,gi=ue.querySelector("SegmentBase"),Ce=(Kl=ue.querySelector("SegmentTemplate"))!=null?Kl:DS;if(gi){let Pt=(Jl=(Xl=ue.querySelector("SegmentBase Initialization"))==null?void 0:Xl.getAttribute("range"))!=null?Jl:"",[at,or]=Pt.split("-").map(jt=>parseInt(jt,10)),Je={from:at,to:or},Ut=(Zl=ue.querySelector("SegmentBase"))==null?void 0:Zl.getAttribute("indexRange"),[ur,Ht]=Ut?Ut.split("-").map(jt=>parseInt(jt,10)):[],ht=Ut?{from:ur,to:Ht}:void 0;Cr={type:"byteRange",url:sr,initRange:Je,indexRange:ht}}else if(Ce){let Pt={representationId:(ec=ue.getAttribute("id"))!=null?ec:void 0,bandwidth:(tc=ue.getAttribute("bandwidth"))!=null?tc:void 0},at=parseInt((rc=Ce.getAttribute("timescale"))!=null?rc:"",10),or=(ic=Ce.getAttribute("initialization"))!=null?ic:"",Je=Ce.getAttribute("media"),Ut=(sc=parseInt((ac=Ce.getAttribute("startNumber"))!=null?ac:"",10))!=null?sc:1,ur=Ct(or,Pt);if(!Je)throw new ReferenceError("No media attribute in SegmentTemplate");let Ht=(nc=Ce.querySelectorAll("SegmentTimeline S"))!=null?nc:[],ht=[],jt=0,Dr="",Si=0;if(Ht.length){let as=Ut,st=0;for(let Vr of Ht){let mt=parseInt((oc=Vr.getAttribute("d"))!=null?oc:"",10),lr=parseInt((uc=Vr.getAttribute("r"))!=null?uc:"",10)||0,ss=parseInt((lc=Vr.getAttribute("t"))!=null?lc:"",10);st=Number.isFinite(ss)?ss:st;let $n=mt/at*1e3,Rn=st/at*1e3;for(let ns=0;ns<lr+1;ns++){let OS=Ct(Je,N(L({},Pt),{segmentNumber:as.toString(10),segmentTime:(st+ns*mt).toString(10)})),pc=(Rn!=null?Rn:0)+ns*$n,BS=pc+$n;as++,ht.push({time:{from:pc,to:BS},url:OS})}st+=(lr+1)*mt,jt+=(lr+1)*$n}Si=st/at*1e3,Dr=Ct(Je,N(L({},Pt),{segmentNumber:as.toString(10),segmentTime:st.toString(10)}))}else if((0,Ma.isNonNullable)(T)){let st=parseInt((cc=Ce.getAttribute("duration"))!=null?cc:"",10)/at*1e3,Vr=Math.ceil(T/st),mt=0;for(let lr=1;lr<Vr;lr++){let ss=Ct(Je,N(L({},Pt),{segmentNumber:lr.toString(10),segmentTime:mt.toString(10)}));ht.push({time:{from:mt,to:mt+st},url:ss}),mt+=st}Si=mt,Dr=Ct(Je,N(L({},Pt),{segmentNumber:Vr.toString(10),segmentTime:mt.toString(10)}))}let _S={time:{from:Si,to:1/0},url:Dr};Cr={type:"template",baseUrl:sr,segmentTemplateUrl:Je,initUrl:ur,totalSegmentsDurationMs:jt,segments:ht,nextSegmentBeyondManifest:_S,timescale:at}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!qt||!Ft)continue;let vi={video:"video",audio:"audio",text:"text"}[qt];if(!vi)continue;$r||($r=vi),Xa={id:rs,kind:vi,segmentReference:Cr,profiles:is,duration:T,bitrate:Za,mime:Ft,codecs:Ka,width:nr,height:bi,fps:Ln,quality:Rr}}ge.language||(ge.language=Nt),ge.label||(ge.label=fi),ge.mime||(ge.mime=Ft),ge.codecs||(ge.codecs=Ka),ge.hdr||(ge.hdr=$r==="video"&&al(Ka)),ge.representations.push(Xa)}if($r){let ue=i[$r].find(Nt=>Nt.id===ge.id);if(ue&&ge.representations.every(Nt=>Ve(Nt.segmentReference)))for(let Nt of ue.representations){let fi=ge.representations.find(Ft=>Ft.id===Nt.id),za=fi==null?void 0:fi.segmentReference,sr=Nt.segmentReference;sr.segments.push(...za.segments),sr.nextSegmentBeyondManifest=za.nextSegmentBeyondManifest}else i[$r].push(ge)}}return{duration:T,streams:i,baseUrls:n,live:v}};var Wv=Q(Be(),1),hl=require("@vkontakte/videoplayer-shared/es2015"),_e=(a,e)=>(0,hl.isNonNullable)(a)&&(0,hl.isNonNullable)(e)&&a.readyState==="open"&&(0,Wv.default)([...a.activeSourceBuffers],e);var Ca=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.currentLowLatencySegmentLength$=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 $e;this.switchAbortController=new $e;this.destroyAbortController=new $e;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 Se(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 jg(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||!_e(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Xu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=It(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),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.switchTo=(0,E.abortable)(this.destroyAbortController.signal,function(e,t=!1){return Se(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||!_e(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,E.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new us(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,E.abortable)(this.destroyAbortController.signal,function(e,t=!1){return Se(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||!_e(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,E.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new us(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 Se(this,null,function*(){var u,l;let t=(u=(0,un.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||!Ve(h.segmentReference))return;let m=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,m)}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,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new $e,(0,E.abortable)(this.switchAbortController.signal,function(r,i=!1){return Se(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||!_e(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,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))}warmUpMediaSource(){!(0,E.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return k(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new $e,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,E.isNullable)(e)||(0,E.isNullable)(this.downloadingRepresentationId)||(0,E.isNullable)(this.playingRepresentationId)||(0,E.isNullable)(this.sourceBuffer)||!_e(this.mediaSource,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(l=>e>=l.time.from&&e<l.time.to);(0,E.isNonNullable)(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=It(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Xu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=It(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,on.default)(o,i))l="high";else{let c=(0,ui.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&It(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ui.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,E.isNonNullable)(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,un.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,un.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ve(o.segmentReference))return;let u=o.segmentReference.segments.map(m=>N(L({},m),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ui.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(m=>d>=m.time.from+l&&d<=m.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let m=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,m)}else{let m=u.slice(h+1);this.segments.set(o.id,[...c,...m])}}}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 r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Ve(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=Ct(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&aa&&aa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&aa&&aa(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:h,to:m}},f)=>{let g=h<=r&&m>=r,v=h>r||g||f===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&h<=r+T||m<=r+T;return(d==="none"||d==="partially_ejected"&&v&&I&&this.sourceBuffer&&_e(this.mediaSource,this.sourceBuffer)&&!(Zt(this.sourceBuffer.buffered,h)&&Zt(this.sourceBuffer.buffered,m)))&&v&&I});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,r="auto"){return k(this,null,function*(){Ve(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return k(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,E.abortable)(o,function(){return Se(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=$a(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:m,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(d);m&&f&&this.currentLiveSegmentServerLatency$.next(f-m),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ra(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())Ve(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return k(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,E.abortable)(n,function(){return Se(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),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Ve(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ui.default)(e,0).byte.from,to:(0,ui.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>k(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)(),yield 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(!Ve(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,on.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return k(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=$a(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return k(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,h=c.byte.to-r,m=h-d+1,f=d<i,g=h<=i;if(!f)continue;let v=$a(u.mime);if(c.status==="downloading"&&g){c.status="downloaded";let T=new DataView(e.buffer,e.byteOffset+d,m);(yield this.sourceBufferTaskQueue.append(T,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(m,i-d),l.loadedBytes>l.feedingBytes)){let T=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),I=l.loadedBytes===m?T:v.parseFeedableSegmentChunk(T);I!=null&&I.byteLength&&(c.status="partially_fed",l.feedingBytes+=I.byteLength,(yield this.sourceBufferTaskQueue.append(I,s))&&!s.aborted?(l.fedBytes+=I.byteLength,l.fedBytes===m&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!((0,E.isNullable)(this.sourceBuffer)||!_e(this.mediaSource,this.sourceBuffer))){!this.isLive&&z.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Zt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Zt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ll(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=zu(()=>(0,Yv.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return k(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,E.abortable)(this.destroyAbortController.signal,function(){return Se(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,$a(e.mime),i)).then(o=>k(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&Ve(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 k(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return k(this,null,function*(){if(!this.sourceBuffer||!_e(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,E.isNullable)(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],m=l[l.length-1];m.to>=d?m.to=Math.max(m.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(L({},u.time)),i=n(i);let l=ll(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 m of h)(0,on.default)(["none","partially_ejected"],m.status)&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.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(){return k(this,null,function*(){if(!this.sourceBuffer||!_e(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!_e(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!_e(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,E.isNullable)(e)?0:It(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!_e(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!_e(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=zu(()=>{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)||!_e(this.mediaSource,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")}}handleAsyncError(e,t){this.error$.next({id:t,category:E.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Da=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var zv=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 F=require("@vkontakte/videoplayer-shared/es2015");var Kv=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var cn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new F.ValueSubject(void 0);this.lastConnectionReused$=new F.ValueSubject(void 0);this.lastRequestFirstBytes$=new F.ValueSubject(void 0);this.recoverableError$=new F.Subject;this.error$=new F.Subject;this.abortAllController=new $e;this.subscription=new F.Subscription;this.fetchManifest=(0,F.abortable)(this.abortAllController.signal,function(e){return Se(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Da(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Kv(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(ln);return i?(t.log("success",(0,F.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,F.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,F.abortable)(this.abortAllController.signal,function(l){return Se(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 J=new URL(c,location.href);J.searchParams.append("bytes",`${r.from}-${r.to}`),c=J.toString();break}default:(0,F.assertNever)(t)}this.requestQuic&&(c=Da(c));let m=this.abortAllController.signal,f;if(n){let J=new $e;if(f=(0,F.merge)((0,F.fromEvent)(this.abortAllController.signal,"abort"),(0,F.fromEvent)(n,"abort")).subscribe(()=>{try{J.abort()}catch(oe){ln(oe)}}),this.abortAllController.signal.aborted||n.aborted)try{J.abort()}catch(oe){ln(oe)}m=J.signal}let g=(0,F.now)();h.log("startRequest",(0,F.flattenObject)({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let v=yield this.doFetch(c,{priority:s,headers:d,signal:m}),T=(0,F.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(T-g),!v.ok||!v.body){f==null||f.unsubscribe();let J=`Fetch error ${v.status}: ${v.statusText}`;return h.error("error",{message:J}),h.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!i&&!o){f==null||f.unsubscribe();let J=(0,F.now)(),oe={requestStartedAt:g,requestEndedAt:J,duration:J-g};return h.log("endRequest",(0,F.flattenObject)(oe)),h.end(),v.arrayBuffer()}let[I,x]=v.body.tee(),w=I.getReader();o&&((ie=this.throughputEstimator)==null||ie.trackStream(x,u));let A=0,_=new Uint8Array(0),q=!1,pe=J=>{f==null||f.unsubscribe(),q=!0,ln(J)},j=(0,F.abortable)(m,function(R){return Se(this,arguments,function*({done:J,value:oe}){if(A===0&&this.lastRequestFirstBytes$.next((0,F.now)()-g),m.aborted){f==null||f.unsubscribe();return}if(!J&&oe){let P=new Uint8Array(_.length+oe.length);P.set(_),P.set(oe,_.length),_=P,A+=oe.byteLength,i==null||i(new DataView(_.buffer),A),yield w==null?void 0:w.read().then(j,pe)}})}.bind(this));yield w==null?void 0:w.read().then(j,pe),f==null||f.unsubscribe();let te=(0,F.now)(),re={failed:q,requestStartedAt:g,requestEndedAt:te,duration:te-g};return q?(h.error("endRequest",(0,F.flattenObject)(re)),h.end(),null):(h.log("endRequest",(0,F.flattenObject)(re)),h.end(),_.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,F.abortable)(this.abortAllController.signal,function(e,t,r){return Se(this,null,function*(){var T;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let m=t.parseInit(h),f=(T=e.indexRange)!=null?T:t.getIndexRange(m);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 I=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!I)return null;g=new DataView(I)}let v=t.parseSegments(g,m,f);return{init:m,dataView:new DataView(d),segments:v}})}.bind(this));this.fetchTemplateRepresentation=(0,F.abortable)(this.abortAllController.signal,function(e,t){return Se(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=>N(L({},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}=zv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return k(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,F.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return k(this,null,function*(){let r=yield Et(e,t);if(r.ok)return r;let i=yield r.text(),s=parseInt(i);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:F.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:F.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:F.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:F.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:F.ErrorCategory.FATAL})}})}},ln=a=>{if(!Ra(a))throw a};var Er=(a,e,t)=>t*e+(1-t)*a,ml=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Xv=(a,e,t,r)=>{let i=0,s=t,n=ml(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 Va=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 Va.ValueSubject(e.initial),this.debounced$=new Va.ValueSubject(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new De(`raw_${t}`),this.smoothedSeries$=new De(`smoothed_${t}`),this.reportedSeries$=new De(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=ft(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,Va.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 dn=class extends rr{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Er(this.slow,e,this.params.emaAlphaSlow),this.fast=Er(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var pn=class extends rr{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ml(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Er(this.emaSmoothed,e,this.params.emaAlpha);let r=Xv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var hn=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?Er(this.smoothed,t,this.params.emaAlpha):t}};var xr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new dn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new pn({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 hn(L({initial:e,label:"liveEdgeDelay"},t))}};var fl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var mn=require("@vkontakte/videoplayer-shared/es2015");var _a=class a{constructor(e,t){this.currentRepresentation$=new mn.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,mn.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(N(L({},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&&Ve(t.segmentReference))}};var bl=Q(Be(),1);var Oa=require("@vkontakte/videoplayer-shared/es2015");var Jv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let{containers:i,protocols:s,codecs:n,nativeHlsSupported:o}=z.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!r||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&i.mp4&&u;case"DASH_WEBM":return l&&i.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&i.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(i.mp4&&u||i.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&i.mp4&&u;case"DASH_LIVE_CMAF":return l&&i.mp4&&u&&i.cmaf;case"DASH_ONDEMAND":return l&&i.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&i.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(i.mp4||i.webm);default:return(0,Oa.assertNever)(c)}})},fn=a=>{let{webmDecodingInfo:e}=z.video,t="DASH_WEBM",r="DASH_WEBM_AV1";switch(a){case"vp9":return[t,r];case"av1":return[r,t];case"none":return[];case"smooth":return e?e[r].smooth?[r,t]:e[t].smooth?[t,r]:[r,t]:[t,r];case"power_efficient":return e?e[r].powerEfficient?[r,t]:e[t].powerEfficient?[t,r]:[r,t]:[t,r];default:(0,Oa.assertNever)(a)}return[t,r]},Zv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...fn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(z.device.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",...fn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...fn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...fn(a),...i,"HLS","HLS_ONDEMAND"];default:(0,Oa.assertNever)(e)}return z.video.nativeHlsSupported?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},eS=({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=z.device.isMac&&z.browser.isSafari;if(z.device.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,Oa.assertNever)(a)}else z.video.nativeHlsSupported&&!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"]},gl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],tS=a=>{let e=a.map(r=>bn(r)),{codecs:t}=z.video;return n$().filter(r=>{if((0,bl.default)(e,r))switch(r){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},rS=a=>{let e=a.map(r=>bn(r)),{codecs:t}=z.video;return o$().filter(r=>{if((0,bl.default)(e,r))switch(r){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}})},bn=a=>a.split(".")[0].replace("0",""),n$=()=>["av1","vp9","avc1","hev1"],o$=()=>["opus","mp4a"];var d$=["timeupdate","progress","play","seeked","stalled","waiting"],p$=["timeupdate","progress","loadeddata","playing","seeked"];var gn=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 Y("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.isActiveLive$=new S.ValueSubject(!1);this.isLowLatency$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveSeekableDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(0);this.liveStreamStatus$=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.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.fetcherRecoverableError$=new S.Subject;this.fetcherError$=new S.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new $e;this.initManifest=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return Se(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Le(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 Se(this,null,function*(){var u,l;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(c=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:c})});if(!e)return null;let t=null;try{t=Gv(e!=null?e:"",this.manifestUrlString)}catch(c){let d=(u=Fg(e))!=null?u:{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:c};this.error$.next(d)}if(!t)return null;let r=(c,d,h)=>{var m,f,g,v;return!!((f=(m=this.element)==null?void 0:m.canPlayType)!=null&&f.call(m,d)&&((v=(g=ct())==null?void 0:g.isTypeSupported)!=null&&v.call(g,`${d}; codecs="${h}"`))||c==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:c,latestSegmentPublishTime:d,streamIsUnpublished:h,streamIsAlive:m}=t.live,f=((l=t.duration)!=null?l:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((d-c)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let g="active";m||(g=h?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(g)}let i={text:t.streams.text,video:[],audio:[]},s,n;for(let c of["video","audio"]){let h=t.streams[c].filter(({mime:g,codecs:v})=>r(c,g,v));i[c]=h;let m=h.map(({codecs:g})=>g),f;if(c==="audio"&&(n=rS(m),f=n[0]),c==="video"&&(s=tS(m),this.forceVideoCodec&&(0,aS.default)(s,this.forceVideoCodec)?f=this.forceVideoCodec:f=s[0]),f&&(i[c]=h.filter(({codecs:g})=>bn(g)===f)),c==="video"){let g=this.tuning.preferHDR,v=i.video.some(I=>I.hdr),T=i.video.some(I=>!I.hdr);z.display.isHDR&&g&&v?i.video=i.video.filter(I=>I.hdr):T&&(i.video=i.video.filter(I=>!I.hdr))}}let o=N(L({},t),{streams:i,codecs:{video:s,audio:n}});return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(o)),o})}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,function(e,t,r){return Se(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=h=>{this.representationSubscription.add((0,S.fromEvent)(h,"error").pipe((0,S.filter)(m=>{var f;return!!((f=this.element)!=null&&f.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?Tb():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ks())if(r){let h=document.createElement("source");i(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((h,m)=>[...h,...m.representations],[]);if(this.videoBufferManager=new Ca("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let h=this.manifest.streams.audio.reduce((m,f)=>[...m,...f.representations],[]);this.audioBufferManager=new Ca("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}_a.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new _a(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...p$.map(h=>(0,S.fromEvent)(this.element,h))).pipe((0,S.map)(h=>this.element?It(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,S.filterChanged)()).subscribe(m=>this.liveStreamEndTimestamp=(0,S.now)())),this.subscription.add((0,S.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,S.interval)(1e3).subscribe(m=>{let f=js(this.manifestUrlString,2);this.manifestUrlString=Le(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()})})).add((0,S.fromEvent)(this.element,"play").subscribe(m=>{var f;return(f=this.livePauseWatchdogSubscription)==null?void 0:f.unsubscribe()})),this.representationSubscription.add((0,S.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,S.map)(({isActiveLive:m,isLowLatency:f})=>m&&f),(0,S.filterChanged)()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||fl(this.element,1)})),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,S.filter)(({bufferLength:m,isActiveLive:f,isLowLatency:g})=>f&&g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(m=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!m)return;let f=this.liveSeekableDuration$.getValue()-m/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+m/1e3)})),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.filterChanged)((m,f)=>f.bufferLength<m.bufferLength),(0,S.map)(({rtt:m,bufferLength:f,segmentServerLatency:g})=>{let v=js(this.manifestUrlString,2);return(m/2+f+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:m,isActiveLive:f,isLowLatency:g})=>{if(!g||!f)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=m-v;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(x)>T&&(w=1+Math.sign(x)*I),fl(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let f=0;if(m){let T=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;f=Math.min(...this.bufferManagers.map(x=>{var w,A;return(A=(w=x.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?A:T}))-T}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let h=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(g=>k(this,[g],function*({liveLoadBufferLength:m,bufferLength:f}){if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,T=js(this.manifestUrlString,2),I=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,x=Math.min(I,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,_=isFinite(m)?m:f,q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),pe=I<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(pe);let j="none";if(q?j="active_low_latency":this.isLowLatency$.getValue()&&pe?(this.bufferManagers.forEach(te=>te.proceedLowLatencyLive()),j="active_low_latency"):T!==0&&_<x?j="live_forward_buffering":_<x+A&&(j="live_with_target_offset"),isFinite(m)&&(h=m>h?m:h),j==="live_forward_buffering"||j==="live_with_target_offset"){let te=h-(x+w),re=this.normolizeLiveOffset(Math.trunc(T+te/v)),B=Math.abs(re-T),ie=0;!m||B<=this.tuning.dashCmafLive.offsetCalculationError?ie=T:re>0&&B>this.tuning.dashCmafLive.offsetCalculationError&&(ie=re),this.manifestUrlString=Le(this.manifestUrlString,ie,2)}(j==="live_with_target_offset"||j==="live_forward_buffering")&&(h=0,yield this.updateLive())}),m=>{this.error$.next({id:"updateLive",category:S.ErrorCategory.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=(0,S.merge)(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));if(this.representationSubscription.add((0,S.merge)(this.forceEnded$,(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filter)(({allBuffersFull:h,someBufferEnded:m})=>h&&m))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(h=this.source)==null||h.endOfStream(),this.bufferManagers.forEach(m=>m.warmUpMediaSource())}catch(m){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(h=>{var m;return(m=this.source)==null?void 0:m.addEventListener("sourceopen",h)})),!this.isLive$.getValue()){let h=[(d=this.manifest.duration)!=null?d:0,...(0,Sl.default)((0,Sl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let f=[];return m.duration&&f.push(m.duration),Ve(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&f.push(m.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...h)/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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new cn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=xr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,L({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return k(this,null,function*(){var i,s,n;(0,S.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,S.now)()-this.liveStreamEndTimestamp:0,r=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(r===0),this.manifestUrlString=Le(this.manifestUrlString,r,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){(0,S.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,S.merge)(...d$.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 m,f,g,v,T,I,x,w,A,_;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=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(I=(T=this.videoBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?I: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%2e3===0){let q=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(q).catch(pe=>{this.error$.next({id:"stallIntervalCallback",category:S.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:pe})}),i.liveLastOffset=q}else{let q=this.element.currentTime*1e3;(A=this.videoBufferManager)==null||A.maintain(q),(_=this.audioBufferManager)==null||_.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 k(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)})}seek(e,t){return k(this,null,function*(){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)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!((0,S.isNullable)(this.element)||(0,S.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:r})))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}getCodecs(){var e;return(e=this.manifest)==null?void 0:e.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,S.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return k(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),r={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=i&&u.to+n>i&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,r=N(L({},r),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,S.flattenObject)(r)))}}};var vn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Sn=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/ft(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=L({},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*ft(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 sS=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var el=G(zt(),1);var Av=require("@vkontakte/videoplayer-shared/es2015"),kv=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Yt(s):void 0)!=null?u:(0,Av.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Rv=({id:a,bitrate:e})=>({id:a,bitrate:e}),Lv=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),$v=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),tl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,el.default)(i.split("."),0),isDefault:r}),il=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,el.default)(r.split("."),0)}),rl=a=>"url"in a,Ce=a=>a.type==="template",Aa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Mv=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},$t=(a,e)=>{let t=a;t=(0,al.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Dv.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,al.default)(t,n,(o,u)=>(0,ka.isNullable)(s)?o:(0,ka.isNullable)(u)?s:(0,Cv.default)(s,parseInt(u,10),"0"))}return t},Ov=(a,e)=>{var Z,D,N,M,ne,ue,Le,C,K,k,J,W,tt,Vt,Pi,ae,$e,Me,Ve,it,wi,Ot,ii,Ai,cr,Il,El,xl,Pl,wl,Al,kl,Rl,Ll,$l,Ml,Dl,Cl,Vl,Ol,_l,Bl,Nl,Fl,ql,Ul,Hl,jl,Ql,Gl,Wl,Yl,zl,Kl,Xl,Jl,Zl,ec,tc,ic,rc;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(rt=>{var le,ri;return(ri=(le=rt.textContent)==null?void 0:le.trim())!=null?ri:""}),o=(Z=(0,Vv.default)(n,0))!=null?Z:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],m=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:m?new Date(m).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let y,I=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],w=x.reduce((rt,le)=>j($({},rt),{[le.id]:le.children}),{}),P=x.reduce((rt,le)=>j($({},rt),{[le.id]:le.getAttribute("duration")}),{});I?y=Mv(I):(0,sl.default)(P).filter(rt=>rt).length&&!u?y=(0,sl.default)(P).reduce((rt,le)=>{var ri;return rt+((ri=Mv(le))!=null?ri:0)},0):g&&(y=parseInt(g,10));let B=0,H=(N=(D=s.getAttribute("profiles"))==null?void 0:D.split(","))!=null?N:[];for(let rt of x.map(le=>le.id))for(let le of w[rt]){let ri=(M=le.getAttribute("id"))!=null?M:"id"+(B++).toString(10),dr=(ne=le.getAttribute("mimeType"))!=null?ne:"",En=(ue=le.getAttribute("codecs"))!=null?ue:"",xn=(Le=le.getAttribute("contentType"))!=null?Le:dr==null?void 0:dr.split("/")[0],yS=(K=(C=le.getAttribute("profiles"))==null?void 0:C.split(","))!=null?K:[],ac=(J=wv((k=le.getAttribute("lang"))!=null?k:""))!=null?J:{},Qa=(Vt=(tt=(W=le.querySelector("Label"))==null?void 0:W.textContent)==null?void 0:tt.trim())!=null?Vt:void 0,TS=le.querySelectorAll("Representation"),IS=le.querySelector("SegmentTemplate"),ES=(ae=(Pi=le.querySelector("Role"))==null?void 0:Pi.getAttribute("value"))!=null?ae:void 0,ki=xn,be={id:ri,language:ac.language,isDefault:ES==="main",label:Qa,codecs:En,hdr:ki==="video"&&Ju(En),mime:dr,representations:[]};for(let oe of TS){let _t=($e=oe.getAttribute("lang"))!=null?$e:void 0,pr=(Ve=(Me=Qa!=null?Qa:le.getAttribute("label"))!=null?Me:oe.getAttribute("label"))!=null?Ve:void 0,Ga=(Ot=(wi=(it=oe.querySelector("BaseURL"))==null?void 0:it.textContent)==null?void 0:wi.trim())!=null?Ot:"",ai=new URL(Ga||o,e).toString(),Bt=(ii=oe.getAttribute("mimeType"))!=null?ii:dr,Wa=(cr=(Ai=oe.getAttribute("codecs"))!=null?Ai:En)!=null?cr:"",Ya;if(xn==="text"){let Nt=oe.getAttribute("id")||"",za=((Il=ac.privateuse)==null?void 0:Il.includes("x-auto"))||Nt.includes("_auto"),si=oe.querySelector("SegmentTemplate");if(si){let hr={representationId:(El=oe.getAttribute("id"))!=null?El:void 0,bandwidth:(xl=oe.getAttribute("bandwidth"))!=null?xl:void 0},Ka=parseInt((Pl=oe.getAttribute("bandwidth"))!=null?Pl:"",10)/1e3,Xa=(Al=parseInt((wl=si.getAttribute("startNumber"))!=null?wl:"",10))!=null?Al:1,Ri=parseInt((kl=si.getAttribute("timescale"))!=null?kl:"",10),Pn=(Rl=si.querySelectorAll("SegmentTimeline S"))!=null?Rl:[],Li=si.getAttribute("media");if(!Li)continue;let Ja=[],Za=0,es="",$i=0,mr=Xa,De=0;for(let at of Pn){let ni=parseInt((Ll=at.getAttribute("d"))!=null?Ll:"",10),ze=parseInt(($l=at.getAttribute("r"))!=null?$l:"",10)||0,Ft=parseInt((Ml=at.getAttribute("t"))!=null?Ml:"",10);De=Number.isFinite(Ft)?Ft:De;let oi=ni/Ri*1e3,qt=De/Ri*1e3;for(let ht=0;ht<ze+1;ht++){let Ut=$t(Li,j($({},hr),{segmentNumber:mr.toString(10),segmentTime:(De+ht*ni).toString(10)})),Mi=(qt!=null?qt:0)+ht*oi,br=Mi+oi;mr++,Ja.push({time:{from:Mi,to:br},url:Ut})}De+=(ze+1)*ni,Za+=(ze+1)*oi}$i=De/Ri*1e3,es=$t(Li,j($({},hr),{segmentNumber:mr.toString(10),segmentTime:De.toString(10)}));let fr={time:{from:$i,to:1/0},url:es},xt={type:"template",baseUrl:ai,segmentTemplateUrl:Li,initUrl:"",totalSegmentsDurationMs:Za,segments:Ja,nextSegmentBeyondManifest:fr,timescale:Ri};Ya={id:Nt,kind:"text",segmentReference:xt,profiles:[],duration:y,bitrate:Ka,mime:"",codecs:"",width:0,height:0,isAuto:za}}else Ya={id:Nt,isAuto:za,kind:"text",url:ai}}else{let Nt=(Cl=(Dl=oe.getAttribute("contentType"))!=null?Dl:Bt==null?void 0:Bt.split("/")[0])!=null?Cl:xn,za=(Ol=(Vl=le.getAttribute("profiles"))==null?void 0:Vl.split(","))!=null?Ol:[],si=parseInt((_l=oe.getAttribute("width"))!=null?_l:"",10),hr=parseInt((Bl=oe.getAttribute("height"))!=null?Bl:"",10),Ka=parseInt((Nl=oe.getAttribute("bandwidth"))!=null?Nl:"",10)/1e3,Xa=(Fl=oe.getAttribute("frameRate"))!=null?Fl:"",Ri=(ql=oe.getAttribute("quality"))!=null?ql:void 0,Pn=Xa?Pv(Xa):void 0,Li=(Ul=oe.getAttribute("id"))!=null?Ul:"id"+(B++).toString(10),Ja=Nt==="video"?`${hr}p`:Nt==="audio"?`${Ka}Kbps`:Wa,Za=`${Li}@${Ja}`,es=[...H,...yS,...za],$i,mr=oe.querySelector("SegmentBase"),De=(Hl=oe.querySelector("SegmentTemplate"))!=null?Hl:IS;if(mr){let xt=(Ql=(jl=oe.querySelector("SegmentBase Initialization"))==null?void 0:jl.getAttribute("range"))!=null?Ql:"",[at,ni]=xt.split("-").map(Ut=>parseInt(Ut,10)),ze={from:at,to:ni},Ft=(Gl=oe.querySelector("SegmentBase"))==null?void 0:Gl.getAttribute("indexRange"),[oi,qt]=Ft?Ft.split("-").map(Ut=>parseInt(Ut,10)):[],ht=Ft?{from:oi,to:qt}:void 0;$i={type:"byteRange",url:ai,initRange:ze,indexRange:ht}}else if(De){let xt={representationId:(Wl=oe.getAttribute("id"))!=null?Wl:void 0,bandwidth:(Yl=oe.getAttribute("bandwidth"))!=null?Yl:void 0},at=parseInt((zl=De.getAttribute("timescale"))!=null?zl:"",10),ni=(Kl=De.getAttribute("initialization"))!=null?Kl:"",ze=De.getAttribute("media"),Ft=(Jl=parseInt((Xl=De.getAttribute("startNumber"))!=null?Xl:"",10))!=null?Jl:1,oi=$t(ni,xt);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");let qt=(Zl=De.querySelectorAll("SegmentTimeline S"))!=null?Zl:[],ht=[],Ut=0,Mi="",br=0;if(qt.length){let ts=Ft,st=0;for(let Di of qt){let mt=parseInt((ec=Di.getAttribute("d"))!=null?ec:"",10),ui=parseInt((tc=Di.getAttribute("r"))!=null?tc:"",10)||0,is=parseInt((ic=Di.getAttribute("t"))!=null?ic:"",10);st=Number.isFinite(is)?is:st;let wn=mt/at*1e3,An=st/at*1e3;for(let rs=0;rs<ui+1;rs++){let PS=$t(ze,j($({},xt),{segmentNumber:ts.toString(10),segmentTime:(st+rs*mt).toString(10)})),sc=(An!=null?An:0)+rs*wn,wS=sc+wn;ts++,ht.push({time:{from:sc,to:wS},url:PS})}st+=(ui+1)*mt,Ut+=(ui+1)*wn}br=st/at*1e3,Mi=$t(ze,j($({},xt),{segmentNumber:ts.toString(10),segmentTime:st.toString(10)}))}else if((0,ka.isNonNullable)(y)){let st=parseInt((rc=De.getAttribute("duration"))!=null?rc:"",10)/at*1e3,Di=Math.ceil(y/st),mt=0;for(let ui=1;ui<Di;ui++){let is=$t(ze,j($({},xt),{segmentNumber:ui.toString(10),segmentTime:mt.toString(10)}));ht.push({time:{from:mt,to:mt+st},url:is}),mt+=st}br=mt,Mi=$t(ze,j($({},xt),{segmentNumber:Di.toString(10),segmentTime:mt.toString(10)}))}let xS={time:{from:br,to:1/0},url:Mi};$i={type:"template",baseUrl:ai,segmentTemplateUrl:ze,initUrl:oi,totalSegmentsDurationMs:Ut,segments:ht,nextSegmentBeyondManifest:xS,timescale:at}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!Bt)continue;let fr={video:"video",audio:"audio",text:"text"}[Nt];if(!fr)continue;ki||(ki=fr),Ya={id:Za,kind:fr,segmentReference:$i,profiles:es,duration:y,bitrate:Ka,mime:Bt,codecs:Wa,width:si,height:hr,fps:Pn,quality:Ri}}be.language||(be.language=_t),be.label||(be.label=pr),be.mime||(be.mime=Bt),be.codecs||(be.codecs=Wa),be.hdr||(be.hdr=ki==="video"&&Ju(Wa)),be.representations.push(Ya)}if(ki){let oe=r[ki].find(_t=>_t.id===be.id);if(oe&&be.representations.every(_t=>Ce(_t.segmentReference)))for(let _t of oe.representations){let pr=be.representations.find(Bt=>Bt.id===_t.id),Ga=pr==null?void 0:pr.segmentReference,ai=_t.segmentReference;ai.segments.push(...Ga.segments),ai.nextSegmentBeyondManifest=Ga.nextSegmentBeyondManifest}else r[ki].push(be)}}return{duration:y,streams:r,baseUrls:n,live:S}};var _v=G(Ke(),1),ol=require("@vkontakte/videoplayer-shared/es2015"),ve=(a,e)=>(0,ol.isNonNullable)(a)&&(0,ol.isNonNullable)(e)&&a.readyState==="open"&&(0,_v.default)([...a.activeSourceBuffers],e);var Ra=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new E.ValueSubject(0);this.currentLowLatencySegmentLength$=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 Re;this.switchAbortController=new Re;this.destroyAbortController=new Re;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 ye(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 Cg(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||!ve(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Qu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,E.assertNonNullable)(i,"No init buffer for starting representation"),(0,E.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,E.abortable)(this.destroyAbortController.signal,function(e,t=!1){return ye(this,null,function*(){if(!ve(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,E.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,E.isNullable)(s)||(0,E.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,E.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ve(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,E.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new as(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,E.abortable)(this.destroyAbortController.signal,function(e,t=!1){return ye(this,null,function*(){if(!ve(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,E.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,E.isNullable)(s)||(0,E.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,E.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ve(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,E.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new as(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 ye(this,null,function*(){var u,l;let t=(u=(0,an.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 m=this.representations.get(c);if(!m||!Ce(m.segmentReference))return;let p=this.getActualLiveStartingSegments(m.segmentReference);this.segments.set(m.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);(0,E.assertNonNullable)(r);let s=this.segments.get(i);(0,E.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,E.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ve(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Re,(0,E.abortable)(this.switchAbortController.signal,function(i,r=!1){return ye(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,E.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,E.isNullable)(o)||(0,E.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,E.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ve(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,E.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!(0,E.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return A(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Re,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,E.isNullable)(e)||(0,E.isNullable)(this.downloadingRepresentationId)||(0,E.isNullable)(this.playingRepresentationId)||(0,E.isNullable)(this.sourceBuffer)||!ve(this.mediaSource,this.sourceBuffer)||(0,E.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,E.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,E.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Qu(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,rn.default)(u,r))c="high";else{let d=(0,or.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,or.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;(0,E.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,an.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,an.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ce(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>j($({},p),{status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,or.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,m=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(m===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(m+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,E.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Ce(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=$t(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&ea&&ea(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ea&&ea(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:m,to:p}},f)=>{let g=m<=i&&p>=i,S=m>i||g||f===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&m<=i+y||p<=i+y;return(d==="none"||d==="partially_ejected"&&S&&I&&this.sourceBuffer&&ve(this.mediaSource,this.sourceBuffer)&&!(Jt(this.sourceBuffer.buffered,m)&&Jt(this.sourceBuffer.buffered,p)))&&S&&I});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=r;d<s.length&&(n<=l||o<=c);d++){let m=s[d];if(n+=m.byte.to+1-m.byte.from,o+=m.time.to+1-m.time.from,m.status==="none"||m.status==="partially_ejected")u.push(m);else break}return u}loadSegments(e,t,i="auto"){return A(this,null,function*(){Ce(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return A(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,E.abortable)(o,function(){return ye(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:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,E.now)(),!c)return;let d=new DataView(c),m=wa(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=m.getChunkEndTime(d,g)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=m.getServerLatencyTimestamps(d);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Aa(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())Ce(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return A(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:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,E.abortable)(n,function(){return ye(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:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,E.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Aa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Ce(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,or.default)(e,0).byte.from,to:(0,or.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>A(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,E.now)(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!Ce(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,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:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,rn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return A(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!ve(this.mediaSource,this.sourceBuffer))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){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=wa(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 A(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ve(this.mediaSource,this.sourceBuffer))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){yield n();continue}let d=c.byte.from-i,m=c.byte.to-i,p=m-d+1,f=d<r,g=m<=r;if(!f)continue;let S=wa(u.mime);if(c.status==="downloading"&&g){c.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(y,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-d),l.loadedBytes>l.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),I=l.loadedBytes===p?y:S.parseFeedableSegmentChunk(y);I!=null&&I.byteLength&&(c.status="partially_fed",l.feedingBytes+=I.byteLength,(yield this.sourceBufferTaskQueue.append(I,s))&&!s.aborted?(l.fedBytes+=I.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!((0,E.isNullable)(this.sourceBuffer)||!ve(this.mediaSource,this.sourceBuffer))){!this.isLive&&ee.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Jt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Jt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:E.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",rl(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");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[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Hu(()=>(0,Bv.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return A(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?(0,E.abortable)(this.destroyAbortController.signal,function(){return ye(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,wa(e.mime),r)).then(o=>A(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 m=c;this.isLive&&Ce(e.segmentReference)&&(m=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,m),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:E.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return A(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,i=!1){return A(this,null,function*(){if(!this.sourceBuffer||!ve(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,E.isNullable)(e))return!1;let r=[],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:m}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,m):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push($({},u.time)),r=n(r);let l=rl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let m of this.segments.values())for(let p of m)(0,rn.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 m={time:{from:l,to:c},url:"",status:"none"};o(m)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return A(this,null,function*(){if(!this.sourceBuffer||!ve(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!ve(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!ve(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,E.isNullable)(e)?0:ir(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ve(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ve(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Hu(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:E.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,E.isNullable)(this.sourceBuffer)||!ve(this.mediaSource,this.sourceBuffer)||(0,E.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(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?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:E.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var La=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Nv=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};var ie=require("@vkontakte/videoplayer-shared/es2015");var Fv=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var nn=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1,useEnableSubtitlesParam:r=!1}){this.lastConnectionType$=new ie.ValueSubject(void 0);this.lastConnectionReused$=new ie.ValueSubject(void 0);this.lastRequestFirstBytes$=new ie.ValueSubject(void 0);this.recoverableError$=new ie.Subject;this.error$=new ie.Subject;this.abortAllController=new Re;this.subscription=new ie.Subscription;this.fetchManifest=(0,ie.abortable)(this.abortAllController.signal,function(e){return ye(this,null,function*(){let t=e;this.requestQuic&&(t=La(t)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(t=Fv(t));let i=yield this.doFetch(t,{signal:this.abortAllController.signal}).catch(sn);return i?(this.onHeadersReceived(i.headers),i.text()):null})}.bind(this));this.fetch=(0,ie.abortable)(this.abortAllController.signal,function(l){return ye(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var Z,D;let c=e,d=new Headers;if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let N=new URL(c,location.href);N.searchParams.append("bytes",`${i.from}-${i.to}`),c=N.toString();break}default:(0,ie.assertNever)(t)}this.requestQuic&&(c=La(c));let m=this.abortAllController.signal,p;if(n){let N=new Re;if(p=(0,ie.merge)((0,ie.fromEvent)(this.abortAllController.signal,"abort"),(0,ie.fromEvent)(n,"abort")).subscribe(()=>{try{N.abort()}catch(M){sn(M)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(M){sn(M)}m=N.signal}let f=(0,ie.now)(),g=yield this.doFetch(c,{priority:s,headers:d,signal:m}),S=(0,ie.now)();if(!g)return p==null||p.unsubscribe(),null;if((Z=this.throughputEstimator)==null||Z.addRawRtt(S-f),!g.ok||!g.body)return p==null||p.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!r&&!o)return p==null||p.unsubscribe(),g.arrayBuffer();let[y,I]=g.body.tee(),x=y.getReader();o&&((D=this.throughputEstimator)==null||D.trackStream(I,u));let w=0,P=new Uint8Array(0),B=!1,H=N=>{p==null||p.unsubscribe(),B=!0,sn(N)},se=(0,ie.abortable)(m,function(ne){return ye(this,arguments,function*({done:N,value:M}){if(w===0&&this.lastRequestFirstBytes$.next((0,ie.now)()-f),m.aborted){p==null||p.unsubscribe();return}if(!N&&M){let ue=new Uint8Array(P.length+M.length);ue.set(P),ue.set(M,P.length),P=ue,w+=M.byteLength,r==null||r(new DataView(P.buffer),w),yield x==null?void 0:x.read().then(se,H)}})}.bind(this));return yield x==null?void 0:x.read().then(se,H),p==null||p.unsubscribe(),B?null:P.buffer})}.bind(this));this.fetchByteRangeRepresentation=(0,ie.abortable)(this.abortAllController.signal,function(e,t,i){return ye(this,null,function*(){var y;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,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,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let m=new DataView(d,r-n,s-n+1);if(!t.validateData(m))throw new Error("Invalid media file");let p=t.parseInit(m),f=(y=e.indexRange)!=null?y: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 I=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!I)return null;g=new DataView(I)}let S=t.parseSegments(g,p,f);return{init:p,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,ie.abortable)(this.abortAllController.signal,function(e,t){return ye(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>j($({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.useEnableSubtitlesParam=r}onHeadersReceived(e){let{type:t,reused:i}=Nv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return A(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:(0,ie.assertNever)(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}doFetch(e,t){return A(this,null,function*(){let i=yield It(e,t);if(i.ok)return i;let r=yield i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ie.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ie.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ie.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ie.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:ie.ErrorCategory.FATAL})}})}},sn=a=>{if(!Aa(a))throw a};var Ti=(a,e,t)=>t*e+(1-t)*a,ul=(a,e)=>a.reduce((t,i)=>t+i,0)/e,qv=(a,e,t,i)=>{let r=0,s=t,n=ul(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var $a=require("@vkontakte/videoplayer-shared/es2015");var ti=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new $a.ValueSubject(e.initial),this.debounced$=new $a.ValueSubject(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=ft(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,$a.isNullable)(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed))}};var on=class extends ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ti(this.slow,e,this.params.emaAlphaSlow),this.fast=Ti(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var un=class extends ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ul(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ti(this.emaSmoothed,e,this.params.emaAlpha);let i=qv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ln=class extends ti{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ti(this.smoothed,t,this.params.emaAlpha):t}};var Ii=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new on({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new un({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new ln($({initial:e,label:"liveEdgeDelay"},t))}};var ll=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var cn=require("@vkontakte/videoplayer-shared/es2015");var Ma=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 i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(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(j($({},r),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ce(t.segmentReference))}};var pn=G(zt(),1);var Da=require("@vkontakte/videoplayer-shared/es2015");var Uv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=ee.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(r.mp4||r.webm);default:return(0,Da.assertNever)(c)}})},dn=a=>{let{webmDecodingInfo:e}=ee.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,Da.assertNever)(a)}return[t,i]},Hv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...dn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ee.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...dn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...dn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...dn(a),...r,"HLS","HLS_ONDEMAND"];default:(0,Da.assertNever)(e)}return ee.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},jv=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=ee.device.isMac&&ee.browser.isSafari;if(ee.device.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,Da.assertNever)(a)}else ee.video.nativeHlsSupported&&!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"]},cl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Qv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,pn.default)(t.value.split("."),0)}for(let t of a){let i=(0,pn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,pn.default)(e.value.split("."),0)};var XR=["timeupdate","progress","play","seeked","stalled","waiting"],JR=["timeupdate","progress","loadeddata","playing","seeked"];var hn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new Y("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.isActiveLive$=new v.ValueSubject(!1);this.isLowLatency$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveSeekableDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(0);this.liveStreamStatus$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLatency$=new v.ValueSubject(void 0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.currentStallDuration$=new v.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new v.ValueSubject(0);this.fetcherRecoverableError$=new v.Subject;this.fetcherError$=new v.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new Re;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,i){return ye(this,null,function*(){var r;this.element=e,this.manifestUrlString=ke(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:v.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,function(){return ye(this,null,function*(){var n,o;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Ov(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Lg(e))!=null?n:{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,m,p,f;return!!((m=(d=this.element)==null?void 0:d.canPlayType)!=null&&m.call(d,l)&&((f=(p=ct())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,m=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*m),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),d=new Set(c.map(({codecs:p})=>p)),m=Qv(d);if(m&&(r[u]=c.filter(({codecs:p})=>p.startsWith(m))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(S=>S.hdr),g=r.video.some(S=>!S.hdr);ee.display.isHDR&&p&&f?r.video=r.video.filter(S=>S.hdr):g&&(r.video=r.video.filter(S=>!S.hdr))}}return j($({},t),{streams:r})})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,i){return ye(this,null,function*(){var m;(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(f=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?mb():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Gs())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new Ra("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((f,g)=>[...f,...g.representations],[]);this.audioBufferManager=new Ra("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ma.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ma(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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,v.merge)(...JR.map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?ir(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,v.merge)((0,v.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,v.filterChanged)()).subscribe(f=>this.liveStreamEndTimestamp=(0,v.now)())),this.subscription.add((0,v.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,v.interval)(1e3).subscribe(f=>{let g=Fs(this.manifestUrlString,2);this.manifestUrlString=ke(this.manifestUrlString,g+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,v.fromEvent)(this.element,"play").subscribe(f=>{var g;return(g=this.livePauseWatchdogSubscription)==null?void 0:g.unsubscribe()})),this.representationSubscription.add((0,v.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.map)(({isActiveLive:f,isLowLatency:g})=>f&&g),(0,v.filterChanged)()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ll(this.element,1)})),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.filter)(({bufferLength:f,isActiveLive:g,isLowLatency:S})=>g&&S&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let g=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(g,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add((0,v.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,v.filter)(({isLive:f})=>f),(0,v.filterChanged)((f,g)=>g.bufferLength<f.bufferLength),(0,v.map)(({rtt:f,bufferLength:g,segmentServerLatency:S})=>{let y=Fs(this.manifestUrlString,2);return(f/2+g+S+y)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,v.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:g,isLowLatency:S})=>{if(!S||!g)return;let y=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,I=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=f-y;if(this.isManualDecreasePlaybackInLive())return;let P=1;Math.abs(w)>I&&(P=1+Math.sign(w)*x),ll(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var S,y;let g=0;if(f){let I=((y=(S=this.element)==null?void 0:S.currentTime)!=null?y:0)*1e3;g=Math.min(...this.bufferManagers.map(w=>{var P,B;return(B=(P=w.getLiveSegmentsToLoadState(this.manifest))==null?void 0:P.to)!=null?B:I}))-I}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(S=>A(this,[S],function*({liveLoadBufferLength:f,bufferLength:g}){if(!this.element||this.isUpdatingLive)return;let y=this.element.playbackRate,I=Fs(this.manifestUrlString,2),x=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,w=Math.min(x,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*y),P=this.tuning.dashCmafLive.normalizedActualBufferOffset*y,B=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,H=isFinite(f)?f:g,se=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),Z=x<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(Z);let D="none";if(se?D="active_low_latency":this.isLowLatency$.getValue()&&Z?(this.bufferManagers.forEach(N=>N.proceedLowLatencyLive()),D="active_low_latency"):I!==0&&H<w?D="live_forward_buffering":H<w+B&&(D="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),D==="live_forward_buffering"||D==="live_with_target_offset"){let N=p-(w+P),M=this.normolizeLiveOffset(Math.trunc(I+N/y)),ne=Math.abs(M-I),ue=0;!f||ne<=this.tuning.dashCmafLive.offsetCalculationError?ue=I:M>0&&ne>this.tuning.dashCmafLive.offsetCalculationError&&(ue=M),this.manifestUrlString=ke(this.manifestUrlString,ue,2)}(D==="live_with_target_offset"||D==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:v.ErrorCategory.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=(0,v.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,v.filterChanged)(),(0,v.map)(({allBuffersFull:p,someBufferEnded:f})=>p&&f),(0,v.filter)(p=>p));if(this.representationSubscription.add((0,v.merge)(this.forceEnded$,d).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:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add((0,v.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"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((f,g)=>{var S;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var y;if(((y=this.source)==null?void 0:y.readyState)==="open"){f();return}this.tuning.dash.rejectOnSourceOpenTimeout?g(new Error("Timeout reject when wait sourceopen event")):f()},this.tuning.dash.sourceOpenTimeout)),(S=this.source)==null||S.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(m=this.manifest.duration)!=null?m:0,...(0,pl.default)((0,pl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let g=[];return f.duration&&g.push(f.duration),Ce(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&g.push(f.segmentReference.totalSegmentsDurationMs),g})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,v.isNonNullable)(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new nn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ii.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,$({},e.tuning.dashCmafLive.lowLatency.bufferEstimator))}seekLive(e){return A(this,null,function*(){var r,s,n;(0,v.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,v.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ke(this.manifestUrlString,i,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(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...XR.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Jt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,g,S,y,I,x,w,P,B,H;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=(0,v.now)(),n=100,o=(g=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(y=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?y:0,l=(x=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?x:0,c=(P=(w=this.audioBufferManager)==null?void 0:w.getForwardBufferDuration())!=null?P:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,m=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||m)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let se=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(se).catch(Z=>{this.error$.next({id:"stallIntervalCallback",category:v.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:Z})}),r.liveLastOffset=se}else{let se=this.element.currentTime*1e3;(B=this.videoBufferManager)==null||B.maintain(se),(H=this.audioBufferManager)==null||H.maintain(se),r.position=se}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return A(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return A(this,null,function*(){var r,s,n,o,u;(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Jt(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!((0,v.isNullable)(this.element)||(0,v.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3)})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;(0,v.isNonNullable)(this.element)&&(0,v.isNonNullable)(this.source)&&(0,v.isNonNullable)(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return A(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue();this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r.push(1/0):r.push(o.to));if(r.length){let n=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():this.element.currentTime=n/1e3}}};var mn=class{constructor(e,t){this.fov=e,this.orientation=t}};var fn=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/ft(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=$({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*ft(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Wv=`attribute vec2 a_vertex;
|
|
71
71
|
attribute vec2 a_texel;
|
|
72
72
|
|
|
73
73
|
varying vec2 v_texel;
|
|
@@ -78,7 +78,7 @@ void main(void) {
|
|
|
78
78
|
// save texel vector to pass to fragment shader
|
|
79
79
|
v_texel = a_texel;
|
|
80
80
|
}
|
|
81
|
-
`;var
|
|
81
|
+
`;var Yv=`#ifdef GL_ES
|
|
82
82
|
precision highp float;
|
|
83
83
|
precision highp int;
|
|
84
84
|
#else
|
|
@@ -121,6 +121,6 @@ void main(void) {
|
|
|
121
121
|
// sample using new coordinates
|
|
122
122
|
gl_FragColor = texture2D(u_texture, tc);
|
|
123
123
|
}
|
|
124
|
-
`;var yn=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 vn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Sn(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(sS,this.gl.VERTEX_SHADER),r=this.createShader(nS,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 Ie=require("@vkontakte/videoplayer-shared/es2015"),yl=class{constructor(){this.isSeeked$=new Ie.ValueSubject(!1);this.isBuffering$=new Ie.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Ie.Subscription;this.severeStallOccurred$=new Ie.ValueSubject(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add((0,Ie.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,Ie.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,Ie.combine)({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if((0,Ie.isNullable)(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=(0,Ie.now)(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Ie.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Ie.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},oS=yl;var je=require("@vkontakte/videoplayer-shared/es2015"),Tn=class{constructor(){this.subscription=new je.Subscription;this.pipSize$=new je.ValueSubject(void 0);this.videoSize$=new je.ValueSubject(void 0);this.elementSize$=new je.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=je.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,je.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,je.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,je.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 Pr=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new Y("stopped");this.droppedFramesManager=new rn;this.stallsManager=new oS;this.elementSizeManager=new Tn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new zi;this.audioTrackSwitchHistory=new zi;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(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(i.position,i.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(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"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&$(this.params.desiredState.playbackState,"ready");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"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return(0,H.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new yn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new et(e.source.url),this.params=e,this.video=Ne(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(xe(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 gn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Ue(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:H.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,H.filter)(l=>!!l.length),(0,H.once)()).subscribe(l=>{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:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,H.map)(l=>l.to.state!=="none"),(0,H.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,H.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.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,H.filter)(H.isNonNullable),(0,H.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,H.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(yt(this.video,t.isLooped,i)),this.subscription.add(qe(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(tt(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),d=this.player.getCodecs();if((0,H.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of c.audio){m.push(ol(f));let g=[];for(let v of f.representations){let T=Nv(v);g.push(T),this.audioTracksMap.set(T,{stream:f,representation:v})}this.audioStreamsMap.set(f,g)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of c.video){h.push(ul(m));let f=[];for(let g of m.representations){let v=Bv(N(L({},g),{streamId:m.id}));v&&(f.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,f)}this.params.output.availableVideoStreams$.next(h);for(let m of c.text)for(let f of m.representations){let g=Fv(m,f);this.textTracksMap.set(g,{stream:m,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),d!=null&&d.video&&this.params.output.availableVideoCodecs$.next(d.video),d!=null&&d.audio&&this.params.output.availableAudioCodecs$.next(d.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add((0,H.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,H.fromEvent)(this.video,"progress")).subscribe(()=>k(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,uS.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[h,m]=d,f=[...this.videoTracksMap.keys()].find(v=>{var T;return((T=this.videoTracksMap.get(v))==null?void 0:T.representation.id)===h.id});(0,H.isNonNullable)(f)&&(this.stallsManager.lastVideoTrackSelected=f);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")yield this.player.initRepresentations(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",h.id),m){let v=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",m.id,v)}}),i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,H.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:h}]=c,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(ul(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,H.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:h}]=c,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(ol(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.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 o=t.playbackState.stateChangeStarted$.pipe((0,H.map)(({to:l})=>l==="ready"),(0,H.filterChanged)());this.subscription.add((0,H.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,H.merge)(o,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,H.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var q,pe,j,te,re,B,ie,J,oe,R,P,W,se;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(q=e.videoTrack.getState())==null?void 0:q.id,n=[...this.videoTracksMap.keys()].find(({id:Z})=>Z===i),o=t.currentVideoTrack$.getValue(),u=((te=(j=e.videoStream.getState())!=null?j:n&&((pe=this.videoTracksMap.get(n))==null?void 0:pe.stream))!=null?te:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:Z})=>Z===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=It(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(h,m||1/0),1),g=(re=e.audioStream.getState())!=null?re:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(B=[...this.audioStreamsMap.keys()].find(({id:Z})=>Z===(g==null?void 0:g.id)))!=null?B:this.audioStreamsMap.keys().next().value,T=0;if(v){if(n&&!r){let Z=en(n,c,(ie=this.audioStreamsMap.get(v))!=null?ie:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(J=Z==null?void 0:Z.bitrate)!=null?J:-1/0)}if(o){let Z=en(o,c,(oe=this.audioStreamsMap.get(v))!=null?oe:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(R=Z==null?void 0:Z.bitrate)!=null?R:-1/0)}}let I=Jt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),x=r?I!=null?I:n:n!=null?n:I,w=v&&Ub(x,c,(P=this.audioStreamsMap.get(v))!=null?P:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=(W=this.videoTracksMap.get(x))==null?void 0:W.representation,_=w&&((se=this.audioTracksMap.get(w))==null?void 0:se.representation);if(A&&_)return[A,_];if(A&&!_&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:H.ErrorCategory.DOM,thrown:e}))}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),this.params.output.currentVideoStream$.next(void 0),Fe(this.video),this.tracer.end()}};var Ba=class extends Pr{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 he=require("@vkontakte/videoplayer-shared/es2015");var Na=class extends Pr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:r,desiredState:i,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(r.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new he.ValueSubject(1);s(r.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe((0,he.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,he.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,he.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add((0,he.combine)({position:t.position$,liveStreamStatus:this.player.liveStreamStatus$}).subscribe(({position:o,liveStreamStatus:u})=>t.isLiveEnded$.next(u!=="active"&&o===0))).add((0,he.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,he.merge)(r.playbackRateState$,new he.ValueSubject(1))}).pipe((0,he.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||(0,he.isNullable)(l)||(e=o-l)})).add((0,he.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,he.merge)(r.playbackRateState$,new he.ValueSubject(1))}).pipe((0,he.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||(0,he.isNullable)(o)||(0,he.isNullable)(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=qv(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(r).then(()=>{this.params.output.position$.next(e/1e3)})}};var lS=Q(Hs(),1);var X=require("@vkontakte/videoplayer-shared/es2015");var pt={};var li=(a,e)=>new X.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Fa=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new Y("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,X.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,X.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,X.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,X.assertNever)(e)}break;default:(0,X.assertNever)(t)}};this.textTracksManager=new et(e.source.url),this.video=Ne(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(xe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:X.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,lS.default)(import("hls.js").then(i=>{e||(pt.Hls=i.default,pt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,X.assertNonNullable)(pt.Hls,"hls.js not loaded"),this.hls=new pt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,X.assertNonNullable)(pt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:X.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ue(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(yt(this.video,e.isLooped,r)),this.subscription.add(qe(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(tt(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,X.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(li(this.hls,pt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:X.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"),$(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(li(this.hls,pt.Events.MANIFEST_PARSED).pipe((0,X.map)(({levels:l})=>l.reduce((c,d)=>{var I,x;let h=d.name||d.height.toString(10),{width:m,height:f}=d,g=(x=Kt((I=d.attrs.QUALITY)!=null?I:""))!=null?x:(0,X.videoSizeToQuality)({width:m,height:f});if(!g)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:h.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:m,height:f},fps:v};return this.trackLevels.set(h,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(li(this.hls,pt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,m=d.attrs.URI||"",f=d.lang;c.push({id:h,url:m,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(li(this.hls,pt.Events.LEVEL_LOADING).pipe((0,X.map)(({url:l})=>xe(l))),t.hostname$),s(li(this.hls,pt.Events.FRAG_CHANGED),l=>{var h,m,f,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((m=c==null?void 0:c.startPTS)!=null?m: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(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=li(this.hls,pt.Events.LEVEL_SWITCHED).pipe((0,X.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,X.filter)(X.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(zt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if((0,X.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,m=this.hls.levels[h];!m||c.bitrate>m.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,X.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,X.observableFrom)(["init"])).pipe((0,X.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 k(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),$(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"),$(this.params.desiredState.playbackState,"stopped",!0)}};var cS="X-Playback-Duration",Tl=a=>k(void 0,null,function*(){var i;let e=yield Et(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(cS)?parseInt(e.headers.get(cS),10):void 0});var K=require("@vkontakte/videoplayer-shared/es2015");var El=Q(Bo(),1);var In=require("@vkontakte/videoplayer-shared/es2015");var b$=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,In.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},g$=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
-
`),
|
|
126
|
-
`),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),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,Xe.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([N(L({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return k(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new $e;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 k(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:Xe.ErrorCategory.WTF,thrown:t,message:e})}};var qa=class{constructor(e){this.subscription=new K.Subscription;this.videoState=new Y("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new K.ValueSubject([]);this.liveOffset=new Sr;this.manifestStartTime$=new K.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"),$(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"?$(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),$(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"&&$(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"&&($(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,K.assertNever)(t)}};var r;this.params=e,this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:K.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,s)=>En(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 xn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new et(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:K.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:K.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(xe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new K.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:K.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ue(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(qe(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(tt(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"),$(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(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,K.filterChanged)(),(0,K.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,K.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(m=>m.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(xe(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,K.combine)({startTime:this.manifestStartTime$.pipe((0,K.filter)(K.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,K.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,K.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,K.observableFrom)(["init"])).pipe((0,K.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,K.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[h,m]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(h||""));m&&h&&i.searchParams.set(m,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Le(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Tl(n).then(c=>{var d;if(!(0,K.isNullable)(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,K.isNullable)(h)||!isFinite(h))&&Et(n).then(m=>m.text()).then(m=>{var g;let f=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(m))==null?void 0:g[1];if(f){let v=new URL(f,n).toString();Tl(v).then(T=>{(0,K.isNullable)(T)||this.maxSeekBackTime$.next(T)})}}).catch(()=>{})}})}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:K.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();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=Le(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 ae=require("@vkontakte/videoplayer-shared/es2015");var Ua=class{constructor(e){this.subscription=new ae.Subscription;this.videoState=new Y("stopped");this.manifests$=new ae.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"),$(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"?$(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),$(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"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,ae.assertNever)(t)}};this.textTracksManager=new et(e.source.url),this.params=e,this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ae.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(xe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),En(Le(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:ae.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||!i.from)&&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:ae.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ue(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,ae.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(yt(this.video,t.isLooped,r)),this.subscription.add(qe(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"),$(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(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 m;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,ae.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(xe(g.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(m=this.params.output.element$.getValue())==null?void 0:m.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,ae.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)),!z.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,ae.merge)((0,ae.fromEvent)(o,"addtrack"),(0,ae.fromEvent)(o,"removetrack"),(0,ae.fromEvent)(o,"change"),(0,ae.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,ae.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ae.observableFrom)(["init"])).pipe((0,ae.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,ae.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(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ae.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var pS=Q(Qr(),1),xl=Q(ti(),1),hS=Q(yr(),1);var de=require("@vkontakte/videoplayer-shared/es2015");var Ha=class{constructor(e){this.subscription=new de.Subscription;this.videoState=new Y("stopped");this.trackUrls={};this.textTracksManager=new et;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.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"),$(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);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?$(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),$(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"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return(0,de.assertNever)(e)}};this.params=e,this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),(0,pS.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,xl.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:de.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ue(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,de.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(yt(this.video,t.isLooped,r)),this.subscription.add(qe(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(tt(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(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,de.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,de.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,de.observableFrom)(["init"])).pipe((0,de.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),Fe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,de.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,de.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Da(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(xe(t))}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:de.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=d=>{let h=Jt(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(h)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,xl.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Yi({limits:e,lowestAvailableQuality:(c=(0,hS.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?(0,de.isLowerOrEqual)(i,e.max):!0,u=e.min?(0,de.isHigherOrEqual)(i,e.min):!0;o&&u||r(e)}};var me=require("@vkontakte/videoplayer-shared/es2015");var fS=require("@vkontakte/videoplayer-shared/es2015");var mS=["stun:videostun.mycdn.me:80"],S$=1e3,y$=3,Pl=()=>null,Pn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Pl;this.externalStopCallback=Pl;this.externalErrorCallback=Pl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return k(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return k(this,null,function*(){try{let e={iceServers:[{urls:mS}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return k(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return k(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:fS.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return k(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return k(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),S$)}normalizeOptions(e={}){let t={stunServerList:mS,maxRetryNumber:y$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ja=class{constructor(e){this.videoState=new Y("stopped");this.maxSeekBackTime$=new me.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"),$(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"),$(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"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return(0,me.assertNever)(e)}};this.subscription=new me.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ne(e.container,e.tuning),this.liveStreamClient=new Pn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:me.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(0,me.merge)(this.videoState.stateChangeStarted$.pipe((0,me.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,me.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ue(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(tt(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(qe(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,me.assertNever)(n.to)}},r)).add((0,me.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,me.observableFrom)(["init"])).pipe((0,me.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(xe(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:me.VideoQuality.INVARIANT}),this.video.srcObject=e,$(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:me.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:me.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ci=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};var y=require("@vkontakte/videoplayer-shared/es2015");var Dt=require("@vkontakte/videoplayer-shared/es2015"),bS=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 rt=require("@vkontakte/videoplayer-shared/es2015");function gS(){return new(window.AudioContext||window.webkitAudioContext)}var Qa=class Qa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new $e;this.subscriptions=new rt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,rt.filter)(s=>!!s.type),(0,rt.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){z.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,rt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,rt.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,rt.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 k(this,null,function*(){let{volumeMultiplier:t}=this,r=gS();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Qa.errorId,category:rt.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Qa.errorId} exception`,thrown:e})}};Qa.errorId="VolumeMultiplierManager";var di=Qa;var T$={chunkDuration:5e3,maxParallelRequests:5},Ga=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),availableVideoCodecs$:new y.ValueSubject([]),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),availableAudioCodecs$: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,fetcherError$:new y.Subject,fetcherRecoverableError$: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),isLiveEnded$:new y.ValueSubject(null),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),severeStallOccurred$:new y.Subject,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=Jv([...eS(this.params.tuning),...Zv(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,wl.default)(i,l)),...t.filter(l=>(0,wl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new ci(s);let n=[...gl(!0),...gl(!1)];this.chromecastFormatsIterator=new ci(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&&di.isSupported()&&(this.volumeMultiplierManager=new di(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new ci(e))}))}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()}switchToNextVideoCodec(){console.log("%cStart switchToNextVideoCodec","color: red; background-color: yellow; font-size: 20px;"),this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider(),console.log("%cEnd switchToNextVideoCodec","color: red; background-color: yellow; font-size: 20px;")}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){var o;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 u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(u),new Ba(N(L({},n),{source:u,sourceHls:l,forceVideoCodec:(o=this.videoCodecsIterator)==null?void 0:o.getValue()}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(u),new Na(N(L({},n),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(u),z.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Ua(N(L({},n),{source:u})):new Fa(N(L({},n),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(u),new qa(N(L({},n),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(u),new Ha(N(L({},n),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(u),new Jb(N(L({},n),{source:u,config:N(L({},T$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(u),new ja({container:r,source:u,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 Gi({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 N(L({},e),{url:r(e.url)})}return(0,SS.default)((0,vS.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))),bS({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.providerOutput.fetcherError$.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=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast(),h=l&&!u&&(o&&t||!c);n=N(L({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:h,canReinitProvider:c}),c?(r++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var O=require("@vkontakte/videoplayer-shared/es2015");var I$=5e3,yS="one_video_throughput",TS="one_video_rtt",Vt=window.navigator.connection,IS=()=>{let a=Vt==null?void 0:Vt.downlink;if((0,O.isNonNullable)(a)&&a!==10)return a*1e3},ES=()=>{let a=Vt==null?void 0:Vt.rtt;if((0,O.isNonNullable)(a)&&a!==3e3)return a},xS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Al=class a{constructor(e){this.subscription=new O.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(yS)||(e.useBrowserEstimation?IS():void 0)||I$,r=(s=(i=a.load(TS))!=null?i:e.useBrowserEstimation?ES():void 0)!=null?s:0;if(this.throughput$=new O.ValueSubject(t),this.rtt$=new O.ValueSubject(r),this.rttAdjustedThroughput$=new O.ValueSubject(xS(t,r,e.rttPenaltyRequestSize)),this.throughput=xr.getSmoothedValue(t,-1,e),this.rtt=xr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=IS();u&&this.throughput.next(u);let l=ES();(0,O.isNonNullable)(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add((0,O.fromEvent)(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{O.safeStorage.set(yS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{O.safeStorage.set(TS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,O.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,O.map)(({throughput:n,rtt:o})=>xS(n,o,e.rttPenaltyRequestSize)),(0,O.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,O.now)(),i=new O.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,O.fromEvent)(e,"progress").pipe((0,O.once)()).subscribe(s=>{t=s.loaded,r=(0,O.now)()}));break;case 1:case 0:i.add((0,O.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,O.now)()}));break}i.add((0,O.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,O.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=(0,O.now)(),n=0,o=(0,O.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>k(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,(0,O.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let m=(0,O.now)();if(m-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||m-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,O.now)()}else n+=d.byteLength;o=(0,O.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,O.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,O.now)()-o,this.concurrentDownloads.size),n=0,o=(0,O.now)());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=O.safeStorage.get(e);if((0,O.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},PS=Al;var wr=require("@vkontakte/videoplayer-shared/es2015");var wS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:wr.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:wr.VideoQuality.Q_720P,trafficSavingLimit:wr.VideoQuality.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:wr.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,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:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1},AS=a=>{var e;return N(L({},(0,wr.fillWithDefault)(a,wS)),{configName:[...(e=a.configName)!=null?e:[],...wS.configName]})};var p=require("@vkontakte/videoplayer-shared/es2015");var _t=require("@vkontakte/videoplayer-shared/es2015"),kl=({seekState:a,position$:e})=>(0,_t.merge)(a.stateChangeEnded$.pipe((0,_t.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,_t.filter)(_t.isNonNullable)),e.pipe((0,_t.filter)(()=>a.getState().state==="none")));var kS=require("@vkontakte/videoplayer-shared/es2015"),LS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,kS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var wn=require("@vkontakte/videoplayer-shared/es2015"),$S=(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,wn.filter)(i=>i.length>0),(0,wn.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Wa=class{constructor(e={configName:[]},t=p.Tracer.createRootTracer(!1)){this.subscription=new p.Subscription;this.logger=new p.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new p.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInited=new p.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Y("stopped"),seekState:new Y({state:"none"}),volume:new Y({volume:1,muted:!1}),videoTrack:new Y(void 0),videoStream:new Y(void 0),audioStream:new Y(void 0),autoVideoTrackSwitching:new Y(!0),autoVideoTrackLimits:new Y({}),isLooped:new Y(!1),isLowLatency:new Y(!1),playbackRate:new Y(1),externalTextTracks:new Y([]),internalTextTracks:new Y([]),currentTextTrack:new Y(void 0),textTrackCuesSettings:new Y({}),cameraOrientation:new Y({x:0,y:0})};this.info={playbackState$:new p.ValueSubject(void 0),position$:new p.ValueSubject(0),duration$:new p.ValueSubject(1/0),muted$:new p.ValueSubject(!1),volume$:new p.ValueSubject(1),availableVideoStreams$:new p.ValueSubject([]),currentVideoStream$:new p.ValueSubject(void 0),availableQualities$:new p.ValueSubject([]),availableQualitiesFps$:new p.ValueSubject({}),currentQuality$:new p.ValueSubject(void 0),isAutoQualityEnabled$:new p.ValueSubject(!0),autoQualityLimitingAvailable$:new p.ValueSubject(!1),autoQualityLimits$:new p.ValueSubject({}),predefinedQualityLimitType$:new p.ValueSubject("unknown"),availableAudioStreams$:new p.ValueSubject([]),currentAudioStream$:new p.ValueSubject(void 0),availableAudioTracks$:new p.ValueSubject([]),isAudioAvailable$:new p.ValueSubject(!0),currentPlaybackRate$:new p.ValueSubject(1),currentBuffer$:new p.ValueSubject({start:0,end:0}),isBuffering$:new p.ValueSubject(!0),isStalled$:new p.ValueSubject(!1),isEnded$:new p.ValueSubject(!1),isLooped$:new p.ValueSubject(!1),isLive$:new p.ValueSubject(void 0),isLiveEnded$:new p.ValueSubject(null),canChangePlaybackSpeed$:new p.ValueSubject(void 0),atLiveEdge$:new p.ValueSubject(void 0),atLiveDurationEdge$:new p.ValueSubject(void 0),liveTime$:new p.ValueSubject(void 0),liveBufferTime$:new p.ValueSubject(void 0),liveLatency$:new p.ValueSubject(void 0),currentFormat$:new p.ValueSubject(void 0),availableTextTracks$:new p.ValueSubject([]),currentTextTrack$:new p.ValueSubject(void 0),throughputEstimation$:new p.ValueSubject(void 0),rttEstimation$:new p.ValueSubject(void 0),videoBitrate$:new p.ValueSubject(void 0),hostname$:new p.ValueSubject(void 0),httpConnectionType$:new p.ValueSubject(void 0),httpConnectionReused$:new p.ValueSubject(void 0),surface$:new p.ValueSubject("none"),chromecastState$:new p.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new p.ValueSubject(void 0),intrinsicVideoSize$:new p.ValueSubject(void 0),availableSources$:new p.ValueSubject(void 0),is3DVideo$:new p.ValueSubject(!1),currentVideoSegmentLength$:new p.ValueSubject(0),currentAudioSegmentLength$:new p.ValueSubject(0)};this.events={inited$:new p.Subject,ready$:new p.Subject,started$:new p.Subject,playing$:new p.Subject,paused$:new p.Subject,stopped$:new p.Subject,willStart$:new p.Subject,willResume$:new p.Subject,willPause$:new p.Subject,willStop$:new p.Subject,willDestruct$:new p.Subject,watchCoverageRecord$:new p.Subject,watchCoverageLive$:new p.Subject,managedError$:new p.Subject,fatalError$:new p.Subject,fetcherRecoverableError$:new p.Subject,ended$:new p.Subject,looped$:new p.Subject,seeked$:new p.Subject,willSeek$:new p.Subject,autoplaySoundProhibited$:new p.Subject,firstBytes$:new p.Subject,loadedMetadata$:new p.Subject,firstFrame$:new p.Subject,canplay$:new p.Subject,log$:new p.Subject,fetcherError$:new p.Subject,severeStallOccured$:new p.Subject};this.experimental={element$:new p.ValueSubject(void 0),tuningConfigName$:new p.ValueSubject([]),enableDebugTelemetry$:new p.ValueSubject(!1),dumpTelemetry:Vb,getCurrentTime$:new p.ValueSubject(null)};if(this.initLogs(),this.tuning=AS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new fs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new PS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new p.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,(m,f)=>{let g=typeof f;return(0,RS.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:p.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i;this.config=e,(i=this.internalsExposure)==null||i.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,c;let o=e,{container:s}=o,n=fc(o,["container"]);this.tracer.log("initVideo",(0,p.flattenObject)(n)),this.domContainer=LS(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ga({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},r=()=>{this.tuning.asyncResolveClientChecker?z.isInited$.pipe((0,p.filter)(s=>!!s),(0,p.once)()).subscribe(()=>{console.log("Core SDK async start"),t()}):t()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,p.fromEvent)(document,"visibilitychange").pipe((0,p.once)()).subscribe(r)):r(),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(){return this.playerInited.pipe((0,p.filter)(e=>!!e),(0,p.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.playerInited.pipe((0,p.filter)(e=>!!e),(0,p.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.playerInited.pipe((0,p.filter)(e=>!!e),(0,p.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.playerInited.pipe((0,p.filter)(e=>!!e),(0,p.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.playerInited.pipe((0,p.filter)(r=>!!r),(0,p.once)()).subscribe(()=>{let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.playerInited.pipe((0,p.filter)(r=>!!r),(0,p.once)()).subscribe(()=>{let r=this.desiredState.volume,i=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||i;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:s}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):r.startTransitionTo({volume:e,muted:s})}),this}setMuted(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{let t=this.tuning.isAudioDisabled||e,r=this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:t,volume:r,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:r,muted:t})}),this}setVideoStream(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{(0,p.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();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,p.filter)(r=>r.length>0),(0,p.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,p.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}this.setAutoQualityLimits(i)}),this}setPlaybackRate(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{var r;(0,p.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)}),this}setExternalTextTracks(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,p.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>L({type:"external"},t)))}),this}selectTextTrack(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{var t;$S(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.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",L({},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.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.playerInited.pipe((0,p.filter)(r=>!!r),(0,p.once)()).subscribe(()=>{let r=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.playerInited.pipe((0,p.filter)(r=>!!r),(0,p.once)()).subscribe(()=>{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})}}),this}holdCamera(){return this.playerInited.pipe((0,p.filter)(e=>e),(0,p.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.playerInited.pipe((0,p.filter)(e=>!!e),(0,p.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,p.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,p.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,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,p.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Du({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.filter)(({from:e})=>e==="stopped"),(0,p.once)()).subscribe(()=>{this.initedAt=(0,p.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,p.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(N(L({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:p.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,p.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,p.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,p.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,p.map)(n=>n.destination),(0,p.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,p.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,p.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,p.isInvariantQuality)(u)?1:(0,p.isInvariantQuality)(l)?-1:(0,p.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,p.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,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,p.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,p.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,p.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,p.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,p.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.isLiveEnded$.pipe((0,p.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).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,p.combine)({hasLiveOffsetByPaused:(0,p.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,p.map)(n=>n.to),(0,p.filterChanged)(),(0,p.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,p.combine)({atLiveEdge:(0,p.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,p.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,p.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,p.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,p.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,p.filterChanged)(),(0,p.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.muted),(0,p.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,p.map)(n=>n.volume),(0,p.filterChanged)()).subscribe(this.info.volume$)).add(kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,p.merge)(e.providerOutput.endedEvent$.pipe((0,p.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,p.mapTo)(!1))).pipe((0,p.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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,p.map)(n=>({id:n?`No${n}`:"NoProviders",category:p.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,p.once)(),(0,p.map)(n=>n!=null?n:(0,p.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,p.once)(),(0,p.map)(()=>(0,p.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 p.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new p.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.filter)(({to:n})=>n==="playing"),(0,p.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,p.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,p.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,p.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,p.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,p.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,p.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 p.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,p.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,p.filter)(r=>r.length>0),(0,p.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;let t;this.wasSetStartedQuality=!0;let r=(i=this.explicitInitialQuality)!=null?i:this.info.currentQuality$.getValue();r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=Jt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,p.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,p.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,p.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,p.assertNonNullable)(this.providerContainer),(0,p.assertNonNullable)(e),Db(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Cb(r)),this.providerContainer.current$.subscribe(({type:r})=>Wi("provider",r)),e.duration$.subscribe(r=>Wi("duration",r)),e.availableVideoTracks$.pipe((0,p.filter)(r=>!!r.length),(0,p.once)()).subscribe(r=>Wi("tracks",r)),this.events.fatalError$.subscribe(new De("fatalError")),this.events.managedError$.subscribe(new De("managedError")),e.position$.subscribe(new De("position")),e.currentVideoTrack$.pipe((0,p.map)(r=>r==null?void 0:r.quality)).subscribe(new De("quality")),this.info.currentBuffer$.subscribe(new De("buffer")),e.isBuffering$.subscribe(new De("isBuffering"))].forEach(r=>this.subscription.add(r)),Wi("codecs",z.video.supportedCodecs)}initTracerSubscription(){let e=(0,p.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,p.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,p.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,p.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,p.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,p.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,p.filter)(r=>r>0),(0,p.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,p.filter)(r=>r>0),(0,p.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,p.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,p.filter)(r=>r.end>0),(0,p.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,p.filterChanged)())}).pipe((0,p.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,p.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,p.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,p.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,p.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,p.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,p.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,p.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,p.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,p.filterChanged)(),(0,p.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,p.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,p.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,p.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,p.filterChanged)(),(0,p.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=()=>k(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:p.ErrorCategory.DOM,message:String(i)})})});this.subscription.add((0,p.merge)((0,p.fromEvent)(document,"visibilitychange"),(0,p.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,p.flattenObject)({quality:t,availableTracks:(0,p.flattenObject)(e),track:(0,p.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}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Zi()}};var xt=require("@vkontakte/videoplayer-shared/es2015"),E$=`@vkontakte/videoplayer-core@${Cn}`;
|
|
124
|
+
`;var bn=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new mn(this.params.fov,this.params.orientation),this.cameraRotationManager=new fn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Wv,this.gl.VERTEX_SHADER),i=this.createShader(Yv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,m=t+r;return[s,n,o,u,l,c,d,m]}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 Se=require("@vkontakte/videoplayer-shared/es2015"),hl=class{constructor(){this.isSeeked$=new Se.ValueSubject(!1);this.isBuffering$=new Se.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Se.Subscription;this.severeStallOccurred$=new Se.ValueSubject(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add((0,Se.combine)({isBuffering:this.isBuffering$.pipe((0,Se.debounce)(this.qualityLimitsOnStall.stallDurationToBeCount)),isSeeked:this.isSeeked$}).pipe((0,Se.filter)(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add((0,Se.combine)({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if((0,Se.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,Se.now)(),d=r&&this.currentStallsCount>=r,m=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||m)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,Se.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,Se.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},zv=hl;var Ue=require("@vkontakte/videoplayer-shared/es2015"),gn=class{constructor(){this.subscription=new Ue.Subscription;this.pipSize$=new Ue.ValueSubject(void 0);this.videoSize$=new Ue.ValueSubject(void 0);this.elementSize$=new Ue.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Ue.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Ue.observeElementSize)(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add((0,Ue.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Ue.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).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 Ei=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new Y("stopped");this.droppedFramesManager=new Js;this.stallsManager=new zv;this.elementSizeManager=new gn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Qr;this.audioTrackSwitchHistory=new Qr;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return(0,U.assertNever)(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new bn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Je(e.source.url),this.params=e,this.video=_e(e.container,e.tuning),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(xe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new hn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Fe(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:U.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,U.filter)(l=>!!l.length),(0,U.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,U.map)(l=>l.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$:i.isBuffering$,looped$:i.looped$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),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.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,U.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(yt(this.video,t.isLooped,r)),this.subscription.add(Ne(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Xe(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Ze(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if((0,U.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let p of c.audio){m.push(tl(p));let f=[];for(let g of p.representations){let S=Rv(g);f.push(S),this.audioTracksMap.set(S,{stream:p,representation:g})}this.audioStreamsMap.set(p,f)}this.params.output.availableAudioStreams$.next(m)}let d=[];for(let m of c.video){d.push(il(m));let p=[];for(let f of m.representations){let g=kv(j($({},f),{streamId:m.id}));g&&(p.push(g),this.videoTracksMap.set(g,{stream:m,representation:f}))}this.videoStreamsMap.set(m,p)}this.params.output.availableVideoStreams$.next(d);for(let m of c.text)for(let p of m.representations){let f=Lv(m,p);this.textTracksMap.set(f,{stream:m,representation:p})}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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),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(()=>A(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Kv.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[m,p]=d,f=[...this.videoTracksMap.keys()].find(S=>{var y;return((y=this.videoTracksMap.get(S))==null?void 0:y.representation.id)===m.id});(0,U.isNonNullable)(f)&&(this.stallsManager.lastVideoTrackSelected=f);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")yield this.player.initRepresentations(m.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",m.id),p){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,S)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,U.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:m}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===m.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(il(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,U.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:m}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===m.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(tl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(m){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${m}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe((0,U.map)(({to:l})=>l==="ready"),(0,U.filterChanged)());this.subscription.add((0,U.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,U.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,U.merge)(o,this.player.state$.stateChangeEnded$,(0,U.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(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(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var H,se,Z,D,N,M,ne,ue,Le,C,K,k,J;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(H=e.videoTrack.getState())==null?void 0:H.id,n=[...this.videoTracksMap.keys()].find(({id:W})=>W===r),o=t.currentVideoTrack$.getValue(),u=((D=(Z=e.videoStream.getState())!=null?Z:n&&((se=this.videoTracksMap.get(n))==null?void 0:se.stream))!=null?D:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:W})=>W===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ir(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let p=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(m,p||1/0),1),g=(N=e.audioStream.getState())!=null?N:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(M=[...this.audioStreamsMap.keys()].find(({id:W})=>W===(g==null?void 0:g.id)))!=null?M:this.audioStreamsMap.keys().next().value,y=0;if(S){if(n&&!i){let W=Ks(n,c,(ne=this.audioStreamsMap.get(S))!=null?ne:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(ue=W==null?void 0:W.bitrate)!=null?ue:-1/0)}if(o){let W=Ks(o,c,(Le=this.audioStreamsMap.get(S))!=null?Le:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(C=W==null?void 0:W.bitrate)!=null?C:-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:y,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),x=i?I!=null?I:n:n!=null?n:I,w=S&&Mb(x,c,(K=this.audioStreamsMap.get(S))!=null?K:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),P=(k=this.videoTracksMap.get(x))==null?void 0:k.representation,B=w&&((J=this.audioTracksMap.get(w))==null?void 0:J.representation);if(P&&B)return[P,B];if(P&&!B&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(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),this.params.output.currentVideoStream$.next(void 0),Be(this.video)}};var Ca=class extends Ei{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var pe=require("@vkontakte/videoplayer-shared/es2015");var Va=class extends Ei{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new pe.ValueSubject(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,pe.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,pe.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,pe.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add((0,pe.combine)({position:t.position$,liveStreamStatus:this.player.liveStreamStatus$}).subscribe(({position:o,liveStreamStatus:u})=>t.isLiveEnded$.next(u!=="active"&&o===0))).add((0,pe.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,pe.merge)(i.playbackRateState$,new pe.ValueSubject(1))}).pipe((0,pe.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||(0,pe.isNullable)(l)||(e=o-l)})).add((0,pe.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,pe.merge)(i.playbackRateState$,new pe.ValueSubject(1))}).pipe((0,pe.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||(0,pe.isNullable)(o)||(0,pe.isNullable)(u))return;let m=-1*(u-o-e);t.position$.next(Math.min(m,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=$v(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Xv=G(Ns(),1);var X=require("@vkontakte/videoplayer-shared/es2015");var pt={};var ur=(a,e)=>new X.Observable(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Oa=class{constructor(e){this.subscription=new X.Subscription;this.videoState=new Y("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:(0,X.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,X.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,X.assertNever)(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:(0,X.assertNever)(e)}break;default:(0,X.assertNever)(t)}};this.textTracksManager=new Je(e.source.url),this.video=_e(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(xe(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),Be(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:X.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Xv.default)(import("hls.js").then(r=>{e||(pt.Hls=r.default,pt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){(0,X.assertNonNullable)(pt.Hls,"hls.js not loaded"),this.hls=new pt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,X.assertNonNullable)(pt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:X.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Fe(this.video);this.subscription.add(()=>r.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(yt(this.video,e.isLooped,i)),this.subscription.add(Ne(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Xe(this.video,e.playbackRate,r.playbackRateState$,i)),s(Ze(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,X.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ur(this.hls,pt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:X.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(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(ur(this.hls,pt.Events.MANIFEST_PARSED).pipe((0,X.map)(({levels:l})=>l.reduce((c,d)=>{var I,x;let m=d.name||d.height.toString(10),{width:p,height:f}=d,g=(x=Yt((I=d.attrs.QUALITY)!=null?I:""))!=null?x:(0,X.videoSizeToQuality)({width:p,height:f});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,y={id:m.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:p,height:f},fps:S};return this.trackLevels.set(m,{track:y,level:d}),c.push(y),c},[]))),t.availableVideoTracks$),s(ur(this.hls,pt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let m=d.name,p=d.attrs.URI||"",f=d.lang;c.push({id:m,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ur(this.hls,pt.Events.LEVEL_LOADING).pipe((0,X.map)(({url:l})=>xe(l))),t.hostname$),s(ur(this.hls,pt.Events.FRAG_CHANGED),l=>{var m,p,f,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((m=c==null?void 0:c.endPTS)!=null?m: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(Wt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ur(this.hls,pt.Events.LEVEL_SWITCHED).pipe((0,X.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,X.filter)(X.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Wt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if((0,X.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),m=this.hls.currentLevel,p=this.hls.levels[m];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,X.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,X.observableFrom)(["init"])).pipe((0,X.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return A(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:X.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState("paused"),L(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"),L(this.params.desiredState.playbackState,"stopped",!0)}};var Jv="X-Playback-Duration",ml=a=>A(void 0,null,function*(){var r;let e=yield It(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Jv)?parseInt(e.headers.get(Jv),10):void 0});var z=require("@vkontakte/videoplayer-shared/es2015");var bl=G(Do(),1);var vn=require("@vkontakte/videoplayer-shared/es2015");var iL=a=>{let e=null;if(a.QUALITY&&(e=Yt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,vn.videoSizeToQuality)({width:t,height:i})}return e!=null?e:null},rL=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
+
`),i=[],r=[];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,bl.default)(l[1].split(",").map(I=>I.split("="))),m=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=iL(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,S;if(d.RESOLUTION){let[I,x]=d.RESOLUTION.split("x").map(w=>parseInt(w,10));I&&x&&(S={width:I,height:x})}let y=new URL(t[++o],e).toString();p&&i.push({id:m,quality:p,url:y,bandwidth:f,size:S,fps:g})}if(c){let d=(0,bl.default)(c[1].split(",").map(g=>{let S=g.indexOf("=");return[g.substring(0,S),g.substring(S+1)]}).map(([g,S])=>[g,S.replace(/^"|"$/g,"")])),m=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,f=d.NAME;m&&p&&r.push({type:"internal",id:p,label:f,language:p,url:m,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},aL=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),fl=0,Zv=(r,...s)=>A(void 0,[r,...s],function*(a,e=a,t,i){let o=yield(yield It(a,i)).text();fl+=1;try{let{qualityManifests:u,textTracks:l}=rL(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(fl<=t.manifestRetryMaxCount)return yield aL((0,vn.getExponentialDelay)(fl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Zv(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Sn=Zv;var Ye=require("@vkontakte/videoplayer-shared/es2015");var yn=class{constructor(e,t,i,r,s){this.subscription=new Ye.Subscription;this.abortControllers={destroy:new Re,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Ye.ValueSubject(null);this.getCurrentTime$=new Ye.ValueSubject(null);this.error$=new Ye.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe((0,Ye.throttle)(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return A(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return A(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return A(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield It(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}})}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
126
|
+
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),m=new Date(i.programDateTime).valueOf();i.segmentStartTime=m-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,Ye.isNonNullable)(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([j($({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return A(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Re;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 A(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:Ye.ErrorCategory.WTF,thrown:t,message:e})}};var _a=class{constructor(e){this.subscription=new z.Subscription;this.videoState=new Y("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new z.ValueSubject([]);this.liveOffset=new vi;this.manifestStartTime$=new z.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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((r==null?void 0:r.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":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),L(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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(r==null?void 0:r.to)==="paused"&&(L(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,z.assertNever)(t)}};var i;this.params=e,this.video=_e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:z.VideoQuality.INVARIANT,url:this.params.source.url};let t=(r,s)=>Sn(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new yn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Je(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:z.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,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:z.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(xe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new z.ValueSubject((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(m=>m.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:z.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Fe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Xe(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ze(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,z.filterChanged)(),(0,z.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,z.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(p=>p.id===d);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(xe(m.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)},i)),this.subscription.add(r.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)},i)),this.subscription.add((0,z.combine)({startTime:this.manifestStartTime$.pipe((0,z.filter)(z.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,z.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:m})=>({id:u,quality:l,size:c,fps:m,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,z.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,z.observableFrom)(["init"])).pipe((0,z.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Be(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,z.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[m,p]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(m||""));p&&m&&r.searchParams.set(p,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ke(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),ml(n).then(c=>{var d;if(!(0,z.isNullable)(c))this.maxSeekBackTime$.next(c);else{let m=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,z.isNullable)(m)||!isFinite(m))&&It(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 S=new URL(f,n).toString();ml(S).then(y=>{(0,z.isNullable)(y)||this.maxSeekBackTime$.next(y)})}}).catch(()=>{})}})}playIfAllowed(){qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:z.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ke(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 re=require("@vkontakte/videoplayer-shared/es2015");var Ba=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new Y("stopped");this.manifests$=new re.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,re.assertNever)(t)}};this.textTracksManager=new Je(e.source.url),this.params=e,this.video=_e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:re.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(xe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Sn(ke(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:re.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,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(m=>m.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:re.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Fe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,re.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(yt(this.video,t.isLooped,i)),this.subscription.add(Ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Xe(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,re.isNonNullable)(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let g=this.manifests$.getValue().find(S=>S.id===f);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(xe(g.url)))}let d=this.params.desiredState.playbackRate.getState(),m=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==m){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)},i))),this.subscription.add(this.manifests$.pipe((0,re.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:m})=>({id:u,quality:l,size:c,fps:m,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!ee.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,re.merge)((0,re.fromEvent)(o,"addtrack"),(0,re.fromEvent)(o,"removetrack"),(0,re.fromEvent)(o,"change"),(0,re.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,re.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,re.observableFrom)(["init"])).pipe((0,re.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Be(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,re.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:re.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var eS=G(Hi(),1),gl=G(Zi(),1),tS=G(zt(),1);var de=require("@vkontakte/videoplayer-shared/es2015");var Na=class{constructor(e){this.subscription=new de.Subscription;this.videoState=new Y("stopped");this.trackUrls={};this.textTracksManager=new Je;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.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"),L(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);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?L(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return(0,de.assertNever)(e)}};this.params=e,this.video=_e(e.container,e.tuning),this.params.output.element$.next(this.video),(0,eS.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,gl.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,i=o=>{e.error$.next({id:"MpegProvider",category:de.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Fe(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,de.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(yt(this.video,t.isLooped,i)),this.subscription.add(Ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Xe(this.video,t.playbackRate,r.playbackRateState$,i)),s(Ze(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&(0,de.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 m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,de.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,de.observableFrom)(["init"])).pipe((0,de.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Be(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;(0,de.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,de.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=La(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(xe(t))}playIfAllowed(){qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:de.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let m=Xt(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(m)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,gl.default)(this.trackUrls).map(d=>d.track);if(!r||!s||jr({limits:e,lowestAvailableQuality:(c=(0,tS.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?(0,de.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,de.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var he=require("@vkontakte/videoplayer-shared/es2015");var rS=require("@vkontakte/videoplayer-shared/es2015");var iS=["stun:videostun.mycdn.me:80"],sL=1e3,nL=3,vl=()=>null,Tn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=vl;this.externalStopCallback=vl;this.externalErrorCallback=vl;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return A(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 A(this,null,function*(){try{let e={iceServers:[{urls:iS}]};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 A(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return A(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:rS.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return A(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 A(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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),sL)}normalizeOptions(e={}){let t={stunServerList:iS,maxRetryNumber:nL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Fa=class{constructor(e){this.videoState=new Y("stopped");this.maxSeekBackTime$=new he.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(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"),L(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return(0,he.assertNever)(e)}};this.subscription=new he.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=_e(e.container,e.tuning),this.liveStreamClient=new Tn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Be(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:he.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,he.merge)(this.videoState.stateChangeStarted$.pipe((0,he.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,he.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Fe(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Ze(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ne(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(0,he.assertNever)(n.to)}},i)).add((0,he.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,he.observableFrom)(["init"])).pipe((0,he.debounce)(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(xe(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:he.VideoQuality.INVARIANT}),this.video.srcObject=e,L(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:he.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:he.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var qa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var T=require("@vkontakte/videoplayer-shared/es2015");var Mt=require("@vkontakte/videoplayer-shared/es2015"),aS=a=>new Mt.Observable(e=>{let t=new Mt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Mt.map)(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Mt.map)(({type:l})=>l!==void 0)),n=new Mt.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var et=require("@vkontakte/videoplayer-shared/es2015");function sS(){return new(window.AudioContext||window.webkitAudioContext)}var Ua=class Ua{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Re;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){ee.browser.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:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,et.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return A(this,null,function*(){let{volumeMultiplier:t}=this,i=sS();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ua.errorId,category:et.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ua.errorId} exception`,thrown:e})}};Ua.errorId="VolumeMultiplierManager";var lr=Ua;var oL={chunkDuration:5e3,maxParallelRequests:5},Ha=class{constructor(e){this.current$=new T.ValueSubject({type:void 0});this.providerError$=new T.Subject;this.noAvailableProvidersError$=new T.Subject;this.volumeMultiplierError$=new T.Subject;this.providerOutput={position$:new T.ValueSubject(0),duration$:new T.ValueSubject(1/0),volume$:new T.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new T.ValueSubject([]),currentVideoStream$:new T.ValueSubject(void 0),availableVideoTracks$:new T.ValueSubject([]),currentVideoTrack$:new T.ValueSubject(void 0),availableAudioStreams$:new T.ValueSubject([]),currentAudioStream$:new T.ValueSubject(void 0),availableAudioTracks$:new T.ValueSubject([]),currentVideoSegmentLength$:new T.ValueSubject(0),currentAudioSegmentLength$:new T.ValueSubject(0),isAudioAvailable$:new T.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new T.ValueSubject(!1),autoVideoTrackLimits$:new T.ValueSubject(void 0),currentBuffer$:new T.ValueSubject(void 0),isBuffering$:new T.ValueSubject(!0),error$:new T.Subject,fetcherError$:new T.Subject,fetcherRecoverableError$:new T.Subject,warning$:new T.Subject,willSeekEvent$:new T.Subject,soundProhibitedEvent$:new T.Subject,seekedEvent$:new T.Subject,loopedEvent$:new T.Subject,endedEvent$:new T.Subject,firstBytesEvent$:new T.Subject,loadedMetadataEvent$:new T.Subject,firstFrameEvent$:new T.Subject,canplay$:new T.Subject,isLive$:new T.ValueSubject(void 0),isLiveEnded$:new T.ValueSubject(null),isLowLatency$:new T.ValueSubject(!1),canChangePlaybackSpeed$:new T.ValueSubject(!0),liveTime$:new T.ValueSubject(void 0),liveBufferTime$:new T.ValueSubject(void 0),liveLatency$:new T.ValueSubject(void 0),severeStallOccurred$:new T.Subject,availableTextTracks$:new T.ValueSubject([]),currentTextTrack$:new T.ValueSubject(void 0),hostname$:new T.ValueSubject(void 0),httpConnectionType$:new T.ValueSubject(void 0),httpConnectionReused$:new T.ValueSubject(void 0),inPiP$:new T.ValueSubject(!1),inFullscreen$:new T.ValueSubject(!1),element$:new T.ValueSubject(void 0),elementVisible$:new T.ValueSubject(!0),availableSources$:new T.ValueSubject(void 0),is3DVideo$:new T.ValueSubject(!1),playbackState$:new T.ValueSubject(""),getCurrentTime$:new T.ValueSubject(null)};this.subscription=new T.Subscription;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Uv([...jv(this.params.tuning),...Hv(this.params.tuning)],this.params.tuning).filter(l=>(0,T.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Sl.default)(r,l)),...t.filter(l=>(0,Sl.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new qa(s);let n=[...cl(!0),...cl(!1)];this.chromecastFormatsIterator=new qa(n.filter(l=>(0,T.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&lr.isSupported()&&(this.volumeMultiplierManager=new lr(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}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,T.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:T.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(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"});let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,T.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,T.assertNonNullable)(o),new Ca(j($({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(o),new Va(j($({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(o),ee.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Ba(j($({},n),{source:o})):new Oa(j($({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(o),new _a(j($({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(o),new Na(j($({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(o),new Ub(j($({},n),{source:o,config:j($({},oL),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,T.assertNonNullable)(o),new Fa({container:i,source:o,desiredState:r,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,T.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,T.assertNonNullable)(o),new Hr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,T.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,T.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,T.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return j($({},e),{url:i(e.url)})}return(0,oS.default)((0,nS.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new T.Subscription,t=!1,i=0;return e.add((0,T.merge)(this.providerOutput.error$.pipe((0,T.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),aS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,T.map)(r=>({id:`ProviderHangup:${r}`,category:T.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,T.filter)(({to:s})=>s==="playing"),(0,T.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=r.category===T.ErrorCategory.NETWORK,o=r.category===T.ErrorCategory.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!o;l?(i++,this.reinitProvider()):u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};var q=require("@vkontakte/videoplayer-shared/es2015");var uL=5e3,uS="one_video_throughput",lS="one_video_rtt",Dt=window.navigator.connection,cS=()=>{let a=Dt==null?void 0:Dt.downlink;if((0,q.isNonNullable)(a)&&a!==10)return a*1e3},dS=()=>{let a=Dt==null?void 0:Dt.rtt;if((0,q.isNonNullable)(a)&&a!==3e3)return a},pS=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},yl=class a{constructor(e){this.subscription=new q.Subscription;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(uS)||(e.useBrowserEstimation?cS():void 0)||uL,i=(s=(r=a.load(lS))!=null?r:e.useBrowserEstimation?dS():void 0)!=null?s:0;if(this.throughput$=new q.ValueSubject(t),this.rtt$=new q.ValueSubject(i),this.rttAdjustedThroughput$=new q.ValueSubject(pS(t,i,e.rttPenaltyRequestSize)),this.throughput=Ii.getSmoothedValue(t,-1,e),this.rtt=Ii.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=cS();u&&this.throughput.next(u);let l=dS();(0,q.isNonNullable)(l)&&this.rtt.next(l)};Dt&&"onchange"in Dt&&this.subscription.add((0,q.fromEvent)(Dt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{q.safeStorage.set(uS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{q.safeStorage.set(lS,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,q.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,q.map)(({throughput:n,rtt:o})=>pS(n,o,e.rttPenaltyRequestSize)),(0,q.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,i=(0,q.now)(),r=new q.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,q.fromEvent)(e,"progress").pipe((0,q.once)()).subscribe(s=>{t=s.loaded,i=(0,q.now)()}));break;case 1:case 0:r.add((0,q.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,q.now)()}));break}r.add((0,q.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,q.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,q.now)(),n=0,o=(0,q.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=m=>A(this,[m],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(r,(0,q.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,q.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,q.now)()}else n+=d.byteLength;o=(0,q.now)()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,q.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,q.now)()-o,this.concurrentDownloads.size),n=0,o=(0,q.now)());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=q.safeStorage.get(e);if((0,q.isNonNullable)(t))return(i=parseInt(t,10))!=null?i:void 0}},hS=yl;var xi=require("@vkontakte/videoplayer-shared/es2015");var mS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:xi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:xi.VideoQuality.Q_720P,trafficSavingLimit:xi.VideoQuality.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:xi.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,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,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1},fS=a=>{var e;return j($({},(0,xi.fillWithDefault)(a,mS)),{configName:[...(e=a.configName)!=null?e:[],...mS.configName]})};var h=require("@vkontakte/videoplayer-shared/es2015");var Ct=require("@vkontakte/videoplayer-shared/es2015"),Tl=({seekState:a,position$:e})=>(0,Ct.merge)(a.stateChangeEnded$.pipe((0,Ct.map)(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),(0,Ct.filter)(Ct.isNonNullable)),e.pipe((0,Ct.filter)(()=>a.getState().state==="none")));var bS=require("@vkontakte/videoplayer-shared/es2015"),gS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,bS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var In=require("@vkontakte/videoplayer-shared/es2015"),vS=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,In.filter)(r=>r.length>0),(0,In.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var ja=class{constructor(e={configName:[]}){this.subscription=new h.Subscription;this.logger=new h.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new h.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInited=new h.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Y("stopped"),seekState:new Y({state:"none"}),volume:new Y({volume:1,muted:!1}),videoTrack:new Y(void 0),videoStream:new Y(void 0),audioStream:new Y(void 0),autoVideoTrackSwitching:new Y(!0),autoVideoTrackLimits:new Y({}),isLooped:new Y(!1),isLowLatency:new Y(!1),playbackRate:new Y(1),externalTextTracks:new Y([]),internalTextTracks:new Y([]),currentTextTrack:new Y(void 0),textTrackCuesSettings:new Y({}),cameraOrientation:new Y({x:0,y:0})};this.info={playbackState$:new h.ValueSubject(void 0),position$:new h.ValueSubject(0),duration$:new h.ValueSubject(1/0),muted$:new h.ValueSubject(!1),volume$:new h.ValueSubject(1),availableVideoStreams$:new h.ValueSubject([]),currentVideoStream$:new h.ValueSubject(void 0),availableQualities$:new h.ValueSubject([]),availableQualitiesFps$:new h.ValueSubject({}),currentQuality$:new h.ValueSubject(void 0),isAutoQualityEnabled$:new h.ValueSubject(!0),autoQualityLimitingAvailable$:new h.ValueSubject(!1),autoQualityLimits$:new h.ValueSubject({}),predefinedQualityLimitType$:new h.ValueSubject("unknown"),availableAudioStreams$:new h.ValueSubject([]),currentAudioStream$:new h.ValueSubject(void 0),availableAudioTracks$:new h.ValueSubject([]),isAudioAvailable$:new h.ValueSubject(!0),currentPlaybackRate$:new h.ValueSubject(1),currentBuffer$:new h.ValueSubject({start:0,end:0}),isBuffering$:new h.ValueSubject(!0),isStalled$:new h.ValueSubject(!1),isEnded$:new h.ValueSubject(!1),isLooped$:new h.ValueSubject(!1),isLive$:new h.ValueSubject(void 0),isLiveEnded$:new h.ValueSubject(null),canChangePlaybackSpeed$:new h.ValueSubject(void 0),atLiveEdge$:new h.ValueSubject(void 0),atLiveDurationEdge$:new h.ValueSubject(void 0),liveTime$:new h.ValueSubject(void 0),liveBufferTime$:new h.ValueSubject(void 0),liveLatency$:new h.ValueSubject(void 0),currentFormat$:new h.ValueSubject(void 0),availableTextTracks$:new h.ValueSubject([]),currentTextTrack$:new h.ValueSubject(void 0),throughputEstimation$:new h.ValueSubject(void 0),rttEstimation$:new h.ValueSubject(void 0),videoBitrate$:new h.ValueSubject(void 0),hostname$:new h.ValueSubject(void 0),httpConnectionType$:new h.ValueSubject(void 0),httpConnectionReused$:new h.ValueSubject(void 0),surface$:new h.ValueSubject("none"),chromecastState$:new h.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new h.ValueSubject(void 0),intrinsicVideoSize$:new h.ValueSubject(void 0),availableSources$:new h.ValueSubject(void 0),is3DVideo$:new h.ValueSubject(!1),currentVideoSegmentLength$:new h.ValueSubject(0),currentAudioSegmentLength$:new h.ValueSubject(0)};this.events={inited$:new h.Subject,ready$:new h.Subject,started$:new h.Subject,playing$:new h.Subject,paused$:new h.Subject,stopped$:new h.Subject,willStart$:new h.Subject,willResume$:new h.Subject,willPause$:new h.Subject,willStop$:new h.Subject,willDestruct$:new h.Subject,watchCoverageRecord$:new h.Subject,watchCoverageLive$:new h.Subject,managedError$:new h.Subject,fatalError$:new h.Subject,fetcherRecoverableError$:new h.Subject,ended$:new h.Subject,looped$:new h.Subject,seeked$:new h.Subject,willSeek$:new h.Subject,autoplaySoundProhibited$:new h.Subject,firstBytes$:new h.Subject,loadedMetadata$:new h.Subject,firstFrame$:new h.Subject,canplay$:new h.Subject,log$:new h.Subject,fetcherError$:new h.Subject,severeStallOccured$:new h.Subject};this.experimental={element$:new h.ValueSubject(void 0),tuningConfigName$:new h.ValueSubject([]),enableDebugTelemetry$:new h.ValueSubject(!1),getCurrentTime$:new h.ValueSubject(null)};if(this.initLogs(),this.tuning=fS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ds({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new hS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new h.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{let s=Reflect.get(t,i,r);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let u=n.map(d=>JSON.stringify(d,(m,p)=>{let f=typeof p;return(0,SS.default)(["number","string","boolean"],f)?p:p===null?null:`<${f}>`})),l=`Player.${String(i)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:h.ErrorCategory.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var r;this.config=e,(r=this.internalsExposure)==null||r.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var s,n,o;this.domContainer=gS(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Ha({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,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.asyncResolveClientChecker?ee.isInited$.pipe((0,h.filter)(s=>!!s),(0,h.once)()).subscribe(()=>{console.log("Core SDK async start"),t()}):t()};return this.isNotActiveTabCase()?(0,h.fromEvent)(document,"visibilitychange").pipe((0,h.once)()).subscribe(i):i(),this}destroy(){var e,t;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(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe((0,h.filter)(e=>!!e),(0,h.once)()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe((0,h.filter)(e=>!!e),(0,h.once)()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe((0,h.filter)(e=>!!e),(0,h.once)()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe((0,h.filter)(e=>!!e),(0,h.once)()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe((0,h.filter)(i=>!!i),(0,h.once)()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{let t=this.info.duration$.getValue();isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe((0,h.filter)(i=>!!i),(0,h.once)()).subscribe(()=>{let i=this.desiredState.volume,r=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||r;this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:s})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{let t=this.tuning.isAudioDisabled||e,i=this.info.volume$.getValue();this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:i,muted:t})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{(0,h.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,h.filter)(i=>i.length>0),(0,h.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{var i;(0,h.assertNonNullable)(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>$({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{var t;vS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e)})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe((0,h.filter)(i=>!!i),(0,h.once)()).subscribe(()=>{let i=this.getScene3D();i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe((0,h.filter)(t=>!!t),(0,h.once)()).subscribe(()=>{let t=this.getScene3D();t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe((0,h.filter)(i=>!!i),(0,h.once)()).subscribe(()=>{let i=this.getScene3D();if(i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,h.filter)(e=>e),(0,h.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,h.filter)(e=>!!e),(0,h.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,h.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,h.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,h.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ku({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.filter)(({from:e})=>e==="stopped"),(0,h.once)()).subscribe(()=>{this.initedAt=(0,h.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();n.state==="requested"?this.desiredState.seekState.setState(j($({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:h.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,h.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,h.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,h.map)(n=>n.destination),(0,h.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,h.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,h.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,h.isInvariantQuality)(u)?1:(0,h.isInvariantQuality)(l)?-1:(0,h.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,h.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,h.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,h.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,h.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,h.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,h.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,h.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.isLiveEnded$.pipe((0,h.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).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,h.combine)({hasLiveOffsetByPaused:(0,h.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,h.map)(n=>n.to),(0,h.filterChanged)(),(0,h.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,h.combine)({atLiveEdge:(0,h.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Tl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,h.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,h.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,h.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,h.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,h.filterChanged)(),(0,h.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.muted),(0,h.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,h.map)(n=>n.volume),(0,h.filterChanged)()).subscribe(this.info.volume$)).add(Tl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,h.merge)(e.providerOutput.endedEvent$.pipe((0,h.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,h.mapTo)(!1))).pipe((0,h.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.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,h.map)(n=>({id:n?`No${n}`:"NoProviders",category:h.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,h.once)(),(0,h.map)(n=>n!=null?n:(0,h.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,h.once)(),(0,h.map)(()=>(0,h.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 h.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new h.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.filter)(({to:n})=>n==="playing"),(0,h.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,h.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,h.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,h.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,h.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,h.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,h.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 h.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,h.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,h.filter)(i=>i.length>0),(0,h.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),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,h.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,h.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,h.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,h.assertNonNullable)(this.providerContainer),(0,h.assertNonNullable)(e),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart)}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>A(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:h.ErrorCategory.DOM,message:String(r)})})});this.subscription.add((0,h.merge)((0,h.fromEvent)(document,"visibilitychange"),(0,h.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!zr()}};var Et=require("@vkontakte/videoplayer-shared/es2015"),lL=`@vkontakte/videoplayer-core@${kn}`;
|