@vkontakte/videoplayer-core 2.0.128 → 2.0.129-dev.53dfa302.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 +28 -28
- package/es2015.esm.js +23 -23
- package/es2018.cjs.js +25 -25
- package/es2018.esm.js +26 -26
- package/esnext.cjs.js +32 -32
- package/esnext.esm.js +29 -29
- package/evergreen.esm.js +23 -23
- package/package.json +1 -1
- package/types/index.d.ts +1 -0
- package/types/player/Player.d.ts +2 -0
- package/types/providers/DashProvider/baseDashProvider.d.ts +1 -1
- package/types/providers/DashProvider/lib/player.d.ts +2 -0
- package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +0 -2
- package/types/providers/utils/StallsManager.d.ts +2 -1
- package/types/utils/ClientChecker/ClientChecker.d.ts +22 -0
- package/types/utils/ClientChecker/index.d.ts +2 -0
- package/types/utils/ClientChecker/services/AudioChecker.d.ts +10 -0
- package/types/utils/ClientChecker/services/BrowserChecker.d.ts +13 -0
- package/types/utils/ClientChecker/services/DeviceChecker.d.ts +23 -0
- package/types/utils/ClientChecker/services/DisplayChecker.d.ts +22 -0
- package/types/utils/ClientChecker/services/VideoChecker.d.ts +45 -0
- package/types/utils/ClientChecker/types/checker.d.ts +3 -0
- package/types/utils/ClientChecker/types/currentClientBrowser.d.ts +12 -0
- package/types/utils/ClientChecker/types/currentClientDevice.d.ts +10 -0
- package/types/utils/ClientChecker/types/userAgentData.d.ts +33 -0
- package/types/utils/ClientChecker/utils/isMobile.d.ts +1 -0
- package/types/utils/tuningConfig.d.ts +4 -0
package/es2015.cjs.js
CHANGED
|
@@ -1,73 +1,73 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.129-dev.53dfa302.0
|
|
3
|
+
* Thu, 13 Mar 2025 08:39:23 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-129/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var zS=Object.create;var xi=Object.defineProperty,KS=Object.defineProperties,XS=Object.getOwnPropertyDescriptor,JS=Object.getOwnPropertyDescriptors,ZS=Object.getOwnPropertyNames,ps=Object.getOwnPropertySymbols,ey=Object.getPrototypeOf,_n=Object.prototype.hasOwnProperty,vc=Object.prototype.propertyIsEnumerable;var ty=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var gt=Math.pow,gc=(a,e,t)=>e in a?xi(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,k=(a,e)=>{for(var t in e||(e={}))_n.call(e,t)&&gc(a,t,e[t]);if(ps)for(var t of ps(e))vc.call(e,t)&&gc(a,t,e[t]);return a},_=(a,e)=>KS(a,JS(e));var Sc=(a,e)=>{var t={};for(var r in a)_n.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&ps)for(var r of ps(a))e.indexOf(r)<0&&vc.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),ry=(a,e)=>{for(var t in e)xi(a,t,{get:e[t],enumerable:!0})},yc=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ZS(e))!_n.call(a,i)&&i!==t&&xi(a,i,{get:()=>e[i],enumerable:!(r=XS(e,i))||r.enumerable});return a};var W=(a,e,t)=>(t=a!=null?zS(ey(a)):{},yc(e||!a||!a.__esModule?xi(t,"default",{value:a,enumerable:!0}):t,a)),iy=a=>yc(xi({},"__esModule",{value:!0}),a);var L=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),hs=function(a,e){this[0]=a,this[1]=e},ve=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof hs,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[ty("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ge=b((Fn,Tc)=>{"use strict";var Ai=function(a){return a&&a.Math===Math&&a};Tc.exports=Ai(typeof globalThis=="object"&&globalThis)||Ai(typeof window=="object"&&window)||Ai(typeof self=="object"&&self)||Ai(typeof global=="object"&&global)||Ai(typeof Fn=="object"&&Fn)||function(){return this}()||Function("return this")()});var we=b((V$,Ic)=>{"use strict";Ic.exports=function(a){try{return!!a()}catch(e){return!0}}});var ki=b((B$,Ec)=>{"use strict";var ay=we();Ec.exports=!ay(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var qn=b((O$,Ac)=>{"use strict";var sy=ki(),wc=Function.prototype,xc=wc.apply,Pc=wc.call;Ac.exports=typeof Reflect=="object"&&Reflect.apply||(sy?Pc.bind(xc):function(){return Pc.apply(xc,arguments)})});var Ie=b((_$,$c)=>{"use strict";var kc=ki(),Lc=Function.prototype,Un=Lc.call,ny=kc&&Lc.bind.bind(Un,Un);$c.exports=kc?ny:function(a){return function(){return Un.apply(a,arguments)}}});var mr=b((N$,Mc)=>{"use strict";var Rc=Ie(),oy=Rc({}.toString),uy=Rc("".slice);Mc.exports=function(a){return uy(oy(a),8,-1)}});var Hn=b((F$,Dc)=>{"use strict";var ly=mr(),cy=Ie();Dc.exports=function(a){if(ly(a)==="Function")return cy(a)}});var fe=b((q$,Cc)=>{"use strict";var jn=typeof document=="object"&&document.all;Cc.exports=typeof jn=="undefined"&&jn!==void 0?function(a){return typeof a=="function"||a===jn}:function(a){return typeof a=="function"}});var Ge=b((U$,Vc)=>{"use strict";var dy=we();Vc.exports=!dy(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var We=b((H$,Bc)=>{"use strict";var py=ki(),bs=Function.prototype.call;Bc.exports=py?bs.bind(bs):function(){return bs.apply(bs,arguments)}});var Qn=b(Nc=>{"use strict";var Oc={}.propertyIsEnumerable,_c=Object.getOwnPropertyDescriptor,hy=_c&&!Oc.call({1:2},1);Nc.f=hy?function(e){var t=_c(this,e);return!!t&&t.enumerable}:Oc});var Li=b((Q$,Fc)=>{"use strict";Fc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Uc=b((G$,qc)=>{"use strict";var my=Ie(),fy=we(),by=mr(),Gn=Object,gy=my("".split);qc.exports=fy(function(){return!Gn("z").propertyIsEnumerable(0)})?function(a){return by(a)==="String"?gy(a,""):Gn(a)}:Gn});var Fr=b((W$,Hc)=>{"use strict";Hc.exports=function(a){return a==null}});var zt=b((Y$,jc)=>{"use strict";var vy=Fr(),Sy=TypeError;jc.exports=function(a){if(vy(a))throw new Sy("Can't call method on "+a);return a}});var fr=b((z$,Qc)=>{"use strict";var yy=Uc(),Ty=zt();Qc.exports=function(a){return yy(Ty(a))}});var Ye=b((K$,Gc)=>{"use strict";var Iy=fe();Gc.exports=function(a){return typeof a=="object"?a!==null:Iy(a)}});var qr=b((X$,Wc)=>{"use strict";Wc.exports={}});var Lt=b((J$,zc)=>{"use strict";var Wn=qr(),Yn=ge(),Ey=fe(),Yc=function(a){return Ey(a)?a:void 0};zc.exports=function(a,e){return arguments.length<2?Yc(Wn[a])||Yc(Yn[a]):Wn[a]&&Wn[a][e]||Yn[a]&&Yn[a][e]}});var $i=b((Z$,Kc)=>{"use strict";var xy=Ie();Kc.exports=xy({}.isPrototypeOf)});var br=b((eR,Zc)=>{"use strict";var Py=ge(),Xc=Py.navigator,Jc=Xc&&Xc.userAgent;Zc.exports=Jc?String(Jc):""});var Kn=b((tR,sd)=>{"use strict";var ad=ge(),zn=br(),ed=ad.process,td=ad.Deno,rd=ed&&ed.versions||td&&td.version,id=rd&&rd.v8,ut,gs;id&&(ut=id.split("."),gs=ut[0]>0&&ut[0]<4?1:+(ut[0]+ut[1]));!gs&&zn&&(ut=zn.match(/Edge\/(\d+)/),(!ut||ut[1]>=74)&&(ut=zn.match(/Chrome\/(\d+)/),ut&&(gs=+ut[1])));sd.exports=gs});var Xn=b((rR,od)=>{"use strict";var nd=Kn(),wy=we(),Ay=ge(),ky=Ay.String;od.exports=!!Object.getOwnPropertySymbols&&!wy(function(){var a=Symbol("symbol detection");return!ky(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&nd&&nd<41})});var Jn=b((iR,ud)=>{"use strict";var Ly=Xn();ud.exports=Ly&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Zn=b((aR,ld)=>{"use strict";var $y=Lt(),Ry=fe(),My=$i(),Dy=Jn(),Cy=Object;ld.exports=Dy?function(a){return typeof a=="symbol"}:function(a){var e=$y("Symbol");return Ry(e)&&My(e.prototype,Cy(a))}});var Ri=b((sR,cd)=>{"use strict";var Vy=String;cd.exports=function(a){try{return Vy(a)}catch(e){return"Object"}}});var vt=b((nR,dd)=>{"use strict";var By=fe(),Oy=Ri(),_y=TypeError;dd.exports=function(a){if(By(a))return a;throw new _y(Oy(a)+" is not a function")}});var Mi=b((oR,pd)=>{"use strict";var Ny=vt(),Fy=Fr();pd.exports=function(a,e){var t=a[e];return Fy(t)?void 0:Ny(t)}});var md=b((uR,hd)=>{"use strict";var eo=We(),to=fe(),ro=Ye(),qy=TypeError;hd.exports=function(a,e){var t,r;if(e==="string"&&to(t=a.toString)&&!ro(r=eo(t,a))||to(t=a.valueOf)&&!ro(r=eo(t,a))||e!=="string"&&to(t=a.toString)&&!ro(r=eo(t,a)))return r;throw new qy("Can't convert object to primitive value")}});var lt=b((lR,fd)=>{"use strict";fd.exports=!0});var vd=b((cR,gd)=>{"use strict";var bd=ge(),Uy=Object.defineProperty;gd.exports=function(a,e){try{Uy(bd,a,{value:e,configurable:!0,writable:!0})}catch(t){bd[a]=e}return e}});var Di=b((dR,Td)=>{"use strict";var Hy=lt(),jy=ge(),Qy=vd(),Sd="__core-js_shared__",yd=Td.exports=jy[Sd]||Qy(Sd,{});(yd.versions||(yd.versions=[])).push({version:"3.38.0",mode:Hy?"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 io=b((pR,Ed)=>{"use strict";var Id=Di();Ed.exports=function(a,e){return Id[a]||(Id[a]=e||{})}});var Ur=b((hR,xd)=>{"use strict";var Gy=zt(),Wy=Object;xd.exports=function(a){return Wy(Gy(a))}});var ct=b((mR,Pd)=>{"use strict";var Yy=Ie(),zy=Ur(),Ky=Yy({}.hasOwnProperty);Pd.exports=Object.hasOwn||function(e,t){return Ky(zy(e),t)}});var ao=b((fR,wd)=>{"use strict";var Xy=Ie(),Jy=0,Zy=Math.random(),eT=Xy(1 .toString);wd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+eT(++Jy+Zy,36)}});var Ae=b((bR,kd)=>{"use strict";var tT=ge(),rT=io(),Ad=ct(),iT=ao(),aT=Xn(),sT=Jn(),Hr=tT.Symbol,so=rT("wks"),nT=sT?Hr.for||Hr:Hr&&Hr.withoutSetter||iT;kd.exports=function(a){return Ad(so,a)||(so[a]=aT&&Ad(Hr,a)?Hr[a]:nT("Symbol."+a)),so[a]}});var Md=b((gR,Rd)=>{"use strict";var oT=We(),Ld=Ye(),$d=Zn(),uT=Mi(),lT=md(),cT=Ae(),dT=TypeError,pT=cT("toPrimitive");Rd.exports=function(a,e){if(!Ld(a)||$d(a))return a;var t=uT(a,pT),r;if(t){if(e===void 0&&(e="default"),r=oT(t,a,e),!Ld(r)||$d(r))return r;throw new dT("Can't convert object to primitive value")}return e===void 0&&(e="number"),lT(a,e)}});var no=b((vR,Dd)=>{"use strict";var hT=Md(),mT=Zn();Dd.exports=function(a){var e=hT(a,"string");return mT(e)?e:e+""}});var vs=b((SR,Vd)=>{"use strict";var fT=ge(),Cd=Ye(),oo=fT.document,bT=Cd(oo)&&Cd(oo.createElement);Vd.exports=function(a){return bT?oo.createElement(a):{}}});var uo=b((yR,Bd)=>{"use strict";var gT=Ge(),vT=we(),ST=vs();Bd.exports=!gT&&!vT(function(){return Object.defineProperty(ST("div"),"a",{get:function(){return 7}}).a!==7})});var Nd=b(_d=>{"use strict";var yT=Ge(),TT=We(),IT=Qn(),ET=Li(),xT=fr(),PT=no(),wT=ct(),AT=uo(),Od=Object.getOwnPropertyDescriptor;_d.f=yT?Od:function(e,t){if(e=xT(e),t=PT(t),AT)try{return Od(e,t)}catch(r){}if(wT(e,t))return ET(!TT(IT.f,e,t),e[t])}});var lo=b((IR,Fd)=>{"use strict";var kT=we(),LT=fe(),$T=/#|\.prototype\./,Ci=function(a,e){var t=MT[RT(a)];return t===CT?!0:t===DT?!1:LT(e)?kT(e):!!e},RT=Ci.normalize=function(a){return String(a).replace($T,".").toLowerCase()},MT=Ci.data={},DT=Ci.NATIVE="N",CT=Ci.POLYFILL="P";Fd.exports=Ci});var jr=b((ER,Ud)=>{"use strict";var qd=Hn(),VT=vt(),BT=ki(),OT=qd(qd.bind);Ud.exports=function(a,e){return VT(a),e===void 0?a:BT?OT(a,e):function(){return a.apply(e,arguments)}}});var co=b((xR,Hd)=>{"use strict";var _T=Ge(),NT=we();Hd.exports=_T&&NT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var St=b((PR,jd)=>{"use strict";var FT=Ye(),qT=String,UT=TypeError;jd.exports=function(a){if(FT(a))return a;throw new UT(qT(a)+" is not an object")}});var gr=b(Gd=>{"use strict";var HT=Ge(),jT=uo(),QT=co(),Ss=St(),Qd=no(),GT=TypeError,po=Object.defineProperty,WT=Object.getOwnPropertyDescriptor,ho="enumerable",mo="configurable",fo="writable";Gd.f=HT?QT?function(e,t,r){if(Ss(e),t=Qd(t),Ss(r),typeof e=="function"&&t==="prototype"&&"value"in r&&fo in r&&!r[fo]){var i=WT(e,t);i&&i[fo]&&(e[t]=r.value,r={configurable:mo in r?r[mo]:i[mo],enumerable:ho in r?r[ho]:i[ho],writable:!1})}return po(e,t,r)}:po:function(e,t,r){if(Ss(e),t=Qd(t),Ss(r),jT)try{return po(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new GT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Qr=b((AR,Wd)=>{"use strict";var YT=Ge(),zT=gr(),KT=Li();Wd.exports=YT?function(a,e,t){return zT.f(a,e,KT(1,t))}:function(a,e,t){return a[e]=t,a}});var Se=b((kR,zd)=>{"use strict";var Vi=ge(),XT=qn(),JT=Hn(),ZT=fe(),eI=Nd().f,tI=lo(),Gr=qr(),rI=jr(),Wr=Qr(),Yd=ct();Di();var iI=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 XT(a,this,arguments)};return e.prototype=a.prototype,e};zd.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Vi:i?Vi[t]:Vi[t]&&Vi[t].prototype,o=r?Gr:Gr[t]||Wr(Gr,t,{})[t],u=o.prototype,l,c,d,p,h,f,g,S,I;for(p in e)l=tI(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Yd(n,p),f=o[p],c&&(a.dontCallGetSet?(I=eI(n,p),g=I&&I.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?S=rI(h,Vi):a.wrap&&c?S=iI(h):s&&ZT(h)?S=JT(h):S=h,(a.sham||h&&h.sham||f&&f.sham)&&Wr(S,"sham",!0),Wr(o,p,S),s&&(d=t+"Prototype",Yd(Gr,d)||Wr(Gr,d,{}),Wr(Gr[d],p,h),a.real&&u&&(l||!u[p])&&Wr(u,p,h)))}});var Xd=b((LR,Kd)=>{"use strict";var aI=Math.ceil,sI=Math.floor;Kd.exports=Math.trunc||function(e){var t=+e;return(t>0?sI:aI)(t)}});var Bi=b(($R,Jd)=>{"use strict";var nI=Xd();Jd.exports=function(a){var e=+a;return e!==e||e===0?0:nI(e)}});var ep=b((RR,Zd)=>{"use strict";var oI=Bi(),uI=Math.max,lI=Math.min;Zd.exports=function(a,e){var t=oI(a);return t<0?uI(t+e,0):lI(t,e)}});var bo=b((MR,tp)=>{"use strict";var cI=Bi(),dI=Math.min;tp.exports=function(a){var e=cI(a);return e>0?dI(e,9007199254740991):0}});var Yr=b((DR,rp)=>{"use strict";var pI=bo();rp.exports=function(a){return pI(a.length)}});var go=b((CR,ap)=>{"use strict";var hI=fr(),mI=ep(),fI=Yr(),ip=function(a){return function(e,t,r){var i=hI(e),s=fI(i);if(s===0)return!a&&-1;var n=mI(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}};ap.exports={includes:ip(!0),indexOf:ip(!1)}});var Oi=b((VR,sp)=>{"use strict";sp.exports=function(){}});var np=b(()=>{"use strict";var bI=Se(),gI=go().includes,vI=we(),SI=Oi(),yI=vI(function(){return!Array(1).includes()});bI({target:"Array",proto:!0,forced:yI},{includes:function(e){return gI(this,e,arguments.length>1?arguments[1]:void 0)}});SI("includes")});var Kt=b((_R,op)=>{"use strict";var TI=Lt();op.exports=TI});var lp=b((NR,up)=>{"use strict";np();var II=Kt();up.exports=II("Array","includes")});var dp=b((FR,cp)=>{"use strict";var EI=lp();cp.exports=EI});var dt=b((qR,pp)=>{"use strict";var xI=dp();pp.exports=xI});var Ts=b((JR,fp)=>{"use strict";var wI=io(),AI=ao(),mp=wI("keys");fp.exports=function(a){return mp[a]||(mp[a]=AI(a))}});var gp=b((ZR,bp)=>{"use strict";var kI=we();bp.exports=!kI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Is=b((eM,Sp)=>{"use strict";var LI=ct(),$I=fe(),RI=Ur(),MI=Ts(),DI=gp(),vp=MI("IE_PROTO"),vo=Object,CI=vo.prototype;Sp.exports=DI?vo.getPrototypeOf:function(a){var e=RI(a);if(LI(e,vp))return e[vp];var t=e.constructor;return $I(t)&&e instanceof t?t.prototype:e instanceof vo?CI:null}});var Es=b((tM,yp)=>{"use strict";yp.exports={}});var Ep=b((rM,Ip)=>{"use strict";var VI=Ie(),So=ct(),BI=fr(),OI=go().indexOf,_I=Es(),Tp=VI([].push);Ip.exports=function(a,e){var t=BI(a),r=0,i=[],s;for(s in t)!So(_I,s)&&So(t,s)&&Tp(i,s);for(;e.length>r;)So(t,s=e[r++])&&(~OI(i,s)||Tp(i,s));return i}});var yo=b((iM,xp)=>{"use strict";xp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var To=b((aM,Pp)=>{"use strict";var NI=Ep(),FI=yo();Pp.exports=Object.keys||function(e){return NI(e,FI)}});var Io=b((sM,$p)=>{"use strict";var Ap=Ge(),qI=we(),kp=Ie(),UI=Is(),HI=To(),jI=fr(),QI=Qn().f,Lp=kp(QI),GI=kp([].push),WI=Ap&&qI(function(){var a=Object.create(null);return a[2]=2,!Lp(a,2)}),wp=function(a){return function(e){for(var t=jI(e),r=HI(t),i=WI&&UI(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Ap||(i?u in t:Lp(t,u)))&&GI(o,a?[u,t[u]]:t[u]);return o}};$p.exports={entries:wp(!0),values:wp(!1)}});var Rp=b(()=>{"use strict";var YI=Se(),zI=Io().entries;YI({target:"Object",stat:!0},{entries:function(e){return zI(e)}})});var Dp=b((uM,Mp)=>{"use strict";Rp();var KI=qr();Mp.exports=KI.Object.entries});var Vp=b((lM,Cp)=>{"use strict";var XI=Dp();Cp.exports=XI});var zr=b((cM,Bp)=>{"use strict";var JI=Vp();Bp.exports=JI});var vr=b((dM,Op)=>{"use strict";Op.exports={}});var Fp=b((pM,Np)=>{"use strict";var ZI=ge(),eE=fe(),_p=ZI.WeakMap;Np.exports=eE(_p)&&/native code/.test(String(_p))});var wo=b((hM,Hp)=>{"use strict";var tE=Fp(),Up=ge(),rE=Ye(),iE=Qr(),Eo=ct(),xo=Di(),aE=Ts(),sE=Es(),qp="Object already initialized",Po=Up.TypeError,nE=Up.WeakMap,xs,_i,Ps,oE=function(a){return Ps(a)?_i(a):xs(a,{})},uE=function(a){return function(e){var t;if(!rE(e)||(t=_i(e)).type!==a)throw new Po("Incompatible receiver, "+a+" required");return t}};tE||xo.state?(pt=xo.state||(xo.state=new nE),pt.get=pt.get,pt.has=pt.has,pt.set=pt.set,xs=function(a,e){if(pt.has(a))throw new Po(qp);return e.facade=a,pt.set(a,e),e},_i=function(a){return pt.get(a)||{}},Ps=function(a){return pt.has(a)}):(Sr=aE("state"),sE[Sr]=!0,xs=function(a,e){if(Eo(a,Sr))throw new Po(qp);return e.facade=a,iE(a,Sr,e),e},_i=function(a){return Eo(a,Sr)?a[Sr]:{}},Ps=function(a){return Eo(a,Sr)});var pt,Sr;Hp.exports={set:xs,get:_i,has:Ps,enforce:oE,getterFor:uE}});var Lo=b((mM,Qp)=>{"use strict";var Ao=Ge(),lE=ct(),jp=Function.prototype,cE=Ao&&Object.getOwnPropertyDescriptor,ko=lE(jp,"name"),dE=ko&&function(){}.name==="something",pE=ko&&(!Ao||Ao&&cE(jp,"name").configurable);Qp.exports={EXISTS:ko,PROPER:dE,CONFIGURABLE:pE}});var Wp=b(Gp=>{"use strict";var hE=Ge(),mE=co(),fE=gr(),bE=St(),gE=fr(),vE=To();Gp.f=hE&&!mE?Object.defineProperties:function(e,t){bE(e);for(var r=gE(t),i=vE(t),s=i.length,n=0,o;s>n;)fE.f(e,o=i[n++],r[o]);return e}});var $o=b((bM,Yp)=>{"use strict";var SE=Lt();Yp.exports=SE("document","documentElement")});var Co=b((gM,th)=>{"use strict";var yE=St(),TE=Wp(),zp=yo(),IE=Es(),EE=$o(),xE=vs(),PE=Ts(),Kp=">",Xp="<",Mo="prototype",Do="script",Zp=PE("IE_PROTO"),Ro=function(){},eh=function(a){return Xp+Do+Kp+a+Xp+"/"+Do+Kp},Jp=function(a){a.write(eh("")),a.close();var e=a.parentWindow.Object;return a=null,e},wE=function(){var a=xE("iframe"),e="java"+Do+":",t;return a.style.display="none",EE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(eh("document.F=Object")),t.close(),t.F},ws,As=function(){try{ws=new ActiveXObject("htmlfile")}catch(e){}As=typeof document!="undefined"?document.domain&&ws?Jp(ws):wE():Jp(ws);for(var a=zp.length;a--;)delete As[Mo][zp[a]];return As()};IE[Zp]=!0;th.exports=Object.create||function(e,t){var r;return e!==null?(Ro[Mo]=yE(e),r=new Ro,Ro[Mo]=null,r[Zp]=e):r=As(),t===void 0?r:TE.f(r,t)}});var Kr=b((vM,rh)=>{"use strict";var AE=Qr();rh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:AE(a,e,t),a}});var _o=b((SM,sh)=>{"use strict";var kE=we(),LE=fe(),$E=Ye(),RE=Co(),ih=Is(),ME=Kr(),DE=Ae(),CE=lt(),Oo=DE("iterator"),ah=!1,$t,Vo,Bo;[].keys&&(Bo=[].keys(),"next"in Bo?(Vo=ih(ih(Bo)),Vo!==Object.prototype&&($t=Vo)):ah=!0);var VE=!$E($t)||kE(function(){var a={};return $t[Oo].call(a)!==a});VE?$t={}:CE&&($t=RE($t));LE($t[Oo])||ME($t,Oo,function(){return this});sh.exports={IteratorPrototype:$t,BUGGY_SAFARI_ITERATORS:ah}});var ks=b((yM,oh)=>{"use strict";var BE=Ae(),OE=BE("toStringTag"),nh={};nh[OE]="z";oh.exports=String(nh)==="[object z]"});var Ni=b((TM,uh)=>{"use strict";var _E=ks(),NE=fe(),Ls=mr(),FE=Ae(),qE=FE("toStringTag"),UE=Object,HE=Ls(function(){return arguments}())==="Arguments",jE=function(a,e){try{return a[e]}catch(t){}};uh.exports=_E?Ls:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=jE(e=UE(a),qE))=="string"?t:HE?Ls(e):(r=Ls(e))==="Object"&&NE(e.callee)?"Arguments":r}});var ch=b((IM,lh)=>{"use strict";var QE=ks(),GE=Ni();lh.exports=QE?{}.toString:function(){return"[object "+GE(this)+"]"}});var Fi=b((EM,ph)=>{"use strict";var WE=ks(),YE=gr().f,zE=Qr(),KE=ct(),XE=ch(),JE=Ae(),dh=JE("toStringTag");ph.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(KE(i,dh)||YE(i,dh,{configurable:!0,value:e}),r&&!WE&&zE(i,"toString",XE))}});var mh=b((xM,hh)=>{"use strict";var ZE=_o().IteratorPrototype,ex=Co(),tx=Li(),rx=Fi(),ix=vr(),ax=function(){return this};hh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=ex(ZE,{next:tx(+!r,t)}),rx(a,i,!1,!0),ix[i]=ax,a}});var bh=b((PM,fh)=>{"use strict";var sx=Ie(),nx=vt();fh.exports=function(a,e,t){try{return sx(nx(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var vh=b((wM,gh)=>{"use strict";var ox=Ye();gh.exports=function(a){return ox(a)||a===null}});var yh=b((AM,Sh)=>{"use strict";var ux=vh(),lx=String,cx=TypeError;Sh.exports=function(a){if(ux(a))return a;throw new cx("Can't set "+lx(a)+" as a prototype")}});var No=b((kM,Th)=>{"use strict";var dx=bh(),px=Ye(),hx=zt(),mx=yh();Th.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=dx(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return hx(i),mx(s),px(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Mh=b((LM,Rh)=>{"use strict";var fx=Se(),bx=We(),$s=lt(),Lh=Lo(),gx=fe(),vx=mh(),Ih=Is(),Eh=No(),Sx=Fi(),yx=Qr(),Fo=Kr(),Tx=Ae(),xh=vr(),$h=_o(),Ix=Lh.PROPER,Ex=Lh.CONFIGURABLE,Ph=$h.IteratorPrototype,Rs=$h.BUGGY_SAFARI_ITERATORS,qi=Tx("iterator"),wh="keys",Ui="values",Ah="entries",kh=function(){return this};Rh.exports=function(a,e,t,r,i,s,n){vx(t,e,r);var o=function(I){if(I===i&&p)return p;if(!Rs&&I&&I in c)return c[I];switch(I){case wh:return function(){return new t(this,I)};case Ui:return function(){return new t(this,I)};case Ah:return function(){return new t(this,I)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[qi]||c["@@iterator"]||i&&c[i],p=!Rs&&d||o(i),h=e==="Array"&&c.entries||d,f,g,S;if(h&&(f=Ih(h.call(new a)),f!==Object.prototype&&f.next&&(!$s&&Ih(f)!==Ph&&(Eh?Eh(f,Ph):gx(f[qi])||Fo(f,qi,kh)),Sx(f,u,!0,!0),$s&&(xh[u]=kh))),Ix&&i===Ui&&d&&d.name!==Ui&&(!$s&&Ex?yx(c,"name",Ui):(l=!0,p=function(){return bx(d,this)})),i)if(g={values:o(Ui),keys:s?p:o(wh),entries:o(Ah)},n)for(S in g)(Rs||l||!(S in c))&&Fo(c,S,g[S]);else fx({target:e,proto:!0,forced:Rs||l},g);return(!$s||n)&&c[qi]!==p&&Fo(c,qi,p,{name:i}),xh[e]=p,g}});var Ch=b(($M,Dh)=>{"use strict";Dh.exports=function(a,e){return{value:a,done:e}}});var Uo=b((RM,Nh)=>{"use strict";var xx=fr(),qo=Oi(),Vh=vr(),Oh=wo(),Px=gr().f,wx=Mh(),Ms=Ch(),Ax=lt(),kx=Ge(),_h="Array Iterator",Lx=Oh.set,$x=Oh.getterFor(_h);Nh.exports=wx(Array,"Array",function(a,e){Lx(this,{type:_h,target:xx(a),index:0,kind:e})},function(){var a=$x(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ms(void 0,!0);switch(a.kind){case"keys":return Ms(t,!1);case"values":return Ms(e[t],!1)}return Ms([t,e[t]],!1)},"values");var Bh=Vh.Arguments=Vh.Array;qo("keys");qo("values");qo("entries");if(!Ax&&kx&&Bh.name!=="values")try{Px(Bh,"name",{value:"values"})}catch(a){}});var qh=b((MM,Fh)=>{"use strict";var Rx=Ae(),Mx=vr(),Dx=Rx("iterator"),Cx=Array.prototype;Fh.exports=function(a){return a!==void 0&&(Mx.Array===a||Cx[Dx]===a)}});var Ho=b((DM,Hh)=>{"use strict";var Vx=Ni(),Uh=Mi(),Bx=Fr(),Ox=vr(),_x=Ae(),Nx=_x("iterator");Hh.exports=function(a){if(!Bx(a))return Uh(a,Nx)||Uh(a,"@@iterator")||Ox[Vx(a)]}});var Qh=b((CM,jh)=>{"use strict";var Fx=We(),qx=vt(),Ux=St(),Hx=Ri(),jx=Ho(),Qx=TypeError;jh.exports=function(a,e){var t=arguments.length<2?jx(a):e;if(qx(t))return Ux(Fx(t,a));throw new Qx(Hx(a)+" is not iterable")}});var Yh=b((VM,Wh)=>{"use strict";var Gx=We(),Gh=St(),Wx=Mi();Wh.exports=function(a,e,t){var r,i;Gh(a);try{if(r=Wx(a,"return"),!r){if(e==="throw")throw t;return t}r=Gx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Gh(r),t}});var Cs=b((BM,Jh)=>{"use strict";var Yx=jr(),zx=We(),Kx=St(),Xx=Ri(),Jx=qh(),Zx=Yr(),zh=$i(),eP=Qh(),tP=Ho(),Kh=Yh(),rP=TypeError,Ds=function(a,e){this.stopped=a,this.result=e},Xh=Ds.prototype;Jh.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=Yx(e,r),l,c,d,p,h,f,g,S=function(E){return l&&Kh(l,"normal",E),new Ds(!0,E)},I=function(E){return i?(Kx(E),o?u(E[0],E[1],S):u(E[0],E[1])):o?u(E,S):u(E)};if(s)l=a.iterator;else if(n)l=a;else{if(c=tP(a),!c)throw new rP(Xx(a)+" is not iterable");if(Jx(c)){for(d=0,p=Zx(a);p>d;d++)if(h=I(a[d]),h&&zh(Xh,h))return h;return new Ds(!1)}l=eP(a,c)}for(f=s?a.next:l.next;!(g=zx(f,l)).done;){try{h=I(g.value)}catch(E){Kh(l,"throw",E)}if(typeof h=="object"&&h&&zh(Xh,h))return h}return new Ds(!1)}});var em=b((OM,Zh)=>{"use strict";var iP=Ge(),aP=gr(),sP=Li();Zh.exports=function(a,e,t){iP?aP.f(a,e,sP(0,t)):a[e]=t}});var tm=b(()=>{"use strict";var nP=Se(),oP=Cs(),uP=em();nP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return oP(e,function(r,i){uP(t,r,i)},{AS_ENTRIES:!0}),t}})});var im=b((FM,rm)=>{"use strict";Uo();tm();var lP=qr();rm.exports=lP.Object.fromEntries});var sm=b((qM,am)=>{"use strict";am.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 om=b(()=>{"use strict";Uo();var cP=sm(),dP=ge(),pP=Fi(),nm=vr();for(Vs in cP)pP(dP[Vs],Vs),nm[Vs]=nm.Array;var Vs});var lm=b((jM,um)=>{"use strict";var hP=im();om();um.exports=hP});var jo=b((QM,cm)=>{"use strict";var mP=lm();cm.exports=mP});var dm=b(()=>{"use strict"});var Qo=b((YM,pm)=>{"use strict";var Hi=ge(),fP=br(),bP=mr(),Bs=function(a){return fP.slice(0,a.length)===a};pm.exports=function(){return Bs("Bun/")?"BUN":Bs("Cloudflare-Workers")?"CLOUDFLARE":Bs("Deno/")?"DENO":Bs("Node.js/")?"NODE":Hi.Bun&&typeof Bun.version=="string"?"BUN":Hi.Deno&&typeof Deno.version=="object"?"DENO":bP(Hi.process)==="process"?"NODE":Hi.window&&Hi.document?"BROWSER":"REST"}()});var Os=b((zM,hm)=>{"use strict";var gP=Qo();hm.exports=gP==="NODE"});var fm=b((KM,mm)=>{"use strict";var vP=gr();mm.exports=function(a,e,t){return vP.f(a,e,t)}});var vm=b((XM,gm)=>{"use strict";var SP=Lt(),yP=fm(),TP=Ae(),IP=Ge(),bm=TP("species");gm.exports=function(a){var e=SP(a);IP&&e&&!e[bm]&&yP(e,bm,{configurable:!0,get:function(){return this}})}});var ym=b((JM,Sm)=>{"use strict";var EP=$i(),xP=TypeError;Sm.exports=function(a,e){if(EP(e,a))return a;throw new xP("Incorrect invocation")}});var Wo=b((ZM,Tm)=>{"use strict";var PP=Ie(),wP=fe(),Go=Di(),AP=PP(Function.toString);wP(Go.inspectSource)||(Go.inspectSource=function(a){return AP(a)});Tm.exports=Go.inspectSource});var zo=b((eD,wm)=>{"use strict";var kP=Ie(),LP=we(),Im=fe(),$P=Ni(),RP=Lt(),MP=Wo(),Em=function(){},xm=RP("Reflect","construct"),Yo=/^\s*(?:class|function)\b/,DP=kP(Yo.exec),CP=!Yo.test(Em),ji=function(e){if(!Im(e))return!1;try{return xm(Em,[],e),!0}catch(t){return!1}},Pm=function(e){if(!Im(e))return!1;switch($P(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return CP||!!DP(Yo,MP(e))}catch(t){return!0}};Pm.sham=!0;wm.exports=!xm||LP(function(){var a;return ji(ji.call)||!ji(Object)||!ji(function(){a=!0})||a})?Pm:ji});var km=b((tD,Am)=>{"use strict";var VP=zo(),BP=Ri(),OP=TypeError;Am.exports=function(a){if(VP(a))return a;throw new OP(BP(a)+" is not a constructor")}});var Ko=b((rD,$m)=>{"use strict";var Lm=St(),_P=km(),NP=Fr(),FP=Ae(),qP=FP("species");$m.exports=function(a,e){var t=Lm(a).constructor,r;return t===void 0||NP(r=Lm(t)[qP])?e:_P(r)}});var Mm=b((iD,Rm)=>{"use strict";var UP=Ie();Rm.exports=UP([].slice)});var Cm=b((aD,Dm)=>{"use strict";var HP=TypeError;Dm.exports=function(a,e){if(a<e)throw new HP("Not enough arguments");return a}});var Xo=b((sD,Vm)=>{"use strict";var jP=br();Vm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(jP)});var nu=b((nD,jm)=>{"use strict";var ze=ge(),QP=qn(),GP=jr(),Bm=fe(),WP=ct(),Hm=we(),Om=$o(),YP=Mm(),_m=vs(),zP=Cm(),KP=Xo(),XP=Os(),iu=ze.setImmediate,au=ze.clearImmediate,JP=ze.process,Jo=ze.Dispatch,ZP=ze.Function,Nm=ze.MessageChannel,ew=ze.String,Zo=0,Qi={},Fm="onreadystatechange",Gi,yr,eu,tu;Hm(function(){Gi=ze.location});var su=function(a){if(WP(Qi,a)){var e=Qi[a];delete Qi[a],e()}},ru=function(a){return function(){su(a)}},qm=function(a){su(a.data)},Um=function(a){ze.postMessage(ew(a),Gi.protocol+"//"+Gi.host)};(!iu||!au)&&(iu=function(e){zP(arguments.length,1);var t=Bm(e)?e:ZP(e),r=YP(arguments,1);return Qi[++Zo]=function(){QP(t,void 0,r)},yr(Zo),Zo},au=function(e){delete Qi[e]},XP?yr=function(a){JP.nextTick(ru(a))}:Jo&&Jo.now?yr=function(a){Jo.now(ru(a))}:Nm&&!KP?(eu=new Nm,tu=eu.port2,eu.port1.onmessage=qm,yr=GP(tu.postMessage,tu)):ze.addEventListener&&Bm(ze.postMessage)&&!ze.importScripts&&Gi&&Gi.protocol!=="file:"&&!Hm(Um)?(yr=Um,ze.addEventListener("message",qm,!1)):Fm in _m("script")?yr=function(a){Om.appendChild(_m("script"))[Fm]=function(){Om.removeChild(this),su(a)}}:yr=function(a){setTimeout(ru(a),0)});jm.exports={set:iu,clear:au}});var Wm=b((oD,Gm)=>{"use strict";var Qm=ge(),tw=Ge(),rw=Object.getOwnPropertyDescriptor;Gm.exports=function(a){if(!tw)return Qm[a];var e=rw(Qm,a);return e&&e.value}});var ou=b((uD,zm)=>{"use strict";var Ym=function(){this.head=null,this.tail=null};Ym.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}}};zm.exports=Ym});var Xm=b((lD,Km)=>{"use strict";var iw=br();Km.exports=/ipad|iphone|ipod/i.test(iw)&&typeof Pebble!="undefined"});var Zm=b((cD,Jm)=>{"use strict";var aw=br();Jm.exports=/web0s(?!.*chrome)/i.test(aw)});var of=b((dD,nf)=>{"use strict";var Jr=ge(),sw=Wm(),ef=jr(),uu=nu().set,nw=ou(),ow=Xo(),uw=Xm(),lw=Zm(),lu=Os(),tf=Jr.MutationObserver||Jr.WebKitMutationObserver,rf=Jr.document,af=Jr.process,_s=Jr.Promise,pu=sw("queueMicrotask"),Xr,cu,du,Ns,sf;pu||(Wi=new nw,Yi=function(){var a,e;for(lu&&(a=af.domain)&&a.exit();e=Wi.get();)try{e()}catch(t){throw Wi.head&&Xr(),t}a&&a.enter()},!ow&&!lu&&!lw&&tf&&rf?(cu=!0,du=rf.createTextNode(""),new tf(Yi).observe(du,{characterData:!0}),Xr=function(){du.data=cu=!cu}):!uw&&_s&&_s.resolve?(Ns=_s.resolve(void 0),Ns.constructor=_s,sf=ef(Ns.then,Ns),Xr=function(){sf(Yi)}):lu?Xr=function(){af.nextTick(Yi)}:(uu=ef(uu,Jr),Xr=function(){uu(Yi)}),pu=function(a){Wi.head||Xr(),Wi.add(a)});var Wi,Yi;nf.exports=pu});var lf=b((pD,uf)=>{"use strict";uf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Fs=b((hD,cf)=>{"use strict";cf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Tr=b((mD,df)=>{"use strict";var cw=ge();df.exports=cw.Promise});var Zr=b((fD,ff)=>{"use strict";var dw=ge(),zi=Tr(),pw=fe(),hw=lo(),mw=Wo(),fw=Ae(),pf=Qo(),bw=lt(),hu=Kn(),hf=zi&&zi.prototype,gw=fw("species"),mu=!1,mf=pw(dw.PromiseRejectionEvent),vw=hw("Promise",function(){var a=mw(zi),e=a!==String(zi);if(!e&&hu===66||bw&&!(hf.catch&&hf.finally))return!0;if(!hu||hu<51||!/native code/.test(a)){var t=new zi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[gw]=r,mu=t.then(function(){})instanceof r,!mu)return!0}return!e&&(pf==="BROWSER"||pf==="DENO")&&!mf});ff.exports={CONSTRUCTOR:vw,REJECTION_EVENT:mf,SUBCLASSING:mu}});var ei=b((bD,gf)=>{"use strict";var bf=vt(),Sw=TypeError,yw=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Sw("Bad Promise constructor");e=r,t=i}),this.resolve=bf(e),this.reject=bf(t)};gf.exports.f=function(a){return new yw(a)}});var Bf=b(()=>{"use strict";var Tw=Se(),Iw=lt(),js=Os(),Xt=ge(),ai=We(),vf=Kr(),Sf=No(),Ew=Fi(),xw=vm(),Pw=vt(),Hs=fe(),ww=Ye(),Aw=ym(),kw=Ko(),xf=nu().set,Su=of(),Lw=lf(),$w=Fs(),Rw=ou(),Pf=wo(),Qs=Tr(),yu=Zr(),wf=ei(),Gs="Promise",Af=yu.CONSTRUCTOR,Mw=yu.REJECTION_EVENT,Dw=yu.SUBCLASSING,fu=Pf.getterFor(Gs),Cw=Pf.set,ti=Qs&&Qs.prototype,Ir=Qs,qs=ti,kf=Xt.TypeError,bu=Xt.document,Tu=Xt.process,gu=wf.f,Vw=gu,Bw=!!(bu&&bu.createEvent&&Xt.dispatchEvent),Lf="unhandledrejection",Ow="rejectionhandled",yf=0,$f=1,_w=2,Iu=1,Rf=2,Us,Tf,Nw,If,Mf=function(a){var e;return ww(a)&&Hs(e=a.then)?e:!1},Df=function(a,e){var t=e.value,r=e.state===$f,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Rf&&qw(e),e.rejection=Iu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new kf("Promise-chain cycle")):(l=Mf(u))?ai(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Cf=function(a,e){a.notified||(a.notified=!0,Su(function(){for(var t=a.reactions,r;r=t.get();)Df(r,a);a.notified=!1,e&&!a.rejection&&Fw(a)}))},Vf=function(a,e,t){var r,i;Bw?(r=bu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Xt.dispatchEvent(r)):r={promise:e,reason:t},!Mw&&(i=Xt["on"+a])?i(r):a===Lf&&Lw("Unhandled promise rejection",t)},Fw=function(a){ai(xf,Xt,function(){var e=a.facade,t=a.value,r=Ef(a),i;if(r&&(i=$w(function(){js?Tu.emit("unhandledRejection",t,e):Vf(Lf,e,t)}),a.rejection=js||Ef(a)?Rf:Iu,i.error))throw i.value})},Ef=function(a){return a.rejection!==Iu&&!a.parent},qw=function(a){ai(xf,Xt,function(){var e=a.facade;js?Tu.emit("rejectionHandled",e):Vf(Ow,e,a.value)})},ri=function(a,e,t){return function(r){a(e,r,t)}},ii=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=_w,Cf(a,!0))},vu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new kf("Promise can't be resolved itself");var r=Mf(e);r?Su(function(){var i={done:!1};try{ai(r,e,ri(vu,i,a),ri(ii,i,a))}catch(s){ii(i,s,a)}}):(a.value=e,a.state=$f,Cf(a,!1))}catch(i){ii({done:!1},i,a)}}};if(Af&&(Ir=function(e){Aw(this,qs),Pw(e),ai(Us,this);var t=fu(this);try{e(ri(vu,t),ri(ii,t))}catch(r){ii(t,r)}},qs=Ir.prototype,Us=function(e){Cw(this,{type:Gs,done:!1,notified:!1,parent:!1,reactions:new Rw,rejection:!1,state:yf,value:void 0})},Us.prototype=vf(qs,"then",function(e,t){var r=fu(this),i=gu(kw(this,Ir));return r.parent=!0,i.ok=Hs(e)?e:!0,i.fail=Hs(t)&&t,i.domain=js?Tu.domain:void 0,r.state===yf?r.reactions.add(i):Su(function(){Df(i,r)}),i.promise}),Tf=function(){var a=new Us,e=fu(a);this.promise=a,this.resolve=ri(vu,e),this.reject=ri(ii,e)},wf.f=gu=function(a){return a===Ir||a===Nw?new Tf(a):Vw(a)},!Iw&&Hs(Qs)&&ti!==Object.prototype)){If=ti.then,Dw||vf(ti,"then",function(e,t){var r=this;return new Ir(function(i,s){ai(If,r,i,s)}).then(e,t)},{unsafe:!0});try{delete ti.constructor}catch(a){}Sf&&Sf(ti,qs)}Tw({global:!0,constructor:!0,wrap:!0,forced:Af},{Promise:Ir});Ew(Ir,Gs,!1,!0);xw(Gs)});var qf=b((SD,Ff)=>{"use strict";var Uw=Ae(),_f=Uw("iterator"),Nf=!1;try{Of=0,Eu={next:function(){return{done:!!Of++}},return:function(){Nf=!0}},Eu[_f]=function(){return this},Array.from(Eu,function(){throw 2})}catch(a){}var Of,Eu;Ff.exports=function(a,e){try{if(!e&&!Nf)return!1}catch(i){return!1}var t=!1;try{var r={};r[_f]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var xu=b((yD,Uf)=>{"use strict";var Hw=Tr(),jw=qf(),Qw=Zr().CONSTRUCTOR;Uf.exports=Qw||!jw(function(a){Hw.all(a).then(void 0,function(){})})});var Hf=b(()=>{"use strict";var Gw=Se(),Ww=We(),Yw=vt(),zw=ei(),Kw=Fs(),Xw=Cs(),Jw=xu();Gw({target:"Promise",stat:!0,forced:Jw},{all:function(e){var t=this,r=zw.f(t),i=r.resolve,s=r.reject,n=Kw(function(){var o=Yw(t.resolve),u=[],l=0,c=1;Xw(e,function(d){var p=l++,h=!1;c++,Ww(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Qf=b(()=>{"use strict";var Zw=Se(),eA=lt(),tA=Zr().CONSTRUCTOR,wu=Tr(),rA=Lt(),iA=fe(),aA=Kr(),jf=wu&&wu.prototype;Zw({target:"Promise",proto:!0,forced:tA,real:!0},{catch:function(a){return this.then(void 0,a)}});!eA&&iA(wu)&&(Pu=rA("Promise").prototype.catch,jf.catch!==Pu&&aA(jf,"catch",Pu,{unsafe:!0}));var Pu});var Gf=b(()=>{"use strict";var sA=Se(),nA=We(),oA=vt(),uA=ei(),lA=Fs(),cA=Cs(),dA=xu();sA({target:"Promise",stat:!0,forced:dA},{race:function(e){var t=this,r=uA.f(t),i=r.reject,s=lA(function(){var n=oA(t.resolve);cA(e,function(o){nA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Wf=b(()=>{"use strict";var pA=Se(),hA=ei(),mA=Zr().CONSTRUCTOR;pA({target:"Promise",stat:!0,forced:mA},{reject:function(e){var t=hA.f(this),r=t.reject;return r(e),t.promise}})});var Au=b((LD,Yf)=>{"use strict";var fA=St(),bA=Ye(),gA=ei();Yf.exports=function(a,e){if(fA(a),bA(e)&&e.constructor===a)return e;var t=gA.f(a),r=t.resolve;return r(e),t.promise}});var Xf=b(()=>{"use strict";var vA=Se(),SA=Lt(),zf=lt(),yA=Tr(),Kf=Zr().CONSTRUCTOR,TA=Au(),IA=SA("Promise"),EA=zf&&!Kf;vA({target:"Promise",stat:!0,forced:zf||Kf},{resolve:function(e){return TA(EA&&this===IA?yA:this,e)}})});var Jf=b(()=>{"use strict";Bf();Hf();Qf();Gf();Wf();Xf()});var rb=b(()=>{"use strict";var xA=Se(),PA=lt(),Ws=Tr(),wA=we(),eb=Lt(),tb=fe(),AA=Ko(),Zf=Au(),kA=Kr(),Lu=Ws&&Ws.prototype,LA=!!Ws&&wA(function(){Lu.finally.call({then:function(){}},function(){})});xA({target:"Promise",proto:!0,real:!0,forced:LA},{finally:function(a){var e=AA(this,eb("Promise")),t=tb(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)}});!PA&&tb(Ws)&&(ku=eb("Promise").prototype.finally,Lu.finally!==ku&&kA(Lu,"finally",ku,{unsafe:!0}));var ku});var ab=b((BD,ib)=>{"use strict";dm();Jf();rb();var $A=Kt();ib.exports=$A("Promise","finally")});var nb=b((OD,sb)=>{"use strict";var RA=ab();sb.exports=RA});var Ys=b((_D,ob)=>{"use strict";var MA=nb();ob.exports=MA});var mb=b(()=>{"use strict";var OA=Se(),_A=Io().values;OA({target:"Object",stat:!0},{values:function(e){return _A(e)}})});var bb=b((fC,fb)=>{"use strict";mb();var NA=qr();fb.exports=NA.Object.values});var vb=b((bC,gb)=>{"use strict";var FA=bb();gb.exports=FA});var si=b((gC,Sb)=>{"use strict";var qA=vb();Sb.exports=qA});var Eb=b(()=>{"use strict";var QA=Se(),GA=Ur(),WA=Yr(),YA=Bi(),zA=Oi();QA({target:"Array",proto:!0},{at:function(e){var t=GA(this),r=WA(t),i=YA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});zA("at")});var Pb=b((qC,xb)=>{"use strict";Eb();var KA=Kt();xb.exports=KA("Array","at")});var Ab=b((UC,wb)=>{"use strict";var XA=Pb();wb.exports=XA});var tr=b((HC,kb)=>{"use strict";var JA=Ab();kb.exports=JA});var Yu=b((vV,Kb)=>{"use strict";var ck=mr();Kb.exports=Array.isArray||function(e){return ck(e)==="Array"}});var Jb=b((SV,Xb)=>{"use strict";var dk=TypeError,pk=9007199254740991;Xb.exports=function(a){if(a>pk)throw dk("Maximum allowed index exceeded");return a}});var tg=b((yV,eg)=>{"use strict";var hk=Yu(),mk=Yr(),fk=Jb(),bk=jr(),Zb=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?bk(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&hk(d)?(p=mk(d),u=Zb(a,e,d,p,u,s-1)-1):(fk(u+1),a[u]=d),u++),l++;return u};eg.exports=Zb});var sg=b((TV,ag)=>{"use strict";var rg=Yu(),gk=zo(),vk=Ye(),Sk=Ae(),yk=Sk("species"),ig=Array;ag.exports=function(a){var e;return rg(a)&&(e=a.constructor,gk(e)&&(e===ig||rg(e.prototype))?e=void 0:vk(e)&&(e=e[yk],e===null&&(e=void 0))),e===void 0?ig:e}});var og=b((IV,ng)=>{"use strict";var Tk=sg();ng.exports=function(a,e){return new(Tk(a))(e===0?0:e)}});var ug=b(()=>{"use strict";var Ik=Se(),Ek=tg(),xk=vt(),Pk=Ur(),wk=Yr(),Ak=og();Ik({target:"Array",proto:!0},{flatMap:function(e){var t=Pk(this),r=wk(t),i;return xk(e),i=Ak(t,0),i.length=Ek(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var lg=b(()=>{"use strict";var kk=Oi();kk("flatMap")});var dg=b((AV,cg)=>{"use strict";ug();lg();var Lk=Kt();cg.exports=Lk("Array","flatMap")});var hg=b((kV,pg)=>{"use strict";var $k=dg();pg.exports=$k});var zu=b((LV,mg)=>{"use strict";var Rk=hg();mg.exports=Rk});var ua=b((NV,Cg)=>{"use strict";var Nk=Ni(),Fk=String;Cg.exports=function(a){if(Nk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Fk(a)}});var Xu=b((FV,Vg)=>{"use strict";Vg.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 _g=b((qV,Og)=>{"use strict";var qk=Ie(),Uk=zt(),Hk=ua(),Zu=Xu(),Bg=qk("".replace),jk=RegExp("^["+Zu+"]+"),Qk=RegExp("(^|[^"+Zu+"])["+Zu+"]+$"),Ju=function(a){return function(e){var t=Hk(Uk(e));return a&1&&(t=Bg(t,jk,"")),a&2&&(t=Bg(t,Qk,"$1")),t}};Og.exports={start:Ju(1),end:Ju(2),trim:Ju(3)}});var Ug=b((UV,qg)=>{"use strict";var Gk=Lo().PROPER,Wk=we(),Ng=Xu(),Fg="\u200B\x85\u180E";qg.exports=function(a){return Wk(function(){return!!Ng[a]()||Fg[a]()!==Fg||Gk&&Ng[a].name!==a})}});var el=b((HV,Hg)=>{"use strict";var Yk=_g().start,zk=Ug();Hg.exports=zk("trimStart")?function(){return Yk(this)}:"".trimStart});var Qg=b(()=>{"use strict";var Kk=Se(),jg=el();Kk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==jg},{trimLeft:jg})});var Wg=b(()=>{"use strict";Qg();var Xk=Se(),Gg=el();Xk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Gg},{trimStart:Gg})});var zg=b((YV,Yg)=>{"use strict";Wg();var Jk=Kt();Yg.exports=Jk("String","trimLeft")});var Xg=b((zV,Kg)=>{"use strict";var Zk=zg();Kg.exports=Zk});var Zg=b((KV,Jg)=>{"use strict";var eL=Xg();Jg.exports=eL});var hv=b(()=>{"use strict"});var mv=b(()=>{"use strict"});var bv=b((k_,fv)=>{"use strict";var yL=Ye(),TL=mr(),IL=Ae(),EL=IL("match");fv.exports=function(a){var e;return yL(a)&&((e=a[EL])!==void 0?!!e:TL(a)==="RegExp")}});var vv=b((L_,gv)=>{"use strict";var xL=St();gv.exports=function(){var a=xL(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 Tv=b(($_,yv)=>{"use strict";var PL=We(),wL=ct(),AL=$i(),kL=vv(),Sv=RegExp.prototype;yv.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in Sv)&&!wL(a,"flags")&&AL(Sv,a)?PL(kL,a):e}});var Ev=b((R_,Iv)=>{"use strict";var ol=Ie(),LL=Ur(),$L=Math.floor,sl=ol("".charAt),RL=ol("".replace),nl=ol("".slice),ML=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,DL=/\$([$&'`]|\d{1,2})/g;Iv.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=DL;return i!==void 0&&(i=LL(i),u=ML),RL(s,u,function(l,c){var d;switch(sl(c,0)){case"$":return"$";case"&":return a;case"`":return nl(e,0,t);case"'":return nl(e,n);case"<":d=i[nl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=$L(p/10);return h===0?l:h<=o?r[h-1]===void 0?sl(c,1):r[h-1]+sl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var wv=b(()=>{"use strict";var CL=Se(),VL=We(),ll=Ie(),xv=zt(),BL=fe(),OL=Fr(),_L=bv(),pi=ua(),NL=Mi(),FL=Tv(),qL=Ev(),UL=Ae(),HL=lt(),jL=UL("replace"),QL=TypeError,ul=ll("".indexOf),GL=ll("".replace),Pv=ll("".slice),WL=Math.max;CL({target:"String",proto:!0},{replaceAll:function(e,t){var r=xv(this),i,s,n,o,u,l,c,d,p,h,f=0,g="";if(!OL(e)){if(i=_L(e),i&&(s=pi(xv(FL(e))),!~ul(s,"g")))throw new QL("`.replaceAll` does not allow non-global regexes");if(n=NL(e,jL),n)return VL(n,e,r,t);if(HL&&i)return GL(pi(r),e,t)}for(o=pi(r),u=pi(e),l=BL(t),l||(t=pi(t)),c=u.length,d=WL(1,c),p=ul(o,u);p!==-1;)h=l?pi(t(u,p,o)):qL(u,o,p,[],void 0,t),g+=Pv(o,f,p)+h,f=p+c,p=p+d>o.length?-1:ul(o,u,p+d);return f<o.length&&(g+=Pv(o,f)),g}})});var kv=b((C_,Av)=>{"use strict";hv();mv();wv();var YL=Kt();Av.exports=YL("String","replaceAll")});var $v=b((V_,Lv)=>{"use strict";var zL=kv();Lv.exports=zL});var Mv=b((B_,Rv)=>{"use strict";var KL=$v();Rv.exports=KL});var Cv=b((O_,Dv)=>{"use strict";var XL=Bi(),JL=ua(),ZL=zt(),e$=RangeError;Dv.exports=function(e){var t=JL(ZL(this)),r="",i=XL(e);if(i<0||i===1/0)throw new e$("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var Nv=b((__,_v)=>{"use strict";var Ov=Ie(),t$=bo(),Vv=ua(),r$=Cv(),i$=zt(),a$=Ov(r$),s$=Ov("".slice),n$=Math.ceil,Bv=function(a){return function(e,t,r){var i=Vv(i$(e)),s=t$(t),n=i.length,o=r===void 0?" ":Vv(r),u,l;return s<=n||o===""?i:(u=s-n,l=a$(o,n$(u/o.length)),l.length>u&&(l=s$(l,0,u)),a?i+l:l+i)}};_v.exports={start:Bv(!1),end:Bv(!0)}});var qv=b((N_,Fv)=>{"use strict";var o$=br();Fv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(o$)});var Uv=b(()=>{"use strict";var u$=Se(),l$=Nv().start,c$=qv();u$({target:"String",proto:!0,forced:c$},{padStart:function(e){return l$(this,e,arguments.length>1?arguments[1]:void 0)}})});var jv=b((U_,Hv)=>{"use strict";Uv();var d$=Kt();Hv.exports=d$("String","padStart")});var Gv=b((H_,Qv)=>{"use strict";var p$=jv();Qv.exports=p$});var Yv=b((j_,Wv)=>{"use strict";var h$=Gv();Wv.exports=h$});var R$={};ry(R$,{ChromecastState:()=>Pi,HttpConnectionType:()=>ms,Observable:()=>wt.Observable,PlaybackState:()=>Be,Player:()=>Ja,PredefinedQualityLimits:()=>wi,SDK_VERSION:()=>$$,Subject:()=>wt.Subject,Subscription:()=>wt.Subscription,Surface:()=>fs,VERSION:()=>Nn,ValueSubject:()=>wt.ValueSubject,VideoFormat:()=>kt,VideoQuality:()=>wt.VideoQuality});module.exports=iy(R$);var Nn="2.0.128";var Be=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Be||{}),kt=(P=>(P.MPEG="MPEG",P.DASH="DASH",P.DASH_SEP="DASH_SEP",P.DASH_SEP_VK="DASH_SEP",P.DASH_WEBM="DASH_WEBM",P.DASH_WEBM_AV1="DASH_WEBM_AV1",P.DASH_STREAMS="DASH_STREAMS",P.DASH_WEBM_VK="DASH_WEBM",P.DASH_ONDEMAND="DASH_ONDEMAND",P.DASH_ONDEMAND_VK="DASH_ONDEMAND",P.DASH_LIVE="DASH_LIVE",P.DASH_LIVE_CMAF="DASH_LIVE_CMAF",P.DASH_LIVE_WEBM="DASH_LIVE_WEBM",P.HLS="HLS",P.HLS_ONDEMAND="HLS_ONDEMAND",P.HLS_JS="HLS",P.HLS_LIVE="HLS_LIVE",P.HLS_LIVE_CMAF="HLS_LIVE_CMAF",P.WEB_RTC_LIVE="WEB_RTC_LIVE",P))(kt||{});var Pi=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(Pi||{}),ms=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ms||{});var fs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(fs||{}),wi=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(wi||{});var qS=W(dt(),1);var j=require("@vkontakte/videoplayer-shared/es2015");var hp=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 ys=class{constructor(e){this.connection$=new j.ValueSubject(void 0);this.castState$=new j.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new j.Subject;this.realCastState$=new j.ValueSubject("NOT_AVAILABLE");this.subscription=new j.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,j.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||hp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:j.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,j.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,j.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,j.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,j.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,j.assertNever)(i.sessionState)}})).add((0,j.merge)((0,j.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,j.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,j.map)(i=>i.castState)),(0,j.observableFrom)([r.getCastState()])).pipe((0,j.filterChanged)(),(0,j.map)(PI),(0,j.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,j.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,j.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,j.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,j.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:j.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},PI=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,j.assertNever)(a)}};var $l=W(dt(),1),kS=W(zr(),1),LS=W(jo(),1);var db=W(Ys(),1);var $u=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 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,$u.assertNever)(t)}return a},zs=(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,$u.assertNever)(e)}};var $=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var yt=require("@vkontakte/videoplayer-shared/es2015"),Y=class{constructor(e){this.transitionStarted$=new yt.Subject;this.transitionEnded$=new yt.Subject;this.transitionUpdated$=new yt.Subject;this.forceChanged$=new yt.Subject;this.stateChangeStarted$=(0,yt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,yt.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,yt.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 ub=require("@vkontakte/videoplayer-shared/es2015"),lb=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,ub.assertNever)(a)}};var M=require("@vkontakte/videoplayer-shared/es2015");var DA=5,CA=5,VA=500,cb=7e3,Ki=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(lb(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new 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)(VA)).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)>DA)&&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<CA&&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 p=c[d];(0,M.assertNonNullable)(p),r=p,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=ke(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)(cb).subscribe(()=>s(`timeout(${cb})`)))});(0,db.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 Gu=W(dt(),1);var Cu=require("@vkontakte/videoplayer-shared/es2015");var pb=require("@vkontakte/videoplayer-shared/es2015"),hb=a=>{try{a.pause(),a.playbackRate=0,(0,pb.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Ks=require("@vkontakte/videoplayer-shared/es2015"),Ru=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)}},Mu=window.WeakMap?new WeakMap:new Ru,Du=window.WeakMap?new WeakMap:new Map,BA=(a,e=20)=>{let t=0;return(0,Ks.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Oe=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?(0,Cu.clearVideoElement)(r):(r=document.createElement("video"),a.appendChild(r)),Mu.set(r,i);let s=new Ks.Subscription;return s.add(BA(r,e)),Du.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},_e=a=>{let e=Du.get(a);e==null||e.unsubscribe(),Du.delete(a);let t=Mu.get(a);Mu.delete(a),t?(0,Cu.clearVideoElement)(a):hb(a)};var Vu=W(si(),1),D=require("@vkontakte/videoplayer-shared/es2015");var Jt=require("@vkontakte/videoplayer-shared/es2015"),Xs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,Jt.isNullable)(i),l=new Jt.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},Tt=(a,e,t)=>Xs(e,()=>a.loop,r=>{(0,Jt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Ne=(a,e,t,r)=>Xs(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,Jt.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)=>Xs(e,()=>a.playbackRate,i=>{(0,Jt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Zt=Xs;var UA=a=>["__",a.language,a.label].join("|"),HA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Bu=class a{constructor(e){this.available$=new D.Subject;this.current$=new D.ValueSubject(void 0);this.error$=new D.Subject;this.subscription=new D.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;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:D.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Zt(t.internalTextTracks,()=>(0,Vu.default)(this.internalTracks),s=>{(0,D.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,D.isNonNullable)(s)&&(0,D.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,D.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Zt(t.externalTextTracks,()=>(0,Vu.default)(this.externalTracks),s=>{(0,D.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,D.isNonNullable)(s)&&(0,D.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,D.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(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,D.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,D.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,D.merge)((0,D.fromEvent)(e,"addtrack"),(0,D.fromEvent)(e,"removetrack"),(0,D.observableFrom)(["init"])).pipe((0,D.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,D.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,D.merge)((0,D.fromEvent)(e,"change"),(0,D.observableFrom)(["init"])).pipe((0,D.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,D.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,D.filterChanged)()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add((0,D.fromEvent)(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add((0,D.fromEvent)(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;(0,D.isNonNullable)(t.align)&&(i.align=t.align),(0,D.isNonNullable)(t.position)&&(i.position=t.position),(0,D.isNonNullable)(t.size)&&(i.size=t.size),(0,D.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,D.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:UA(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){(0,D.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,D.isNullable)(e)||!HA(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){(0,D.assertNonNullable)(this.video);let t=document.createElement("track");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,D.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},et=Bu;var Er=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 yb=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},Ou=a=>{let e=yb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Tb=a=>{let e=yb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var C=require("@vkontakte/videoplayer-shared/es2015");var jA=3,Ib=(a,e,t=jA)=>{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 Fe=a=>{let e=P=>(0,C.fromEvent)(a,P).pipe((0,C.mapTo)(void 0)),r=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>(0,C.fromEvent)(a,P))).pipe((0,C.map)(P=>P.type==="ended"?a.readyState<2:a.readyState<3),(0,C.filterChanged)()),i=(0,C.merge)((0,C.fromEvent)(a,"progress"),(0,C.fromEvent)(a,"timeupdate")).pipe((0,C.map)(()=>Ib(a.buffered,a.currentTime))),s=C.clientChecker.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0)):e("playing"),n=(0,C.fromEvent)(a,"volumechange").pipe((0,C.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,C.fromEvent)(a,"ratechange").pipe((0,C.map)(()=>a.playbackRate)),u=(0,C.fromEvent)(a,"error").pipe((0,C.filter)(()=>!!(a.error||a.played.length)),(0,C.map)(()=>{var w;let P=a.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(w=a.error)!=null?w:void 0}})),l=(0,C.fromEvent)(a,"timeupdate").pipe((0,C.map)(()=>a.currentTime)),c=new C.Subject,d=.3,p;l.subscribe(P=>{a.loop&&(0,C.isNonNullable)(p)&&(0,C.isNonNullable)(P)&&p>=a.duration-d&&P<=d&&c.next(p),p=P});let h=e("pause").pipe((0,C.filter)(()=>!a.error&&p!==a.duration)),f=(0,C.fromEvent)(a,"enterpictureinpicture"),g=(0,C.fromEvent)(a,"leavepictureinpicture"),S=new C.ValueSubject(Tb(a));f.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let I=new C.ValueSubject(Ou(a));return(0,C.fromEvent)(a,"fullscreenchange").pipe((0,C.map)(()=>Ou(a))).subscribe(I),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,C.fromEvent)(a,"durationchange").pipe((0,C.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:I,enterPip$:f,leavePip$:g}};var Mt=require("@vkontakte/videoplayer-shared/es2015"),er=a=>{switch(a){case"mobile":return Mt.VideoQuality.Q_144P;case"lowest":return Mt.VideoQuality.Q_240P;case"low":return Mt.VideoQuality.Q_360P;case"sd":case"medium":return Mt.VideoQuality.Q_480P;case"hd":case"high":return Mt.VideoQuality.Q_720P;case"fullhd":case"full":return Mt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Mt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Mt.VideoQuality.Q_2160P}};var rr=W(tr(),1),Cb=W(dt(),1),Js=W(zr(),1),q=require("@vkontakte/videoplayer-shared/es2015");var _u=!1,Dt={},Lb=a=>{_u=a},$b=()=>{Dt={}},Rb=a=>{a(Dt)},Xi=(a,e)=>{var t;_u&&(Dt.meta=(t=Dt.meta)!=null?t:{},Dt.meta[a]=e)},De=class{constructor(e){this.name=e}next(e){var r,i;if(!_u)return;Dt.series=(r=Dt.series)!=null?r:{};let t=(i=Dt.series[this.name])!=null?i:[];t.push([Date.now(),e]),Dt.series[this.name]=t}};var ye=require("@vkontakte/videoplayer-shared/es2015");function Nu({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Fu({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&Nu({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Ji({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return(0,ye.isNullable)(a)||(0,ye.isNonNullable)(a.min)&&(0,ye.isNonNullable)(a.max)&&(0,ye.isLower)(a.max,a.min)||(0,ye.isNonNullable)(a.min)&&e&&(0,ye.isHigher)(a.min,e)||(0,ye.isNonNullable)(a.max)&&t&&(0,ye.isLower)(a.max,t)}function Mb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Ji({limits:{max:a!=null&&a.max?(0,ye.videoHeightToQuality)(a.max):void 0,min:a!=null&&a.min?(0,ye.videoHeightToQuality)(a.min):void 0},highestAvailableQuality:e?(0,ye.videoHeightToQuality)(e):void 0,lowestAvailableQuality:t?(0,ye.videoHeightToQuality)(t):void 0})}var ZA=new De("best_bitrate"),Vb=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var qu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Zi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,q.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Bb='Assertion "ABR Tracks is empty array" failed',Zs=(a,e,t,r)=>{var u;let i=[...e].sort(qu(1)),s=[...t].sort(qu(1)),n=s.filter(l=>(0,q.isNonNullable)(l.bitrate)&&(0,q.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,rr.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,rr.default)(s,-1);return o&&(0,Cb.default)(n,o)?o:n.length?(0,rr.default)(n,-1):(0,rr.default)(s,0)},Db=a=>"quality"in a,Ob=(a,e,t,r)=>{var n;let i=(0,q.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,q.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,q.now)()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Db(o)?"video":"audio",l=Db(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
"use strict";var _S=Object.create;var Si=Object.defineProperty,BS=Object.defineProperties,OS=Object.getOwnPropertyDescriptor,NS=Object.getOwnPropertyDescriptors,FS=Object.getOwnPropertyNames,os=Object.getOwnPropertySymbols,qS=Object.getPrototypeOf,Mn=Object.prototype.hasOwnProperty,hc=Object.prototype.propertyIsEnumerable;var US=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var bt=Math.pow,pc=(a,e,t)=>e in a?Si(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,R=(a,e)=>{for(var t in e||(e={}))Mn.call(e,t)&&pc(a,t,e[t]);if(os)for(var t of os(e))hc.call(e,t)&&pc(a,t,e[t]);return a},F=(a,e)=>BS(a,NS(e));var mc=(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&&hc.call(a,r)&&(t[r]=a[r]);return t};var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),HS=(a,e)=>{for(var t in e)Si(a,t,{get:e[t],enumerable:!0})},fc=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of FS(e))!Mn.call(a,i)&&i!==t&&Si(a,i,{get:()=>e[i],enumerable:!(r=OS(e,i))||r.enumerable});return a};var G=(a,e,t)=>(t=a!=null?_S(qS(a)):{},fc(e||!a||!a.__esModule?Si(t,"default",{value:a,enumerable:!0}):t,a)),jS=a=>fc(Si({},"__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},ye=(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[US("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ve=b((Dn,bc)=>{"use strict";var Ii=function(a){return a&&a.Math===Math&&a};bc.exports=Ii(typeof globalThis=="object"&&globalThis)||Ii(typeof window=="object"&&window)||Ii(typeof self=="object"&&self)||Ii(typeof global=="object"&&global)||Ii(typeof Dn=="object"&&Dn)||function(){return this}()||Function("return this")()});var Ae=b((ER,gc)=>{"use strict";gc.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ei=b((xR,vc)=>{"use strict";var QS=Ae();vc.exports=!QS(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Vn=b((PR,Ic)=>{"use strict";var GS=Ei(),Tc=Function.prototype,Sc=Tc.apply,yc=Tc.call;Ic.exports=typeof Reflect=="object"&&Reflect.apply||(GS?yc.bind(Sc):function(){return yc.apply(Sc,arguments)})});var xe=b((wR,Pc)=>{"use strict";var Ec=Ei(),xc=Function.prototype,_n=xc.call,WS=Ec&&xc.bind.bind(_n,_n);Pc.exports=Ec?WS:function(a){return function(){return _n.apply(a,arguments)}}});var pr=b((AR,Ac)=>{"use strict";var wc=xe(),YS=wc({}.toString),zS=wc("".slice);Ac.exports=function(a){return zS(YS(a),8,-1)}});var Bn=b((kR,kc)=>{"use strict";var KS=pr(),XS=xe();kc.exports=function(a){if(KS(a)==="Function")return XS(a)}});var be=b(($R,$c)=>{"use strict";var On=typeof document=="object"&&document.all;$c.exports=typeof On=="undefined"&&On!==void 0?function(a){return typeof a=="function"||a===On}:function(a){return typeof a=="function"}});var je=b((RR,Rc)=>{"use strict";var JS=Ae();Rc.exports=!JS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Qe=b((LR,Lc)=>{"use strict";var ZS=Ei(),ds=Function.prototype.call;Lc.exports=ZS?ds.bind(ds):function(){return ds.apply(ds,arguments)}});var Nn=b(Dc=>{"use strict";var Mc={}.propertyIsEnumerable,Cc=Object.getOwnPropertyDescriptor,ey=Cc&&!Mc.call({1:2},1);Dc.f=ey?function(e){var t=Cc(this,e);return!!t&&t.enumerable}:Mc});var xi=b((CR,Vc)=>{"use strict";Vc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Bc=b((DR,_c)=>{"use strict";var ty=xe(),ry=Ae(),iy=pr(),Fn=Object,ay=ty("".split);_c.exports=ry(function(){return!Fn("z").propertyIsEnumerable(0)})?function(a){return iy(a)==="String"?ay(a,""):Fn(a)}:Fn});var Br=b((VR,Oc)=>{"use strict";Oc.exports=function(a){return a==null}});var Gt=b((_R,Nc)=>{"use strict";var sy=Br(),ny=TypeError;Nc.exports=function(a){if(sy(a))throw new ny("Can't call method on "+a);return a}});var hr=b((BR,Fc)=>{"use strict";var oy=Bc(),uy=Gt();Fc.exports=function(a){return oy(uy(a))}});var Ge=b((OR,qc)=>{"use strict";var ly=be();qc.exports=function(a){return typeof a=="object"?a!==null:ly(a)}});var Or=b((NR,Uc)=>{"use strict";Uc.exports={}});var At=b((FR,jc)=>{"use strict";var qn=Or(),Un=ve(),cy=be(),Hc=function(a){return cy(a)?a:void 0};jc.exports=function(a,e){return arguments.length<2?Hc(qn[a])||Hc(Un[a]):qn[a]&&qn[a][e]||Un[a]&&Un[a][e]}});var Pi=b((qR,Qc)=>{"use strict";var dy=xe();Qc.exports=dy({}.isPrototypeOf)});var mr=b((UR,Yc)=>{"use strict";var py=ve(),Gc=py.navigator,Wc=Gc&&Gc.userAgent;Yc.exports=Wc?String(Wc):""});var jn=b((HR,ed)=>{"use strict";var Zc=ve(),Hn=mr(),zc=Zc.process,Kc=Zc.Deno,Xc=zc&&zc.versions||Kc&&Kc.version,Jc=Xc&&Xc.v8,ot,ps;Jc&&(ot=Jc.split("."),ps=ot[0]>0&&ot[0]<4?1:+(ot[0]+ot[1]));!ps&&Hn&&(ot=Hn.match(/Edge\/(\d+)/),(!ot||ot[1]>=74)&&(ot=Hn.match(/Chrome\/(\d+)/),ot&&(ps=+ot[1])));ed.exports=ps});var Qn=b((jR,rd)=>{"use strict";var td=jn(),hy=Ae(),my=ve(),fy=my.String;rd.exports=!!Object.getOwnPropertySymbols&&!hy(function(){var a=Symbol("symbol detection");return!fy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&td&&td<41})});var Gn=b((QR,id)=>{"use strict";var by=Qn();id.exports=by&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Wn=b((GR,ad)=>{"use strict";var gy=At(),vy=be(),Sy=Pi(),yy=Gn(),Ty=Object;ad.exports=yy?function(a){return typeof a=="symbol"}:function(a){var e=gy("Symbol");return vy(e)&&Sy(e.prototype,Ty(a))}});var wi=b((WR,sd)=>{"use strict";var Iy=String;sd.exports=function(a){try{return Iy(a)}catch(e){return"Object"}}});var vt=b((YR,nd)=>{"use strict";var Ey=be(),xy=wi(),Py=TypeError;nd.exports=function(a){if(Ey(a))return a;throw new Py(xy(a)+" is not a function")}});var Ai=b((zR,od)=>{"use strict";var wy=vt(),Ay=Br();od.exports=function(a,e){var t=a[e];return Ay(t)?void 0:wy(t)}});var ld=b((KR,ud)=>{"use strict";var Yn=Qe(),zn=be(),Kn=Ge(),ky=TypeError;ud.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 ky("Can't convert object to primitive value")}});var ut=b((XR,cd)=>{"use strict";cd.exports=!0});var hd=b((JR,pd)=>{"use strict";var dd=ve(),$y=Object.defineProperty;pd.exports=function(a,e){try{$y(dd,a,{value:e,configurable:!0,writable:!0})}catch(t){dd[a]=e}return e}});var ki=b((ZR,bd)=>{"use strict";var Ry=ut(),Ly=ve(),My=hd(),md="__core-js_shared__",fd=bd.exports=Ly[md]||My(md,{});(fd.versions||(fd.versions=[])).push({version:"3.38.0",mode:Ry?"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((eL,vd)=>{"use strict";var gd=ki();vd.exports=function(a,e){return gd[a]||(gd[a]=e||{})}});var Nr=b((tL,Sd)=>{"use strict";var Cy=Gt(),Dy=Object;Sd.exports=function(a){return Dy(Cy(a))}});var lt=b((rL,yd)=>{"use strict";var Vy=xe(),_y=Nr(),By=Vy({}.hasOwnProperty);yd.exports=Object.hasOwn||function(e,t){return By(_y(e),t)}});var Jn=b((iL,Td)=>{"use strict";var Oy=xe(),Ny=0,Fy=Math.random(),qy=Oy(1 .toString);Td.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+qy(++Ny+Fy,36)}});var ke=b((aL,Ed)=>{"use strict";var Uy=ve(),Hy=Xn(),Id=lt(),jy=Jn(),Qy=Qn(),Gy=Gn(),Fr=Uy.Symbol,Zn=Hy("wks"),Wy=Gy?Fr.for||Fr:Fr&&Fr.withoutSetter||jy;Ed.exports=function(a){return Id(Zn,a)||(Zn[a]=Qy&&Id(Fr,a)?Fr[a]:Wy("Symbol."+a)),Zn[a]}});var Ad=b((sL,wd)=>{"use strict";var Yy=Qe(),xd=Ge(),Pd=Wn(),zy=Ai(),Ky=ld(),Xy=ke(),Jy=TypeError,Zy=Xy("toPrimitive");wd.exports=function(a,e){if(!xd(a)||Pd(a))return a;var t=zy(a,Zy),r;if(t){if(e===void 0&&(e="default"),r=Yy(t,a,e),!xd(r)||Pd(r))return r;throw new Jy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ky(a,e)}});var eo=b((nL,kd)=>{"use strict";var eT=Ad(),tT=Wn();kd.exports=function(a){var e=eT(a,"string");return tT(e)?e:e+""}});var hs=b((oL,Rd)=>{"use strict";var rT=ve(),$d=Ge(),to=rT.document,iT=$d(to)&&$d(to.createElement);Rd.exports=function(a){return iT?to.createElement(a):{}}});var ro=b((uL,Ld)=>{"use strict";var aT=je(),sT=Ae(),nT=hs();Ld.exports=!aT&&!sT(function(){return Object.defineProperty(nT("div"),"a",{get:function(){return 7}}).a!==7})});var Dd=b(Cd=>{"use strict";var oT=je(),uT=Qe(),lT=Nn(),cT=xi(),dT=hr(),pT=eo(),hT=lt(),mT=ro(),Md=Object.getOwnPropertyDescriptor;Cd.f=oT?Md:function(e,t){if(e=dT(e),t=pT(t),mT)try{return Md(e,t)}catch(r){}if(hT(e,t))return cT(!uT(lT.f,e,t),e[t])}});var io=b((cL,Vd)=>{"use strict";var fT=Ae(),bT=be(),gT=/#|\.prototype\./,$i=function(a,e){var t=ST[vT(a)];return t===TT?!0:t===yT?!1:bT(e)?fT(e):!!e},vT=$i.normalize=function(a){return String(a).replace(gT,".").toLowerCase()},ST=$i.data={},yT=$i.NATIVE="N",TT=$i.POLYFILL="P";Vd.exports=$i});var qr=b((dL,Bd)=>{"use strict";var _d=Bn(),IT=vt(),ET=Ei(),xT=_d(_d.bind);Bd.exports=function(a,e){return IT(a),e===void 0?a:ET?xT(a,e):function(){return a.apply(e,arguments)}}});var ao=b((pL,Od)=>{"use strict";var PT=je(),wT=Ae();Od.exports=PT&&wT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var St=b((hL,Nd)=>{"use strict";var AT=Ge(),kT=String,$T=TypeError;Nd.exports=function(a){if(AT(a))return a;throw new $T(kT(a)+" is not an object")}});var fr=b(qd=>{"use strict";var RT=je(),LT=ro(),MT=ao(),ms=St(),Fd=eo(),CT=TypeError,so=Object.defineProperty,DT=Object.getOwnPropertyDescriptor,no="enumerable",oo="configurable",uo="writable";qd.f=RT?MT?function(e,t,r){if(ms(e),t=Fd(t),ms(r),typeof e=="function"&&t==="prototype"&&"value"in r&&uo in r&&!r[uo]){var i=DT(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=Fd(t),ms(r),LT)try{return so(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new CT("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Ur=b((fL,Ud)=>{"use strict";var VT=je(),_T=fr(),BT=xi();Ud.exports=VT?function(a,e,t){return _T.f(a,e,BT(1,t))}:function(a,e,t){return a[e]=t,a}});var Te=b((bL,jd)=>{"use strict";var Ri=ve(),OT=Vn(),NT=Bn(),FT=be(),qT=Dd().f,UT=io(),Hr=Or(),HT=qr(),jr=Ur(),Hd=lt();ki();var jT=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 OT(a,this,arguments)};return e.prototype=a.prototype,e};jd.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?Hr:Hr[t]||jr(Hr,t,{})[t],u=o.prototype,l,c,d,h,m,f,g,S,T;for(h in e)l=UT(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&Hd(n,h),f=o[h],c&&(a.dontCallGetSet?(T=qT(n,h),g=T&&T.value):g=n[h]),m=c&&g?g:e[h],!(!l&&!s&&typeof f==typeof m)&&(a.bind&&c?S=HT(m,Ri):a.wrap&&c?S=jT(m):s&&FT(m)?S=NT(m):S=m,(a.sham||m&&m.sham||f&&f.sham)&&jr(S,"sham",!0),jr(o,h,S),s&&(d=t+"Prototype",Hd(Hr,d)||jr(Hr,d,{}),jr(Hr[d],h,m),a.real&&u&&(l||!u[h])&&jr(u,h,m)))}});var Gd=b((gL,Qd)=>{"use strict";var QT=Math.ceil,GT=Math.floor;Qd.exports=Math.trunc||function(e){var t=+e;return(t>0?GT:QT)(t)}});var Li=b((vL,Wd)=>{"use strict";var WT=Gd();Wd.exports=function(a){var e=+a;return e!==e||e===0?0:WT(e)}});var zd=b((SL,Yd)=>{"use strict";var YT=Li(),zT=Math.max,KT=Math.min;Yd.exports=function(a,e){var t=YT(a);return t<0?zT(t+e,0):KT(t,e)}});var lo=b((yL,Kd)=>{"use strict";var XT=Li(),JT=Math.min;Kd.exports=function(a){var e=XT(a);return e>0?JT(e,9007199254740991):0}});var Qr=b((TL,Xd)=>{"use strict";var ZT=lo();Xd.exports=function(a){return ZT(a.length)}});var co=b((IL,Zd)=>{"use strict";var eI=hr(),tI=zd(),rI=Qr(),Jd=function(a){return function(e,t,r){var i=eI(e),s=rI(i);if(s===0)return!a&&-1;var n=tI(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}};Zd.exports={includes:Jd(!0),indexOf:Jd(!1)}});var Mi=b((EL,ep)=>{"use strict";ep.exports=function(){}});var tp=b(()=>{"use strict";var iI=Te(),aI=co().includes,sI=Ae(),nI=Mi(),oI=sI(function(){return!Array(1).includes()});iI({target:"Array",proto:!0,forced:oI},{includes:function(e){return aI(this,e,arguments.length>1?arguments[1]:void 0)}});nI("includes")});var Wt=b((wL,rp)=>{"use strict";var uI=At();rp.exports=uI});var ap=b((AL,ip)=>{"use strict";tp();var lI=Wt();ip.exports=lI("Array","includes")});var np=b((kL,sp)=>{"use strict";var cI=ap();sp.exports=cI});var Xe=b(($L,op)=>{"use strict";var dI=np();op.exports=dI});var bs=b((FL,cp)=>{"use strict";var hI=Xn(),mI=Jn(),lp=hI("keys");cp.exports=function(a){return lp[a]||(lp[a]=mI(a))}});var pp=b((qL,dp)=>{"use strict";var fI=Ae();dp.exports=!fI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gs=b((UL,mp)=>{"use strict";var bI=lt(),gI=be(),vI=Nr(),SI=bs(),yI=pp(),hp=SI("IE_PROTO"),po=Object,TI=po.prototype;mp.exports=yI?po.getPrototypeOf:function(a){var e=vI(a);if(bI(e,hp))return e[hp];var t=e.constructor;return gI(t)&&e instanceof t?t.prototype:e instanceof po?TI:null}});var vs=b((HL,fp)=>{"use strict";fp.exports={}});var vp=b((jL,gp)=>{"use strict";var II=xe(),ho=lt(),EI=hr(),xI=co().indexOf,PI=vs(),bp=II([].push);gp.exports=function(a,e){var t=EI(a),r=0,i=[],s;for(s in t)!ho(PI,s)&&ho(t,s)&&bp(i,s);for(;e.length>r;)ho(t,s=e[r++])&&(~xI(i,s)||bp(i,s));return i}});var mo=b((QL,Sp)=>{"use strict";Sp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var fo=b((GL,yp)=>{"use strict";var wI=vp(),AI=mo();yp.exports=Object.keys||function(e){return wI(e,AI)}});var bo=b((WL,Pp)=>{"use strict";var Ip=je(),kI=Ae(),Ep=xe(),$I=gs(),RI=fo(),LI=hr(),MI=Nn().f,xp=Ep(MI),CI=Ep([].push),DI=Ip&&kI(function(){var a=Object.create(null);return a[2]=2,!xp(a,2)}),Tp=function(a){return function(e){for(var t=LI(e),r=RI(t),i=DI&&$I(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Ip||(i?u in t:xp(t,u)))&&CI(o,a?[u,t[u]]:t[u]);return o}};Pp.exports={entries:Tp(!0),values:Tp(!1)}});var wp=b(()=>{"use strict";var VI=Te(),_I=bo().entries;VI({target:"Object",stat:!0},{entries:function(e){return _I(e)}})});var kp=b((KL,Ap)=>{"use strict";wp();var BI=Or();Ap.exports=BI.Object.entries});var Rp=b((XL,$p)=>{"use strict";var OI=kp();$p.exports=OI});var Gr=b((JL,Lp)=>{"use strict";var NI=Rp();Lp.exports=NI});var br=b((ZL,Mp)=>{"use strict";Mp.exports={}});var Vp=b((eM,Dp)=>{"use strict";var FI=ve(),qI=be(),Cp=FI.WeakMap;Dp.exports=qI(Cp)&&/native code/.test(String(Cp))});var yo=b((tM,Op)=>{"use strict";var UI=Vp(),Bp=ve(),HI=Ge(),jI=Ur(),go=lt(),vo=ki(),QI=bs(),GI=vs(),_p="Object already initialized",So=Bp.TypeError,WI=Bp.WeakMap,Ss,Ci,ys,YI=function(a){return ys(a)?Ci(a):Ss(a,{})},zI=function(a){return function(e){var t;if(!HI(e)||(t=Ci(e)).type!==a)throw new So("Incompatible receiver, "+a+" required");return t}};UI||vo.state?(ct=vo.state||(vo.state=new WI),ct.get=ct.get,ct.has=ct.has,ct.set=ct.set,Ss=function(a,e){if(ct.has(a))throw new So(_p);return e.facade=a,ct.set(a,e),e},Ci=function(a){return ct.get(a)||{}},ys=function(a){return ct.has(a)}):(gr=QI("state"),GI[gr]=!0,Ss=function(a,e){if(go(a,gr))throw new So(_p);return e.facade=a,jI(a,gr,e),e},Ci=function(a){return go(a,gr)?a[gr]:{}},ys=function(a){return go(a,gr)});var ct,gr;Op.exports={set:Ss,get:Ci,has:ys,enforce:YI,getterFor:zI}});var Eo=b((rM,Fp)=>{"use strict";var To=je(),KI=lt(),Np=Function.prototype,XI=To&&Object.getOwnPropertyDescriptor,Io=KI(Np,"name"),JI=Io&&function(){}.name==="something",ZI=Io&&(!To||To&&XI(Np,"name").configurable);Fp.exports={EXISTS:Io,PROPER:JI,CONFIGURABLE:ZI}});var Up=b(qp=>{"use strict";var eE=je(),tE=ao(),rE=fr(),iE=St(),aE=hr(),sE=fo();qp.f=eE&&!tE?Object.defineProperties:function(e,t){iE(e);for(var r=aE(t),i=sE(t),s=i.length,n=0,o;s>n;)rE.f(e,o=i[n++],r[o]);return e}});var xo=b((aM,Hp)=>{"use strict";var nE=At();Hp.exports=nE("document","documentElement")});var ko=b((sM,Kp)=>{"use strict";var oE=St(),uE=Up(),jp=mo(),lE=vs(),cE=xo(),dE=hs(),pE=bs(),Qp=">",Gp="<",wo="prototype",Ao="script",Yp=pE("IE_PROTO"),Po=function(){},zp=function(a){return Gp+Ao+Qp+a+Gp+"/"+Ao+Qp},Wp=function(a){a.write(zp("")),a.close();var e=a.parentWindow.Object;return a=null,e},hE=function(){var a=dE("iframe"),e="java"+Ao+":",t;return a.style.display="none",cE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(zp("document.F=Object")),t.close(),t.F},Ts,Is=function(){try{Ts=new ActiveXObject("htmlfile")}catch(e){}Is=typeof document!="undefined"?document.domain&&Ts?Wp(Ts):hE():Wp(Ts);for(var a=jp.length;a--;)delete Is[wo][jp[a]];return Is()};lE[Yp]=!0;Kp.exports=Object.create||function(e,t){var r;return e!==null?(Po[wo]=oE(e),r=new Po,Po[wo]=null,r[Yp]=e):r=Is(),t===void 0?r:uE.f(r,t)}});var Wr=b((nM,Xp)=>{"use strict";var mE=Ur();Xp.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:mE(a,e,t),a}});var Mo=b((oM,eh)=>{"use strict";var fE=Ae(),bE=be(),gE=Ge(),vE=ko(),Jp=gs(),SE=Wr(),yE=ke(),TE=ut(),Lo=yE("iterator"),Zp=!1,kt,$o,Ro;[].keys&&(Ro=[].keys(),"next"in Ro?($o=Jp(Jp(Ro)),$o!==Object.prototype&&(kt=$o)):Zp=!0);var IE=!gE(kt)||fE(function(){var a={};return kt[Lo].call(a)!==a});IE?kt={}:TE&&(kt=vE(kt));bE(kt[Lo])||SE(kt,Lo,function(){return this});eh.exports={IteratorPrototype:kt,BUGGY_SAFARI_ITERATORS:Zp}});var Es=b((uM,rh)=>{"use strict";var EE=ke(),xE=EE("toStringTag"),th={};th[xE]="z";rh.exports=String(th)==="[object z]"});var Di=b((lM,ih)=>{"use strict";var PE=Es(),wE=be(),xs=pr(),AE=ke(),kE=AE("toStringTag"),$E=Object,RE=xs(function(){return arguments}())==="Arguments",LE=function(a,e){try{return a[e]}catch(t){}};ih.exports=PE?xs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=LE(e=$E(a),kE))=="string"?t:RE?xs(e):(r=xs(e))==="Object"&&wE(e.callee)?"Arguments":r}});var sh=b((cM,ah)=>{"use strict";var ME=Es(),CE=Di();ah.exports=ME?{}.toString:function(){return"[object "+CE(this)+"]"}});var Vi=b((dM,oh)=>{"use strict";var DE=Es(),VE=fr().f,_E=Ur(),BE=lt(),OE=sh(),NE=ke(),nh=NE("toStringTag");oh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(BE(i,nh)||VE(i,nh,{configurable:!0,value:e}),r&&!DE&&_E(i,"toString",OE))}});var lh=b((pM,uh)=>{"use strict";var FE=Mo().IteratorPrototype,qE=ko(),UE=xi(),HE=Vi(),jE=br(),QE=function(){return this};uh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=qE(FE,{next:UE(+!r,t)}),HE(a,i,!1,!0),jE[i]=QE,a}});var dh=b((hM,ch)=>{"use strict";var GE=xe(),WE=vt();ch.exports=function(a,e,t){try{return GE(WE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var hh=b((mM,ph)=>{"use strict";var YE=Ge();ph.exports=function(a){return YE(a)||a===null}});var fh=b((fM,mh)=>{"use strict";var zE=hh(),KE=String,XE=TypeError;mh.exports=function(a){if(zE(a))return a;throw new XE("Can't set "+KE(a)+" as a prototype")}});var Co=b((bM,bh)=>{"use strict";var JE=dh(),ZE=Ge(),ex=Gt(),tx=fh();bh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=JE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return ex(i),tx(s),ZE(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Ah=b((gM,wh)=>{"use strict";var rx=Te(),ix=Qe(),Ps=ut(),xh=Eo(),ax=be(),sx=lh(),gh=gs(),vh=Co(),nx=Vi(),ox=Ur(),Do=Wr(),ux=ke(),Sh=br(),Ph=Mo(),lx=xh.PROPER,cx=xh.CONFIGURABLE,yh=Ph.IteratorPrototype,ws=Ph.BUGGY_SAFARI_ITERATORS,_i=ux("iterator"),Th="keys",Bi="values",Ih="entries",Eh=function(){return this};wh.exports=function(a,e,t,r,i,s,n){sx(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 Th:return function(){return new t(this,T)};case Bi:return function(){return new t(this,T)};case Ih:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[_i]||c["@@iterator"]||i&&c[i],h=!ws&&d||o(i),m=e==="Array"&&c.entries||d,f,g,S;if(m&&(f=gh(m.call(new a)),f!==Object.prototype&&f.next&&(!Ps&&gh(f)!==yh&&(vh?vh(f,yh):ax(f[_i])||Do(f,_i,Eh)),nx(f,u,!0,!0),Ps&&(Sh[u]=Eh))),lx&&i===Bi&&d&&d.name!==Bi&&(!Ps&&cx?ox(c,"name",Bi):(l=!0,h=function(){return ix(d,this)})),i)if(g={values:o(Bi),keys:s?h:o(Th),entries:o(Ih)},n)for(S in g)(ws||l||!(S in c))&&Do(c,S,g[S]);else rx({target:e,proto:!0,forced:ws||l},g);return(!Ps||n)&&c[_i]!==h&&Do(c,_i,h,{name:i}),Sh[e]=h,g}});var $h=b((vM,kh)=>{"use strict";kh.exports=function(a,e){return{value:a,done:e}}});var _o=b((SM,Dh)=>{"use strict";var dx=hr(),Vo=Mi(),Rh=br(),Mh=yo(),px=fr().f,hx=Ah(),As=$h(),mx=ut(),fx=je(),Ch="Array Iterator",bx=Mh.set,gx=Mh.getterFor(Ch);Dh.exports=hx(Array,"Array",function(a,e){bx(this,{type:Ch,target:dx(a),index:0,kind:e})},function(){var a=gx(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 Lh=Rh.Arguments=Rh.Array;Vo("keys");Vo("values");Vo("entries");if(!mx&&fx&&Lh.name!=="values")try{px(Lh,"name",{value:"values"})}catch(a){}});var _h=b((yM,Vh)=>{"use strict";var vx=ke(),Sx=br(),yx=vx("iterator"),Tx=Array.prototype;Vh.exports=function(a){return a!==void 0&&(Sx.Array===a||Tx[yx]===a)}});var Bo=b((TM,Oh)=>{"use strict";var Ix=Di(),Bh=Ai(),Ex=Br(),xx=br(),Px=ke(),wx=Px("iterator");Oh.exports=function(a){if(!Ex(a))return Bh(a,wx)||Bh(a,"@@iterator")||xx[Ix(a)]}});var Fh=b((IM,Nh)=>{"use strict";var Ax=Qe(),kx=vt(),$x=St(),Rx=wi(),Lx=Bo(),Mx=TypeError;Nh.exports=function(a,e){var t=arguments.length<2?Lx(a):e;if(kx(t))return $x(Ax(t,a));throw new Mx(Rx(a)+" is not iterable")}});var Hh=b((EM,Uh)=>{"use strict";var Cx=Qe(),qh=St(),Dx=Ai();Uh.exports=function(a,e,t){var r,i;qh(a);try{if(r=Dx(a,"return"),!r){if(e==="throw")throw t;return t}r=Cx(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return qh(r),t}});var $s=b((xM,Wh)=>{"use strict";var Vx=qr(),_x=Qe(),Bx=St(),Ox=wi(),Nx=_h(),Fx=Qr(),jh=Pi(),qx=Fh(),Ux=Bo(),Qh=Hh(),Hx=TypeError,ks=function(a,e){this.stopped=a,this.result=e},Gh=ks.prototype;Wh.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Vx(e,r),l,c,d,h,m,f,g,S=function(E){return l&&Qh(l,"normal",E),new ks(!0,E)},T=function(E){return i?(Bx(E),o?u(E[0],E[1],S):u(E[0],E[1])):o?u(E,S):u(E)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Ux(a),!c)throw new Hx(Ox(a)+" is not iterable");if(Nx(c)){for(d=0,h=Fx(a);h>d;d++)if(m=T(a[d]),m&&jh(Gh,m))return m;return new ks(!1)}l=qx(a,c)}for(f=s?a.next:l.next;!(g=_x(f,l)).done;){try{m=T(g.value)}catch(E){Qh(l,"throw",E)}if(typeof m=="object"&&m&&jh(Gh,m))return m}return new ks(!1)}});var zh=b((PM,Yh)=>{"use strict";var jx=je(),Qx=fr(),Gx=xi();Yh.exports=function(a,e,t){jx?Qx.f(a,e,Gx(0,t)):a[e]=t}});var Kh=b(()=>{"use strict";var Wx=Te(),Yx=$s(),zx=zh();Wx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Yx(e,function(r,i){zx(t,r,i)},{AS_ENTRIES:!0}),t}})});var Jh=b((kM,Xh)=>{"use strict";_o();Kh();var Kx=Or();Xh.exports=Kx.Object.fromEntries});var em=b(($M,Zh)=>{"use strict";Zh.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 rm=b(()=>{"use strict";_o();var Xx=em(),Jx=ve(),Zx=Vi(),tm=br();for(Rs in Xx)Zx(Jx[Rs],Rs),tm[Rs]=tm.Array;var Rs});var am=b((MM,im)=>{"use strict";var eP=Jh();rm();im.exports=eP});var Oo=b((CM,sm)=>{"use strict";var tP=am();sm.exports=tP});var nm=b(()=>{"use strict"});var No=b((_M,om)=>{"use strict";var Oi=ve(),rP=mr(),iP=pr(),Ls=function(a){return rP.slice(0,a.length)===a};om.exports=function(){return Ls("Bun/")?"BUN":Ls("Cloudflare-Workers")?"CLOUDFLARE":Ls("Deno/")?"DENO":Ls("Node.js/")?"NODE":Oi.Bun&&typeof Bun.version=="string"?"BUN":Oi.Deno&&typeof Deno.version=="object"?"DENO":iP(Oi.process)==="process"?"NODE":Oi.window&&Oi.document?"BROWSER":"REST"}()});var Ms=b((BM,um)=>{"use strict";var aP=No();um.exports=aP==="NODE"});var cm=b((OM,lm)=>{"use strict";var sP=fr();lm.exports=function(a,e,t){return sP.f(a,e,t)}});var hm=b((NM,pm)=>{"use strict";var nP=At(),oP=cm(),uP=ke(),lP=je(),dm=uP("species");pm.exports=function(a){var e=nP(a);lP&&e&&!e[dm]&&oP(e,dm,{configurable:!0,get:function(){return this}})}});var fm=b((FM,mm)=>{"use strict";var cP=Pi(),dP=TypeError;mm.exports=function(a,e){if(cP(e,a))return a;throw new dP("Incorrect invocation")}});var qo=b((qM,bm)=>{"use strict";var pP=xe(),hP=be(),Fo=ki(),mP=pP(Function.toString);hP(Fo.inspectSource)||(Fo.inspectSource=function(a){return mP(a)});bm.exports=Fo.inspectSource});var Ho=b((UM,Tm)=>{"use strict";var fP=xe(),bP=Ae(),gm=be(),gP=Di(),vP=At(),SP=qo(),vm=function(){},Sm=vP("Reflect","construct"),Uo=/^\s*(?:class|function)\b/,yP=fP(Uo.exec),TP=!Uo.test(vm),Ni=function(e){if(!gm(e))return!1;try{return Sm(vm,[],e),!0}catch(t){return!1}},ym=function(e){if(!gm(e))return!1;switch(gP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return TP||!!yP(Uo,SP(e))}catch(t){return!0}};ym.sham=!0;Tm.exports=!Sm||bP(function(){var a;return Ni(Ni.call)||!Ni(Object)||!Ni(function(){a=!0})||a})?ym:Ni});var Em=b((HM,Im)=>{"use strict";var IP=Ho(),EP=wi(),xP=TypeError;Im.exports=function(a){if(IP(a))return a;throw new xP(EP(a)+" is not a constructor")}});var jo=b((jM,Pm)=>{"use strict";var xm=St(),PP=Em(),wP=Br(),AP=ke(),kP=AP("species");Pm.exports=function(a,e){var t=xm(a).constructor,r;return t===void 0||wP(r=xm(t)[kP])?e:PP(r)}});var Am=b((QM,wm)=>{"use strict";var $P=xe();wm.exports=$P([].slice)});var $m=b((GM,km)=>{"use strict";var RP=TypeError;km.exports=function(a,e){if(a<e)throw new RP("Not enough arguments");return a}});var Qo=b((WM,Rm)=>{"use strict";var LP=mr();Rm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(LP)});var eu=b((YM,Nm)=>{"use strict";var We=ve(),MP=Vn(),CP=qr(),Lm=be(),DP=lt(),Om=Ae(),Mm=xo(),VP=Am(),Cm=hs(),_P=$m(),BP=Qo(),OP=Ms(),Xo=We.setImmediate,Jo=We.clearImmediate,NP=We.process,Go=We.Dispatch,FP=We.Function,Dm=We.MessageChannel,qP=We.String,Wo=0,Fi={},Vm="onreadystatechange",qi,vr,Yo,zo;Om(function(){qi=We.location});var Zo=function(a){if(DP(Fi,a)){var e=Fi[a];delete Fi[a],e()}},Ko=function(a){return function(){Zo(a)}},_m=function(a){Zo(a.data)},Bm=function(a){We.postMessage(qP(a),qi.protocol+"//"+qi.host)};(!Xo||!Jo)&&(Xo=function(e){_P(arguments.length,1);var t=Lm(e)?e:FP(e),r=VP(arguments,1);return Fi[++Wo]=function(){MP(t,void 0,r)},vr(Wo),Wo},Jo=function(e){delete Fi[e]},OP?vr=function(a){NP.nextTick(Ko(a))}:Go&&Go.now?vr=function(a){Go.now(Ko(a))}:Dm&&!BP?(Yo=new Dm,zo=Yo.port2,Yo.port1.onmessage=_m,vr=CP(zo.postMessage,zo)):We.addEventListener&&Lm(We.postMessage)&&!We.importScripts&&qi&&qi.protocol!=="file:"&&!Om(Bm)?(vr=Bm,We.addEventListener("message",_m,!1)):Vm in Cm("script")?vr=function(a){Mm.appendChild(Cm("script"))[Vm]=function(){Mm.removeChild(this),Zo(a)}}:vr=function(a){setTimeout(Ko(a),0)});Nm.exports={set:Xo,clear:Jo}});var Um=b((zM,qm)=>{"use strict";var Fm=ve(),UP=je(),HP=Object.getOwnPropertyDescriptor;qm.exports=function(a){if(!UP)return Fm[a];var e=HP(Fm,a);return e&&e.value}});var tu=b((KM,jm)=>{"use strict";var Hm=function(){this.head=null,this.tail=null};Hm.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}}};jm.exports=Hm});var Gm=b((XM,Qm)=>{"use strict";var jP=mr();Qm.exports=/ipad|iphone|ipod/i.test(jP)&&typeof Pebble!="undefined"});var Ym=b((JM,Wm)=>{"use strict";var QP=mr();Wm.exports=/web0s(?!.*chrome)/i.test(QP)});var tf=b((ZM,ef)=>{"use strict";var zr=ve(),GP=Um(),zm=qr(),ru=eu().set,WP=tu(),YP=Qo(),zP=Gm(),KP=Ym(),iu=Ms(),Km=zr.MutationObserver||zr.WebKitMutationObserver,Xm=zr.document,Jm=zr.process,Cs=zr.Promise,nu=GP("queueMicrotask"),Yr,au,su,Ds,Zm;nu||(Ui=new WP,Hi=function(){var a,e;for(iu&&(a=Jm.domain)&&a.exit();e=Ui.get();)try{e()}catch(t){throw Ui.head&&Yr(),t}a&&a.enter()},!YP&&!iu&&!KP&&Km&&Xm?(au=!0,su=Xm.createTextNode(""),new Km(Hi).observe(su,{characterData:!0}),Yr=function(){su.data=au=!au}):!zP&&Cs&&Cs.resolve?(Ds=Cs.resolve(void 0),Ds.constructor=Cs,Zm=zm(Ds.then,Ds),Yr=function(){Zm(Hi)}):iu?Yr=function(){Jm.nextTick(Hi)}:(ru=zm(ru,zr),Yr=function(){ru(Hi)}),nu=function(a){Ui.head||Yr(),Ui.add(a)});var Ui,Hi;ef.exports=nu});var af=b((eC,rf)=>{"use strict";rf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Vs=b((tC,sf)=>{"use strict";sf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Sr=b((rC,nf)=>{"use strict";var XP=ve();nf.exports=XP.Promise});var Kr=b((iC,cf)=>{"use strict";var JP=ve(),ji=Sr(),ZP=be(),ew=io(),tw=qo(),rw=ke(),of=No(),iw=ut(),ou=jn(),uf=ji&&ji.prototype,aw=rw("species"),uu=!1,lf=ZP(JP.PromiseRejectionEvent),sw=ew("Promise",function(){var a=tw(ji),e=a!==String(ji);if(!e&&ou===66||iw&&!(uf.catch&&uf.finally))return!0;if(!ou||ou<51||!/native code/.test(a)){var t=new ji(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[aw]=r,uu=t.then(function(){})instanceof r,!uu)return!0}return!e&&(of==="BROWSER"||of==="DENO")&&!lf});cf.exports={CONSTRUCTOR:sw,REJECTION_EVENT:lf,SUBCLASSING:uu}});var Xr=b((aC,pf)=>{"use strict";var df=vt(),nw=TypeError,ow=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new nw("Bad Promise constructor");e=r,t=i}),this.resolve=df(e),this.reject=df(t)};pf.exports.f=function(a){return new ow(a)}});var Lf=b(()=>{"use strict";var uw=Te(),lw=ut(),Ns=Ms(),Yt=ve(),ti=Qe(),hf=Wr(),mf=Co(),cw=Vi(),dw=hm(),pw=vt(),Os=be(),hw=Ge(),mw=fm(),fw=jo(),Sf=eu().set,hu=tf(),bw=af(),gw=Vs(),vw=tu(),yf=yo(),Fs=Sr(),mu=Kr(),Tf=Xr(),qs="Promise",If=mu.CONSTRUCTOR,Sw=mu.REJECTION_EVENT,yw=mu.SUBCLASSING,lu=yf.getterFor(qs),Tw=yf.set,Jr=Fs&&Fs.prototype,yr=Fs,_s=Jr,Ef=Yt.TypeError,cu=Yt.document,fu=Yt.process,du=Tf.f,Iw=du,Ew=!!(cu&&cu.createEvent&&Yt.dispatchEvent),xf="unhandledrejection",xw="rejectionhandled",ff=0,Pf=1,Pw=2,bu=1,wf=2,Bs,bf,ww,gf,Af=function(a){var e;return hw(a)&&Os(e=a.then)?e:!1},kf=function(a,e){var t=e.value,r=e.state===Pf,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===wf&&kw(e),e.rejection=bu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Ef("Promise-chain cycle")):(l=Af(u))?ti(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();)kf(r,a);a.notified=!1,e&&!a.rejection&&Aw(a)}))},Rf=function(a,e,t){var r,i;Ew?(r=cu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Yt.dispatchEvent(r)):r={promise:e,reason:t},!Sw&&(i=Yt["on"+a])?i(r):a===xf&&bw("Unhandled promise rejection",t)},Aw=function(a){ti(Sf,Yt,function(){var e=a.facade,t=a.value,r=vf(a),i;if(r&&(i=gw(function(){Ns?fu.emit("unhandledRejection",t,e):Rf(xf,e,t)}),a.rejection=Ns||vf(a)?wf:bu,i.error))throw i.value})},vf=function(a){return a.rejection!==bu&&!a.parent},kw=function(a){ti(Sf,Yt,function(){var e=a.facade;Ns?fu.emit("rejectionHandled",e):Rf(xw,e,a.value)})},Zr=function(a,e,t){return function(r){a(e,r,t)}},ei=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Pw,$f(a,!0))},pu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Ef("Promise can't be resolved itself");var r=Af(e);r?hu(function(){var i={done:!1};try{ti(r,e,Zr(pu,i,a),Zr(ei,i,a))}catch(s){ei(i,s,a)}}):(a.value=e,a.state=Pf,$f(a,!1))}catch(i){ei({done:!1},i,a)}}};if(If&&(yr=function(e){mw(this,_s),pw(e),ti(Bs,this);var t=lu(this);try{e(Zr(pu,t),Zr(ei,t))}catch(r){ei(t,r)}},_s=yr.prototype,Bs=function(e){Tw(this,{type:qs,done:!1,notified:!1,parent:!1,reactions:new vw,rejection:!1,state:ff,value:void 0})},Bs.prototype=hf(_s,"then",function(e,t){var r=lu(this),i=du(fw(this,yr));return r.parent=!0,i.ok=Os(e)?e:!0,i.fail=Os(t)&&t,i.domain=Ns?fu.domain:void 0,r.state===ff?r.reactions.add(i):hu(function(){kf(i,r)}),i.promise}),bf=function(){var a=new Bs,e=lu(a);this.promise=a,this.resolve=Zr(pu,e),this.reject=Zr(ei,e)},Tf.f=du=function(a){return a===yr||a===ww?new bf(a):Iw(a)},!lw&&Os(Fs)&&Jr!==Object.prototype)){gf=Jr.then,yw||hf(Jr,"then",function(e,t){var r=this;return new yr(function(i,s){ti(gf,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Jr.constructor}catch(a){}mf&&mf(Jr,_s)}uw({global:!0,constructor:!0,wrap:!0,forced:If},{Promise:yr});cw(yr,qs,!1,!0);dw(qs)});var _f=b((oC,Vf)=>{"use strict";var $w=ke(),Cf=$w("iterator"),Df=!1;try{Mf=0,gu={next:function(){return{done:!!Mf++}},return:function(){Df=!0}},gu[Cf]=function(){return this},Array.from(gu,function(){throw 2})}catch(a){}var Mf,gu;Vf.exports=function(a,e){try{if(!e&&!Df)return!1}catch(i){return!1}var t=!1;try{var r={};r[Cf]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var vu=b((uC,Bf)=>{"use strict";var Rw=Sr(),Lw=_f(),Mw=Kr().CONSTRUCTOR;Bf.exports=Mw||!Lw(function(a){Rw.all(a).then(void 0,function(){})})});var Of=b(()=>{"use strict";var Cw=Te(),Dw=Qe(),Vw=vt(),_w=Xr(),Bw=Vs(),Ow=$s(),Nw=vu();Cw({target:"Promise",stat:!0,forced:Nw},{all:function(e){var t=this,r=_w.f(t),i=r.resolve,s=r.reject,n=Bw(function(){var o=Vw(t.resolve),u=[],l=0,c=1;Ow(e,function(d){var h=l++,m=!1;c++,Dw(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 Ff=b(()=>{"use strict";var Fw=Te(),qw=ut(),Uw=Kr().CONSTRUCTOR,yu=Sr(),Hw=At(),jw=be(),Qw=Wr(),Nf=yu&&yu.prototype;Fw({target:"Promise",proto:!0,forced:Uw,real:!0},{catch:function(a){return this.then(void 0,a)}});!qw&&jw(yu)&&(Su=Hw("Promise").prototype.catch,Nf.catch!==Su&&Qw(Nf,"catch",Su,{unsafe:!0}));var Su});var qf=b(()=>{"use strict";var Gw=Te(),Ww=Qe(),Yw=vt(),zw=Xr(),Kw=Vs(),Xw=$s(),Jw=vu();Gw({target:"Promise",stat:!0,forced:Jw},{race:function(e){var t=this,r=zw.f(t),i=r.reject,s=Kw(function(){var n=Yw(t.resolve);Xw(e,function(o){Ww(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Uf=b(()=>{"use strict";var Zw=Te(),eA=Xr(),tA=Kr().CONSTRUCTOR;Zw({target:"Promise",stat:!0,forced:tA},{reject:function(e){var t=eA.f(this),r=t.reject;return r(e),t.promise}})});var Tu=b((gC,Hf)=>{"use strict";var rA=St(),iA=Ge(),aA=Xr();Hf.exports=function(a,e){if(rA(a),iA(e)&&e.constructor===a)return e;var t=aA.f(a),r=t.resolve;return r(e),t.promise}});var Gf=b(()=>{"use strict";var sA=Te(),nA=At(),jf=ut(),oA=Sr(),Qf=Kr().CONSTRUCTOR,uA=Tu(),lA=nA("Promise"),cA=jf&&!Qf;sA({target:"Promise",stat:!0,forced:jf||Qf},{resolve:function(e){return uA(cA&&this===lA?oA:this,e)}})});var Wf=b(()=>{"use strict";Lf();Of();Ff();qf();Uf();Gf()});var Xf=b(()=>{"use strict";var dA=Te(),pA=ut(),Us=Sr(),hA=Ae(),zf=At(),Kf=be(),mA=jo(),Yf=Tu(),fA=Wr(),Eu=Us&&Us.prototype,bA=!!Us&&hA(function(){Eu.finally.call({then:function(){}},function(){})});dA({target:"Promise",proto:!0,real:!0,forced:bA},{finally:function(a){var e=mA(this,zf("Promise")),t=Kf(a);return this.then(t?function(r){return Yf(e,a()).then(function(){return r})}:a,t?function(r){return Yf(e,a()).then(function(){throw r})}:a)}});!pA&&Kf(Us)&&(Iu=zf("Promise").prototype.finally,Eu.finally!==Iu&&fA(Eu,"finally",Iu,{unsafe:!0}));var Iu});var Zf=b((xC,Jf)=>{"use strict";nm();Wf();Xf();var gA=Wt();Jf.exports=gA("Promise","finally")});var tb=b((PC,eb)=>{"use strict";var vA=Zf();eb.exports=vA});var Hs=b((wC,rb)=>{"use strict";var SA=tb();rb.exports=SA});var lb=b(()=>{"use strict";var xA=Te(),PA=bo().values;xA({target:"Object",stat:!0},{values:function(e){return PA(e)}})});var db=b((iD,cb)=>{"use strict";lb();var wA=Or();cb.exports=wA.Object.values});var hb=b((aD,pb)=>{"use strict";var AA=db();pb.exports=AA});var ri=b((sD,mb)=>{"use strict";var kA=hb();mb.exports=kA});var wb=b(()=>{"use strict";var OA=Te(),NA=Nr(),FA=Qr(),qA=Li(),UA=Mi();OA({target:"Array",proto:!0},{at:function(e){var t=NA(this),r=FA(t),i=qA(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});UA("at")});var kb=b((p0,Ab)=>{"use strict";wb();var HA=Wt();Ab.exports=HA("Array","at")});var Rb=b((h0,$b)=>{"use strict";var jA=kb();$b.exports=jA});var Jt=b((m0,Lb)=>{"use strict";var QA=Rb();Lb.exports=QA});var Hu=b((QV,Zb)=>{"use strict";var ik=pr();Zb.exports=Array.isArray||function(e){return ik(e)==="Array"}});var tg=b((GV,eg)=>{"use strict";var ak=TypeError,sk=9007199254740991;eg.exports=function(a){if(a>sk)throw ak("Maximum allowed index exceeded");return a}});var ag=b((WV,ig)=>{"use strict";var nk=Hu(),ok=Qr(),uk=tg(),lk=qr(),rg=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?lk(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&nk(d)?(h=ok(d),u=rg(a,e,d,h,u,s-1)-1):(uk(u+1),a[u]=d),u++),l++;return u};ig.exports=rg});var ug=b((YV,og)=>{"use strict";var sg=Hu(),ck=Ho(),dk=Ge(),pk=ke(),hk=pk("species"),ng=Array;og.exports=function(a){var e;return sg(a)&&(e=a.constructor,ck(e)&&(e===ng||sg(e.prototype))?e=void 0:dk(e)&&(e=e[hk],e===null&&(e=void 0))),e===void 0?ng:e}});var cg=b((zV,lg)=>{"use strict";var mk=ug();lg.exports=function(a,e){return new(mk(a))(e===0?0:e)}});var dg=b(()=>{"use strict";var fk=Te(),bk=ag(),gk=vt(),vk=Nr(),Sk=Qr(),yk=cg();fk({target:"Array",proto:!0},{flatMap:function(e){var t=vk(this),r=Sk(t),i;return gk(e),i=yk(t,0),i.length=bk(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var pg=b(()=>{"use strict";var Tk=Mi();Tk("flatMap")});var mg=b((e_,hg)=>{"use strict";dg();pg();var Ik=Wt();hg.exports=Ik("Array","flatMap")});var bg=b((t_,fg)=>{"use strict";var Ek=mg();fg.exports=Ek});var ju=b((r_,gg)=>{"use strict";var xk=bg();gg.exports=xk});var ra=b((i_,vg)=>{"use strict";var Pk=Di(),wk=String;vg.exports=function(a){if(Pk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return wk(a)}});var Qu=b((a_,Sg)=>{"use strict";Sg.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 Ig=b((s_,Tg)=>{"use strict";var Ak=xe(),kk=Gt(),$k=ra(),Wu=Qu(),yg=Ak("".replace),Rk=RegExp("^["+Wu+"]+"),Lk=RegExp("(^|[^"+Wu+"])["+Wu+"]+$"),Gu=function(a){return function(e){var t=$k(kk(e));return a&1&&(t=yg(t,Rk,"")),a&2&&(t=yg(t,Lk,"$1")),t}};Tg.exports={start:Gu(1),end:Gu(2),trim:Gu(3)}});var wg=b((n_,Pg)=>{"use strict";var Mk=Eo().PROPER,Ck=Ae(),Eg=Qu(),xg="\u200B\x85\u180E";Pg.exports=function(a){return Ck(function(){return!!Eg[a]()||xg[a]()!==xg||Mk&&Eg[a].name!==a})}});var Yu=b((o_,Ag)=>{"use strict";var Dk=Ig().start,Vk=wg();Ag.exports=Vk("trimStart")?function(){return Dk(this)}:"".trimStart});var $g=b(()=>{"use strict";var _k=Te(),kg=Yu();_k({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==kg},{trimLeft:kg})});var Lg=b(()=>{"use strict";$g();var Bk=Te(),Rg=Yu();Bk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Rg},{trimStart:Rg})});var Cg=b((p_,Mg)=>{"use strict";Lg();var Ok=Wt();Mg.exports=Ok("String","trimLeft")});var Vg=b((h_,Dg)=>{"use strict";var Nk=Cg();Dg.exports=Nk});var Bg=b((m_,_g)=>{"use strict";var Fk=Vg();_g.exports=Fk});var Xg=b(()=>{"use strict"});var Jg=b(()=>{"use strict"});var ev=b((WO,Zg)=>{"use strict";var n$=Ge(),o$=pr(),u$=ke(),l$=u$("match");Zg.exports=function(a){var e;return n$(a)&&((e=a[l$])!==void 0?!!e:o$(a)==="RegExp")}});var rv=b((YO,tv)=>{"use strict";var c$=St();tv.exports=function(){var a=c$(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 sv=b((zO,av)=>{"use strict";var d$=Qe(),p$=lt(),h$=Pi(),m$=rv(),iv=RegExp.prototype;av.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in iv)&&!p$(a,"flags")&&h$(iv,a)?d$(m$,a):e}});var ov=b((KO,nv)=>{"use strict";var tl=xe(),f$=Nr(),b$=Math.floor,Zu=tl("".charAt),g$=tl("".replace),el=tl("".slice),v$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,S$=/\$([$&'`]|\d{1,2})/g;nv.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=S$;return i!==void 0&&(i=f$(i),u=v$),g$(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=b$(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 cv=b(()=>{"use strict";var y$=Te(),T$=Qe(),il=xe(),uv=Gt(),I$=be(),E$=Br(),x$=ev(),ui=ra(),P$=Ai(),w$=sv(),A$=ov(),k$=ke(),$$=ut(),R$=k$("replace"),L$=TypeError,rl=il("".indexOf),M$=il("".replace),lv=il("".slice),C$=Math.max;y$({target:"String",proto:!0},{replaceAll:function(e,t){var r=uv(this),i,s,n,o,u,l,c,d,h,m,f=0,g="";if(!E$(e)){if(i=x$(e),i&&(s=ui(uv(w$(e))),!~rl(s,"g")))throw new L$("`.replaceAll` does not allow non-global regexes");if(n=P$(e,R$),n)return T$(n,e,r,t);if($$&&i)return M$(ui(r),e,t)}for(o=ui(r),u=ui(e),l=I$(t),l||(t=ui(t)),c=u.length,d=C$(1,c),h=rl(o,u);h!==-1;)m=l?ui(t(u,h,o)):A$(u,o,h,[],void 0,t),g+=lv(o,f,h)+m,f=h+c,h=h+d>o.length?-1:rl(o,u,h+d);return f<o.length&&(g+=lv(o,f)),g}})});var pv=b((ZO,dv)=>{"use strict";Xg();Jg();cv();var D$=Wt();dv.exports=D$("String","replaceAll")});var mv=b((eN,hv)=>{"use strict";var V$=pv();hv.exports=V$});var bv=b((tN,fv)=>{"use strict";var _$=mv();fv.exports=_$});var vv=b((rN,gv)=>{"use strict";var B$=Li(),O$=ra(),N$=Gt(),F$=RangeError;gv.exports=function(e){var t=O$(N$(this)),r="",i=B$(e);if(i<0||i===1/0)throw new F$("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var Ev=b((iN,Iv)=>{"use strict";var Tv=xe(),q$=lo(),Sv=ra(),U$=vv(),H$=Gt(),j$=Tv(U$),Q$=Tv("".slice),G$=Math.ceil,yv=function(a){return function(e,t,r){var i=Sv(H$(e)),s=q$(t),n=i.length,o=r===void 0?" ":Sv(r),u,l;return s<=n||o===""?i:(u=s-n,l=j$(o,G$(u/o.length)),l.length>u&&(l=Q$(l,0,u)),a?i+l:l+i)}};Iv.exports={start:yv(!1),end:yv(!0)}});var Pv=b((aN,xv)=>{"use strict";var W$=mr();xv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(W$)});var wv=b(()=>{"use strict";var Y$=Te(),z$=Ev().start,K$=Pv();Y$({target:"String",proto:!0,forced:K$},{padStart:function(e){return z$(this,e,arguments.length>1?arguments[1]:void 0)}})});var kv=b((oN,Av)=>{"use strict";wv();var X$=Wt();Av.exports=X$("String","padStart")});var Rv=b((uN,$v)=>{"use strict";var J$=kv();$v.exports=J$});var Mv=b((lN,Lv)=>{"use strict";var Z$=Rv();Lv.exports=Z$});var SR={};HS(SR,{ChromecastState:()=>yi,HttpConnectionType:()=>ls,Observable:()=>Pt.Observable,PlaybackState:()=>Be,Player:()=>Wa,PredefinedQualityLimits:()=>Ti,SDK_VERSION:()=>vR,Subject:()=>Pt.Subject,Subscription:()=>Pt.Subscription,Surface:()=>cs,VERSION:()=>Cn,ValueSubject:()=>Pt.ValueSubject,VideoFormat:()=>gt,VideoQuality:()=>Pt.VideoQuality,clientChecker:()=>ee,isMobile:()=>ii});module.exports=jS(SR);var Cn="2.0.129-dev.53dfa302.0";var Be=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Be||{}),gt=(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))(gt||{});var yi=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(yi||{}),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||{}),Ti=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(Ti||{});var kS=G(Xe(),1);var Q=require("@vkontakte/videoplayer-shared/es2015");var up=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 Q.ValueSubject(void 0);this.castState$=new Q.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new Q.Subject;this.realCastState$=new Q.ValueSubject("NOT_AVAILABLE");this.subscription=new Q.Subscription;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=(0,Q.isNonNullable)((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||up("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Q.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){(0,Q.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,Q.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,Q.isNullable)(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add((0,Q.fromEvent)(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return(0,Q.assertNever)(i.sessionState)}})).add((0,Q.merge)((0,Q.fromEvent)(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,Q.tap)(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),(0,Q.map)(i=>i.castState)),(0,Q.observableFrom)([r.getCastState()])).pipe((0,Q.filterChanged)(),(0,Q.map)(pI),(0,Q.tap)(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=(0,Q.isNonNullable)(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();(0,Q.assertNonNullable)(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;((0,Q.isNullable)(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?(0,Q.isNonNullable)(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Q.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},pI=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 Pl=G(Xe(),1),fS=G(Gr(),1),bS=G(Oo(),1);var nb=G(Hs(),1);var xu=require("@vkontakte/videoplayer-shared/es2015");var $e=(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 L=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};var yt=require("@vkontakte/videoplayer-shared/es2015"),Y=class{constructor(e){this.transitionStarted$=new yt.Subject;this.transitionEnded$=new yt.Subject;this.transitionUpdated$=new yt.Subject;this.forceChanged$=new yt.Subject;this.stateChangeStarted$=(0,yt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,yt.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,yt.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 ib=require("@vkontakte/videoplayer-shared/es2015"),ab=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,ib.assertNever)(a)}};var D=require("@vkontakte/videoplayer-shared/es2015");var yA=5,TA=5,IA=500,sb=7e3,Qi=class{constructor(e){this.subscription=new D.Subscription;this.loadMediaTimeoutSubscription=new D.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,D.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,D.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,D.assertNever)(e)}break}default:(0,D.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(ab(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 D.Subscription;this.subscription.add(e),this.subscription.add((0,D.merge)(this.videoState.stateChangeStarted$.pipe((0,D.map)(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe((0,D.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 D.Subject;e.add(i.pipe((0,D.debounce)(IA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,D.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)>yA)&&i.next(o),s=o})),e.add((0,D.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,D.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,D.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,D.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<TA&&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,D.assertNever)(n)}}),t((0,D.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t((0,D.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=(0,D.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,D.observableFrom)(["init"])).pipe((0,D.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"),L(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),L(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"),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 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,D.assertNonNullable)(c);let d=(0,D.getHighestQuality)(Object.keys(c));(0,D.assertNonNullable)(d);let h=c[d];(0,D.assertNonNullable)(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];(0,D.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,D.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,D.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,D.assertNonNullable)(c),r=$e(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:D.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,D.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,D.isNonNullable)(o)&&(n.metadata.title=o),(0,D.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,D.timeout)(sb).subscribe(()=>s(`timeout(${sb})`)))});(0,nb.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:D.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var qu=G(Xe(),1);var ku=require("@vkontakte/videoplayer-shared/es2015");var ob=require("@vkontakte/videoplayer-shared/es2015"),ub=a=>{try{a.pause(),a.playbackRate=0,(0,ob.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,EA=(a,e=20)=>{let t=0;return(0,Qs.fromEvent)(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Oe=(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(EA(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},Ne=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):ub(a)};var $u=G(ri(),1),V=require("@vkontakte/videoplayer-shared/es2015");var zt=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,zt.isNullable)(i),l=new zt.Subscription;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},Tt=(a,e,t)=>Gs(e,()=>a.loop,r=>{(0,zt.isNonNullable)(r)&&(a.loop=r)},{onError:t}),Fe=(a,e,t,r)=>Gs(e,()=>({muted:a.muted,volume:a.volume}),i=>{(0,zt.isNonNullable)(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Je=(a,e,t,r)=>Gs(e,()=>a.playbackRate,i=>{(0,zt.isNonNullable)(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Kt=Gs;var $A=a=>["__",a.language,a.label].join("|"),RA=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Ru=class a{constructor(e){this.available$=new V.Subject;this.current$=new V.ValueSubject(void 0);this.error$=new V.Subject;this.subscription=new V.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:V.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Kt(t.internalTextTracks,()=>(0,$u.default)(this.internalTracks),s=>{(0,V.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,V.isNonNullable)(s)&&(0,V.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,V.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Kt(t.externalTextTracks,()=>(0,$u.default)(this.externalTracks),s=>{(0,V.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,V.isNonNullable)(s)&&(0,V.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,V.map)(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Kt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Kt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,V.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,V.fromEvent)(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add((0,V.merge)((0,V.fromEvent)(e,"addtrack"),(0,V.fromEvent)(e,"removetrack"),(0,V.observableFrom)(["init"])).pipe((0,V.map)(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),(0,V.filterChanged)((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add((0,V.merge)((0,V.fromEvent)(e,"change"),(0,V.observableFrom)(["init"])).pipe((0,V.map)(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),(0,V.map)(r=>r&&this.htmlTextTrackToITextTrack(r).id),(0,V.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,V.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,V.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,V.isNonNullable)(t.align)&&(i.align=t.align),(0,V.isNonNullable)(t.position)&&(i.position=t.position),(0,V.isNonNullable)(t.size)&&(i.size=t.size),(0,V.isNonNullable)(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,V.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:$A(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,V.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,V.isNullable)(e)||!RA(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,V.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,V.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ze=Ru;var Tr=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 fb=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},Lu=a=>{let e=fb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},bb=a=>{let e=fb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var M=require("@vkontakte/videoplayer-shared/es2015");var LA=3,gb=(a,e,t=LA)=>{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 vb=G(Xe(),1);var ii=()=>{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,vb.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=ii()}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 dt=()=>window.ManagedMediaSource||window.MediaSource,Ks=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Sb=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},yb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var MA=document.createElement("video"),CA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',DA='video/mp4; codecs="hev1.1.6.L93.B0"',Tb='video/webm; codecs="vp09.00.10.08"',Ib='video/webm; codecs="av01.0.00M.08"',VA='audio/mp4; codecs="mp4a.40.2"',_A='audio/webm; codecs="opus"',Eb,BA=()=>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(F(R({},a),{video:F(R({},a.video),{contentType:Ib})})),window.navigator.mediaCapabilities.decodingInfo(F(R({},a),{video:F(R({},a.video),{contentType:Tb})}))]);Eb={DASH_WEBM_AV1:e,DASH_WEBM:t}});BA().catch(a=>{console.log(MA),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 Eb}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,S,T,E,x,w;this._video=document.createElement("video");try{this._protocols={mms:Ks(),mse:Sb(),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 P=!!((c=(l=dt())==null?void 0:l.isTypeSupported)!=null&&c.call(l,CA)),A=!!((h=(d=dt())==null?void 0:d.isTypeSupported)!=null&&h.call(d,DA)),U=!!((f=(m=dt())==null?void 0:m.isTypeSupported)!=null&&f.call(m,VA));this._codecs={h264:P,h265:A,vp9:!!((S=(g=dt())==null?void 0:g.isTypeSupported)!=null&&S.call(g,Tb)),av1:!!((E=(T=dt())==null?void 0:T.isTypeSupported)!=null&&E.call(T,Ib)),aac:U,opus:!!((w=(x=dt())==null?void 0:x.isTypeSupported)!=null&&w.call(x,_A)),mpeg:(P||A)&&U},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 xb="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,xb))},this._codecs={mp3:!!((i=(r=dt())==null?void 0:r.isTypeSupported)!=null&&i.call(r,xb))}}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 Pb=require("@vkontakte/videoplayer-shared/es2015");var Mu=class{constructor(){this.isInited$=new Pb.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)})}},ee=new Mu;var qe=a=>{let e=A=>(0,M.fromEvent)(a,A).pipe((0,M.mapTo)(void 0)),r=(0,M.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(A=>(0,M.fromEvent)(a,A))).pipe((0,M.map)(A=>A.type==="ended"?a.readyState<2:a.readyState<3),(0,M.filterChanged)()),i=(0,M.merge)((0,M.fromEvent)(a,"progress"),(0,M.fromEvent)(a,"timeupdate")).pipe((0,M.map)(()=>gb(a.buffered,a.currentTime))),s=ee.browser.isSafari?(0,M.combine)({play:e("play").pipe((0,M.once)()),playing:e("playing")}).pipe((0,M.mapTo)(void 0)):e("playing"),n=(0,M.fromEvent)(a,"volumechange").pipe((0,M.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,M.fromEvent)(a,"ratechange").pipe((0,M.map)(()=>a.playbackRate)),u=(0,M.fromEvent)(a,"error").pipe((0,M.filter)(()=>!!(a.error||a.played.length)),(0,M.map)(()=>{var U;let A=a.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:M.ErrorCategory.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:(U=a.error)!=null?U:void 0}})),l=(0,M.fromEvent)(a,"timeupdate").pipe((0,M.map)(()=>a.currentTime)),c=new M.Subject,d=.3,h;l.subscribe(A=>{a.loop&&(0,M.isNonNullable)(h)&&(0,M.isNonNullable)(A)&&h>=a.duration-d&&A<=d&&c.next(h),h=A});let m=e("pause").pipe((0,M.filter)(()=>!a.error&&h!==a.duration)),f=(0,M.fromEvent)(a,"enterpictureinpicture"),g=(0,M.fromEvent)(a,"leavepictureinpicture"),S=new M.ValueSubject(bb(a));f.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));let T=new M.ValueSubject(Lu(a));(0,M.fromEvent)(a,"fullscreenchange").pipe((0,M.map)(()=>Lu(a))).subscribe(T);let x=.1,P=(0,M.merge)((0,M.fromEvent)(a,"timeupdate").pipe((0,M.filter)(A=>a.duration-a.currentTime<x&&!a.loop)),(0,M.fromEvent)(a,"ended")).pipe((0,M.debounce)(200),(0,M.mapTo)(void 0));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:P,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,M.fromEvent)(a,"durationchange").pipe((0,M.map)(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:T,enterPip$:f,leavePip$:g}};var Rt=require("@vkontakte/videoplayer-shared/es2015"),Xt=a=>{switch(a){case"mobile":return Rt.VideoQuality.Q_144P;case"lowest":return Rt.VideoQuality.Q_240P;case"low":return Rt.VideoQuality.Q_360P;case"sd":case"medium":return Rt.VideoQuality.Q_480P;case"hd":case"high":return Rt.VideoQuality.Q_720P;case"fullhd":case"full":return Rt.VideoQuality.Q_1080P;case"quadhd":case"quad":return Rt.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Rt.VideoQuality.Q_2160P}};var Zt=G(Jt(),1),Bb=G(Xe(),1),Zs=G(Gr(),1),O=require("@vkontakte/videoplayer-shared/es2015");var Cu=!1,Lt={},Mb=a=>{Cu=a},Cb=()=>{Lt={}},Db=a=>{a(Lt)},Gi=(a,e)=>{var t;Cu&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[a]=e)},De=class{constructor(e){this.name=e}next(e){var r,i;if(!Cu)return;Lt.series=(r=Lt.series)!=null?r:{};let t=(i=Lt.series[this.name])!=null?i:[];t.push([Date.now(),e]),Lt.series[this.name]=t}};var Ie=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 Wi({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 Vb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Wi({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 GA=new De("best_bitrate"),Ob=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var _u=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Yi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,O.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Nb='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,O.isNonNullable)(l.bitrate)&&(0,O.isNonNullable)(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Zt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Zt.default)(s,-1);return o&&(0,Bb.default)(n,o)?o:n.length?(0,Zt.default)(n,-1):(0,Zt.default)(s,0)},_b=a=>"quality"in a,Fb=(a,e,t,r)=>{var n;let i=(0,O.isNonNullable)((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&(0,O.isNonNullable)(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&(0,O.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=_b(o)?"video":"audio",l=_b(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return r==null||r.recordSwitch(t),t},
|
|
9
|
+
`}),o}return r==null||r.recordSwitch(t),t},WA=(a,e)=>Math.log(e)/Math.log(a),YA=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&ee.display.pixelRatio){let i=ee.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=WA(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return Vu({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},er=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:m,abrLogger:f})=>{var se,K,ue,C,H;(0,O.assertNotEmptyArray)(a,Nb);let{containerSizeFactor:g,containerSizeLimit:S}=YA({container:e,tuning:r,limits:i}),T=r.considerPlaybackRate&&(0,O.isNonNullable)(o)?o:1,E=a.filter($=>!(0,O.isInvariantQuality)($.quality)).sort(($,Z)=>(0,O.isHigher)($.quality,Z.quality)?-1:1),x=(se=(0,Zt.default)(E,-1))==null?void 0:se.quality,w=(K=(0,Zt.default)(E,0))==null?void 0:K.quality,P=Wi({limits:i,lowestAvailableQuality:x,highestAvailableQuality:w}),A=T*Ob(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),U={},J=E.filter($=>{let Z=!0;if(S)if($.size)Z=$.size.width<=S.width&&$.size.height<=S.height;else{let it=S&&(0,O.videoSizeToQuality)(S);Z=it?(0,O.isLowerOrEqual)($.quality,it):!0}if(!Z)return U[$.quality]="FitsContainer",!1;let W=m||t,rt=(0,O.isNonNullable)(W)&&isFinite(W)&&(0,O.isNonNullable)($.bitrate)?W-s>=$.bitrate*A:!0,Ot=Vu({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===$.quality;if(!rt&&!Ot)return U[$.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&(0,O.isNonNullable)(r.minBufferToSwitchUp)&&u&&!(0,O.isInvariantQuality)(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&(0,O.isHigher)($.quality,u.quality))return U[$.quality]="Buffer",!1;if(!!d&&(0,O.isHigherOrEqual)($.quality,d)&&!Ot)return U[$.quality]="DroppedFramesLimit",!1;if(!!h&&(0,O.isHigherOrEqual)($.quality,h)&&!Ot)return U[$.quality]="StallsLimit",!1;let Me=P||((0,O.isNullable)(i==null?void 0:i.max)||(0,O.isLowerOrEqual)($.quality,i.max))&&((0,O.isNullable)(i==null?void 0:i.min)||(0,O.isHigherOrEqual)($.quality,i.min)),_e=(0,O.isNonNullable)(c)&&!c?(0,O.isLowerOrEqual)($.quality,r.backgroundVideoQualityLimit):!0;return!Me||!_e?(U[$.quality]="FitsQualityLimits",!1):!0})[0];J&&J.bitrate&&GA.next(J.bitrate);let te=(ue=J!=null?J:(0,Zt.default)(E,-1))!=null?ue:a[0],re=l==null?void 0:l.last,_=Fb(r,f,te,l);return(0,O.isNonNullable)(l)&&_.quality!==(re==null?void 0:re.quality)&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(
|
|
12
|
+
${a.map($=>{var Z,W;return`{ id: ${$.id}, quality: ${$.quality}, bitrate: ${$.bitrate}, size: ${(Z=$.size)==null?void 0:Z.width}:${(W=$.size)==null?void 0:W.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Zs.default)(r!=null?r:{}).map(([$,Z])=>`${$}: ${Z}`).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 ${(H=S==null?void 0:S.height)!=null?H:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
|
-
stallsPredictedThroughput: ${
|
|
23
|
+
stallsPredictedThroughput: ${m},
|
|
24
24
|
reserve: ${s},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${T},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${A},
|
|
29
29
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
30
30
|
droppedVideoMaxQualityLimit: ${d},
|
|
31
|
-
stallsVideoMaxQualityLimit: ${
|
|
32
|
-
limitsAreInvalid: ${
|
|
31
|
+
stallsVideoMaxQualityLimit: ${h},
|
|
32
|
+
limitsAreInvalid: ${P},
|
|
33
33
|
maxQualityLimit: ${i==null?void 0:i.max},
|
|
34
34
|
minQualityLimit: ${i==null?void 0:i.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,Zs.default)(U).map(([$,Z])=>`${$}: ${Z}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${J==null?void 0:J.quality}
|
|
41
|
+
[selected video track] ${_==null?void 0:_.quality}
|
|
42
|
+
`}),_},qb=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{(0,O.assertNotEmptyArray)(t,Nb);let c=i.considerPlaybackRate&&(0,O.isNonNullable)(s)?s:1,d=[...t].sort(_u(-1)),h=a.bitrate;(0,O.assertNonNullable)(h);let m=c*Ob(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,g=en(a,e,t,i.minVideoAudioRatio),S=l||r;(0,O.isNonNullable)(S)&&isFinite(S)&&(f=d.find(x=>(0,O.isNonNullable)(x.bitrate)&&(0,O.isNonNullable)(g==null?void 0:g.bitrate)?S-h>=x.bitrate*m&&x.bitrate>=g.bitrate:!1)),f||(f=g);let T=o==null?void 0:o.last,E=f&&Fb(i,u,f,o);return(0,O.isNonNullable)(o)&&(E==null?void 0:E.bitrate)!==(T==null?void 0:T.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)(i!=null?i:{}).map(([x,w])=>`${x}: ${w}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
53
|
estimatedThroughput: ${r},
|
|
54
54
|
stallsPredictedThroughput: ${l},
|
|
55
|
-
reserve: ${
|
|
55
|
+
reserve: ${h},
|
|
56
56
|
playbackRate: ${s},
|
|
57
57
|
playbackRateFactor: ${c},
|
|
58
58
|
forwardBufferHealth: ${n},
|
|
59
|
-
bitrateFactor: ${
|
|
59
|
+
bitrateFactor: ${m},
|
|
60
60
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
61
61
|
|
|
62
62
|
[selected audio track] ${f==null?void 0:f.id}
|
|
63
|
-
`}),f&&Ob(i,u,f,o)};var Ee=a=>new URL(a).hostname;var V=require("@vkontakte/videoplayer-shared/es2015");var jb=W(tr(),1);var Fb=W(dt(),1);var Nb=a=>{if(a instanceof DOMException&&(0,Fb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},qe=(a,e)=>L(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Nb(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Nb(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});var Ke=require("@vkontakte/videoplayer-shared/es2015");var qb=W(si(),1),It=require("@vkontakte/videoplayer-shared/es2015");function xe(){return(0,It.now)()}function Uu(a){return xe()-a}function Hu(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 Ub(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ni(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,g=2e3,S=()=>{if(u)return;(0,It.assertNonNullable)(c);let O=Uu(c),ie;if(O<g){ie=g-O,setTimeout(S,ie);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new i,F()},I=O=>(s=O,re),E=O=>(d=O,re),P=()=>(h="json",re),w=()=>{if(!u){if(--l>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},A=O=>(p=O,re),F=()=>{c=xe(),n=new i,n.open("get",a);let O=0,ie,X=0,ne=()=>((0,It.assertNonNullable)(c),Math.max(c,Math.max(ie||0,X||0)));if(s&&n.addEventListener("progress",R=>{let x=xe();s.updateChunk&&R.loaded>O&&(s.updateChunk(ne(),R.loaded-O),O=R.loaded,ie=x)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;(0,It.assertNonNullable)(n);let R=n.status;if(R>=200&&R<300){let{response:x,responseType:G}=n,ae=x==null?void 0:x.byteLength;if(typeof ae=="number"&&s){let J=ae-O;J&&s.updateChunk&&s.updateChunk(ne(),J)}G==="json"&&(!x||!(0,qb.default)(x).length)?w():(d&&d(),e(x))}else w()}),n.addEventListener("error",()=>{w()}),p){let R=()=>{(0,It.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(X=xe(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=h,n.send(),re},re={withBitrateReporting:I,withParallel:A,withJSONResponse:P,withRetryCount:O=>(l=O,re),withRetryInterval:(O,ie)=>((0,It.isNonNullable)(O)&&(g=O),(0,It.isNonNullable)(ie)&&(f=ie),re),withTimeout:O=>(o=O,re),withFinally:E,send:F,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return re}var ea=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 Hb=W(si(),1);var ta=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=xe(),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=xe()-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=ni(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=xe()}_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=xe();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,Hb.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 Qb=require("@vkontakte/videoplayer-shared/es2015");var en=1e4,ju=3;var ik=6e4,ak=10,sk=1,nk=500,ra=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 Qb.Subject,this.chunkRateEstimator=new ea(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Hu(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=Hu(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Mb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,jb.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=()=>{Ub(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 ta(ju,en,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},p=(w,A,F)=>{u&&u.abort(),u=ni(this.urlResolver.resolve(w,!1),A,F,()=>this._retryCallback()).withTimeout(en).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ju).withFinally(()=>{u=null}).send()},h=(w,A,F)=>{(0,Ke.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),A,F,()=>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}`),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 F=xe()-1e4,Q=0;for(let H=0;H<this.bufferStates.length;H++){let te=this.bufferStates[H];w=Math.min(w,te.buf),te.ts<F&&Q++}this.bufferStates.splice(0,Q),t(`update playback rate; minBuffer=${w} drop=${Q} jitter=${this.sourceJitter}`);let de=w-sk;this.sourceJitter>=0?de-=this.sourceJitter/2:this.sourceJitter-=1,de>3?f(1.15):de>1?f(1.1):de>.3?f(1.05):f(1)}},I=w=>{let A,F=()=>A&&A.start?A.start.length:0,Q=R=>A.start[R]/1e3,de=R=>A.dur[R]/1e3,H=R=>A.fragIndex+R,te=(R,x)=>({chunkIdx:H(R),startTS:Q(R),dur:de(R),discontinuity:x}),re=()=>{let R=0;if(A&&A.dur){let x=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ae=x;this.sourceJitter>1&&(ae+=this.sourceJitter-1);let J=A.dur.length-1;for(;J>=0&&(ae-=A.dur[J],!(ae<=0));--J);R=Math.min(J,A.dur.length-1-G),R=Math.max(R,0)}return te(R,!0)},O=R=>{let x=F();if(!(x<=0)){if((0,Ke.isNonNullable)(R)){for(let G=0;G<x;G++)if(Q(G)>R)return te(G)}return re()}},ie=R=>{let x=F(),G=R?R.chunkIdx+1:0,ae=G-A.fragIndex;if(!(x<=0)){if(!R||ae<0||ae-x>ak)return t(`Resync: offset=${ae} bChunks=${x} chunk=`+JSON.stringify(R)),re();if(!(ae>=x))return te(G-A.fragIndex,!1)}},X=(R,x,G)=>{l&&l.abort(),l=ni(this.urlResolver.resolve(R,!0,this.lowLatency),x,G,()=>this._retryCallback()).withTimeout(en).withRetryCount(ju).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,x)=>{X(w,G=>{if(!d())return;A=G;let ae=!!A.lowLatency;ae!==this.lowLatency&&g(ae);let J=0;for(let Qe=0;Qe<A.dur.length;++Qe)J+=A.dur[Qe];J>0&&((0,Ke.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(J/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(O(x))},()=>this._handleNetworkError())},nextChunk:ie}},E=()=>{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:F}=this.params,Q=I(e.jidxUrl),de,H,te,re,O=0,ie,X,ne,R=()=>{ie&&(clearTimeout(ie),ie=void 0);let se=Math.max(nk,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Pe=O+se,$e=xe(),Re=Math.min(1e4,Pe-$e);O=$e;let qt=()=>{l||d()&&Q.seek(()=>{d()&&(O=xe(),x(),R())})};Re>0?ie=window.setTimeout(()=>{this.paused?R():qt()},Re):qt()},x=()=>{let se;for(;se=Q.nextChunk(re);)re=se,bi(se);let Pe=Q.nextChunk(te);if(Pe){if(te&&Pe.discontinuity){F("Detected discontinuity; restarting playback"),this.paused?R():(E(),this._initPlayerWith(e));return}Qe(Pe)}else R()},G=(se,Pe)=>{if(!d()||!this.sourceBuffer)return;let $e,Re,qt,Mr=Ut=>{window.setTimeout(()=>{d()&&G(se,Pe)},Ut)};if(this.sourceBuffer.updating)F("Source buffer is updating; delaying appendBuffer"),Mr(100);else{let Ut=xe(),or=A.currentTime;!this.paused&&A.buffered.length>1&&X===or&&Ut-ne>500&&(F("Stall suspected; trying to fix"),this._fixupStall()),X!==or&&(X=or,ne=Ut);let Dr=this._getBufferSizeSec();if(Dr>30)F(`Buffered ${Dr} seconds; delaying appendBuffer`),Mr(2e3);else try{this.sourceBuffer.appendBuffer(se),this.videoPlayStarted?(this.bufferStates.push({ts:Ut,buf:Dr}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Pe&&Pe()}catch(gi){if(gi.name==="QuotaExceededError")F("QuotaExceededError; delaying appendBuffer"),qt=this.sourceBuffer.buffered.length,qt!==0&&($e=this.sourceBuffer.buffered.start(0),Re=or,Re-$e>4&&this.sourceBuffer.remove($e,Re-3)),Mr(1e3);else throw gi}}},ae=()=>{H&&de&&(F([`Appending chunk, sz=${H.byteLength}:`,JSON.stringify(te)]),G(H,function(){H=null,x()}))},J=se=>e.fragUrlTemplate.replace("%%id%%",se.chunkIdx),Qe=se=>{d()&&h(J(se),(Pe,$e)=>{if(d()){if($e/=1e3,H=Pe,te=se,n=se.startTS,$e){let Re=Math.min(10,se.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Re:Re}ae()}},()=>this._handleNetworkError())},bi=se=>{d()&&((0,Ke.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(J(se),!1)))},Rr=se=>{d()&&(e.cachedHeader=se,G(se,()=>{de=!0,ae()}))};s=!0,Q.seek(se=>{if(d()){if(O=xe(),!se){R();return}re=se,!(0,Ke.isNullable)(w)||se.startTS>w?Qe(se):(te=se,x())}},w),e.cachedHeader?Rr(e.cachedHeader):p(e.headerUrl,Rr,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,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 p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=xe();if(this.chunkRateEstimator.addInterval(p,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Uu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=xe();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ni(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(en).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: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))},ik))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Gb=W(zr(),1),me=require("@vkontakte/videoplayer-shared/es2015"),Qu=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(),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,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 i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe((0,me.debounce)(this.droppedFramesChecker.checkTime)),r=(0,me.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,Gb.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>(0,me.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}},tn=Qu;var rn=require("@vkontakte/videoplayer-shared/es2015"),Wb=require("@vkontakte/videoplayer-shared/es2015");var ia=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var ok=(a,e)=>new rn.Observable(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||ia()))},k(k({},r),e));i.observe(a);let s=(0,Wb.fromEvent)(document,"visibilitychange").pipe((0,rn.map)(n=>!document.hidden||ia())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),tt=ok;var uk=["paused","playing","ready"],lk=["paused","playing","ready"],aa=class{constructor(e){this.subscription=new V.Subscription;this.videoState=new Y("stopped");this.representations$=new V.ValueSubject([]);this.droppedFramesManager=new tn;this.maxSeekBackTime$=new V.ValueSubject(1/0);this.zeroTime$=new V.ValueSubject(void 0);this.liveOffset=new Er;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=er(u.name))!=null?r:(0,V.videoSizeToQuality)(u.video),d=u.bitrate/1e3,p=k({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),(0,V.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Gu.default)(lk,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Gu.default)(uk,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(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(ke(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=Oe(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(Ee(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=Fe(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(Tt(this.video,this.params.desiredState.isLooped,t)).add(Ne(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),_e(this.video)}createLiveDashPlayer(){let e=new ra({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&(0,V.isNonNullable)(t)?t:ir(e.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let g=(f=e.find(({track:S})=>S.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(ke(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Yb=aa;var gS=W(dt(),1);var Et=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var U=require("@vkontakte/videoplayer-shared/es2015");var an=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}},oi=class extends an{constructor(){super(),this.listeners||an.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)}},sa=class{constructor(){Object.defineProperty(this,"signal",{value:new oi,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&&(sa.prototype[Symbol.toStringTag]="AbortController",oi.prototype[Symbol.toStringTag]="AbortSignal");function sn(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 Wu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!sn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var na=sn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zb=na?Wu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xt=na?zb.fetch:window.fetch,fV=na?zb.Request:window.Request,Le=na?sa:window.AbortController,bV=na?oi:window.AbortSignal;var El=W(zu(),1);var mn=W(tr(),1);var Ct=()=>window.ManagedMediaSource||window.MediaSource,nn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},fg=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},bg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Pt=require("@vkontakte/videoplayer-shared/es2015");var rt=document.createElement("video"),Ck='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Vk='video/mp4; codecs="hev1.1.6.L93.B0"',Ag='video/webm; codecs="vp09.00.10.08"',kg='video/webm; codecs="av01.0.00M.08"',Bk='audio/mp4; codecs="mp4a.40.2"',Ok='audio/webm; codecs="opus"',gg,vg,oa={mms:nn(),mse:fg(),hls:!!((gg=rt.canPlayType)!=null&&gg.call(rt,"application/x-mpegurl")||(vg=rt.canPlayType)!=null&&vg.call(rt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Sg,yg,Ue={mp4:!!((Sg=rt.canPlayType)!=null&&Sg.call(rt,"video/mp4")),webm:!!((yg=rt.canPlayType)!=null&&yg.call(rt,"video/webm")),cmaf:!0},un,Tg,ln,Ig,cn,Eg,dn,xg,pn,Pg,hn,wg,He={h264:!!((Tg=(un=Ct())==null?void 0:un.isTypeSupported)!=null&&Tg.call(un,Ck)),h265:!!((Ig=(ln=Ct())==null?void 0:ln.isTypeSupported)!=null&&Ig.call(ln,Vk)),vp9:!!((Eg=(cn=Ct())==null?void 0:cn.isTypeSupported)!=null&&Eg.call(cn,Ag)),av1:!!((xg=(dn=Ct())==null?void 0:dn.isTypeSupported)!=null&&xg.call(dn,kg)),aac:!!((Pg=(pn=Ct())==null?void 0:pn.isTypeSupported)!=null&&Pg.call(pn,Bk)),opus:!!((wg=(hn=Ct())==null?void 0:hn.isTypeSupported)!=null&&wg.call(hn,Ok))},ui=(He.h264||He.h265)&&He.aac,xr,_k=()=>L(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(_(k({},a),{video:_(k({},a.video),{contentType:kg})})),window.navigator.mediaCapabilities.decodingInfo(_(k({},a),{video:_(k({},a.video),{contentType:Ag})}))]);xr={DASH_WEBM_AV1:e,DASH_WEBM:t}});_k().catch(a=>{console.error(a)});var li=oa.hls&&Ue.mp4,Lg=()=>Object.keys(He).filter(a=>He[a]),$g=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=oa.mse&&(!r||!!window.MediaStreamTrack)||oa.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Ue.mp4&&ui;case"DASH_WEBM":return i&&Ue.webm&&He.vp9&&He.opus;case"DASH_WEBM_AV1":return i&&Ue.webm&&He.av1&&He.opus;case"DASH_STREAMS":return i&&(Ue.mp4&&ui||Ue.webm&&(He.vp9||He.av1)&&(He.opus||He.aac));case"DASH_LIVE":return i&&Ue.mp4&&ui;case"DASH_LIVE_CMAF":return i&&Ue.mp4&&ui&&Ue.cmaf;case"DASH_ONDEMAND":return i&&Ue.mp4&&ui;case"HLS":case"HLS_ONDEMAND":return li||e&&i&&Ue.mp4&&ui;case"HLS_LIVE":case"HLS_LIVE_CMAF":return li;case"MPEG":return Ue.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return oa.webrtc&&oa.ws&&He.h264&&(Ue.mp4||Ue.webm);default:return(0,Pt.assertNever)(s)}})},on=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return xr?xr[t].smooth?[t,e]:xr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return xr?xr[t].powerEfficient?[t,e]:xr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:(0,Pt.assertNever)(a)}return[e,t]},Rg=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...on(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Pt.clientChecker.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...on(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...on(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...on(a),...i,"HLS","HLS_ONDEMAND"];default:(0,Pt.assertNever)(e)}return li?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Mg=({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=Pt.clientChecker.isMac&&Pt.clientChecker.isSafari;if(Pt.clientChecker.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,Pt.assertNever)(a)}else li&&!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"]},Ku=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Dg=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,mn.default)(t.value.split("."),0)}for(let t of a){let r=(0,mn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,mn.default)(e.value.split("."),0)};var ev=W(Zg(),1),ci=require("@vkontakte/videoplayer-shared/es2015"),tv=a=>{if(!a)return{id:"EmptyResponse",category:ci.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ci.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,ev.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ci.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:ci.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ci.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var ar=(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 v=require("@vkontakte/videoplayer-shared/es2015");var fn=W(dt(),1),hi=W(tr(),1),bn=W(zu(),1);var tL=(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)},rL=a=>window.clearTimeout(a),rv=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),iv=!rv(window.requestIdleCallback)||!rv(window.cancelIdleCallback),tl=iv?tL:window.requestIdleCallback,la=iv?rL:window.cancelIdleCallback;var lS=W(Ys(),1);var it=require("@vkontakte/videoplayer-shared/es2015");var iL=18,av=!1;try{av=it.clientChecker.isSafari&&!!it.clientChecker.macVersion&&it.clientChecker.macVersion<=iL}catch(a){console.error(a)}var rl=class{constructor(e){this.bufferFull$=new it.Subject;this.error$=new it.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:it.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return L(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return L(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return L(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};av&&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:it.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,it.assertNever)(t)}}},sv=rl;var il=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var T=require("@vkontakte/videoplayer-shared/es2015");var Z=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 di=class extends Z{};var ca=class extends Z{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 da=class extends Z{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 pa=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var le=class extends Z{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ha=class extends le{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ma=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends Z{constructor(e,t){super(e,t),this.data=this.content}};var Pr=class extends le{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ba=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends le{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Sa=class extends le{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ya=class extends le{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ta=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends le{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Ea=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xa=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends le{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var wa=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends le{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ka=class extends le{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var La=class extends le{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var $a=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ra=class extends le{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 Ma=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var sL={ftyp:da,moov:pa,mvhd:ha,moof:ma,mdat:fa,sidx:Pr,trak:ba,mdia:Ta,mfhd:Pa,tkhd:Ia,traf:wa,tfhd:Aa,tfdt:ka,trun:La,minf:Ea,sv3d:ga,st3d:va,prhd:Sa,proj:xa,equi:ya,uuid:ca,stbl:$a,stsd:Ra,avc1:Ma,unknown:di},Vt=class a{constructor(e={}){this.options=k({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=sL[e];return r?new r(t,new a):new di(t,new a)}};var sr=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 oL=new TextDecoder("ascii"),uL=a=>oL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",lL=a=>{let e=new Pr(a,new Vt),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})},cL=(a,e)=>{let r=new Vt().parse(a),i=new sr(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)},dL=a=>{let t=new Vt().parse(a),r=new sr(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},pL=a=>{var i;let t=new Vt().parse(a);return(i=new sr(t).find("sidx"))==null?void 0:i.timescale},hL=(a,e)=>{let r=new Vt().parse(a),s=new sr(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},mL=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 Vt().parse(a),i=new sr(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},nv={validateData:uL,parseInit:mL,getIndexRange:()=>{},parseSegments:lL,parseFeedableSegmentChunk:cL,getChunkEndTime:hL,getServerLatencyTimestamps:dL,getTimescaleFromIndex:pL};var Ca=W(dt(),1),Bt=require("@vkontakte/videoplayer-shared/es2015");var uv=require("@vkontakte/videoplayer-shared/es2015");var ov={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"}},lv=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=Da(a,t),i=r in ov,s=i?ov[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=Da(u),d=l*gt(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Da=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*gt(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*gt(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*gt(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},ht=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Da(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,uv.assertNever)(e)}},wr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=lv(r);if(!e(i))return;i.type==="master"&&wr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},cv=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=lv(a);return wr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=ht(o,n):s===17026?t=ht(o,n):s===17029&&(r=ht(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var dv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],fL=[231,22612,22743,167,171,163,160,175],bL=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return wr(a,({tag:p,type:h,value:f,valueSize:g})=>{if(p===21419){let S=ht(f,h);l=Da(S)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=ht(f,h):p===17545?i=ht(f,h):p===21420&&l===475249515?u=ht(f,h):p===374648427?wr(f,({tag:S,type:I,value:E})=>S===30321?(c=ht(E,I)===1,!1):!0):s&&n&&(0,Ca.default)(dv,p)&&(o=!0),!o}),(0,Bt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Bt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Bt.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}}}},gL=a=>{if((0,Bt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},vL=(a,e)=>{let t=!1,r=!1,i=o=>(0,Bt.isNonNullable)(o.time)&&(0,Bt.isNonNullable)(o.position),s=[],n;return wr(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=ht(l,u));break;case 183:break;case 241:n&&(n.position=ht(l,u));break;default:t&&(0,Ca.default)(dv,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}}})},SL=a=>{let e=0,t=!1;try{wr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Ca.default)(fL,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Ca.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},pv={validateData:cv,parseInit:bL,getIndexRange:gL,parseSegments:vL,parseFeedableSegmentChunk:SL};var Va=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return pv;case"mp4":return nv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var bl=W(Mv(),1),aS=W(zr(),1),sS=W(Yv(),1),nS=W(tr(),1),gl=W(si(),1);var zv=W(dt(),1),cl=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,zv.default)(["6E","7A","F4"],o)}}return!1};var Oa=require("@vkontakte/videoplayer-shared/es2015");var Kv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Xv=a=>{var e;try{let t=m$(),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 m$(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
63
|
+
`}),E};var Pe=a=>new URL(a).hostname;var B=require("@vkontakte/videoplayer-shared/es2015");var Wb=G(Jt(),1);var Hb=G(Xe(),1);var Ub=a=>{if(a instanceof DOMException&&(0,Hb.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"))},Ue=(a,e)=>k(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Ub(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Ub(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});var Ye=require("@vkontakte/videoplayer-shared/es2015");var jb=G(ri(),1),It=require("@vkontakte/videoplayer-shared/es2015");function we(){return(0,It.now)()}function Bu(a){return we()-a}function Ou(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 Qb(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ai(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,S=()=>{if(u)return;(0,It.assertNonNullable)(c);let _=Bu(c),se;if(_<g){se=g-_,setTimeout(S,se);return}g*=2,g>f&&(g=f),n&&n.abort(),n=new i,A()},T=_=>(s=_,re),E=_=>(d=_,re),x=()=>(m="json",re),w=()=>{if(!u){if(--l>=0){S(),r&&r();return}u=!0,d&&d(),t&&t()}},P=_=>(h=_,re),A=()=>{c=we(),n=new i,n.open("get",a);let _=0,se,K=0,ue=()=>((0,It.assertNonNullable)(c),Math.max(c,Math.max(se||0,K||0)));if(s&&n.addEventListener("progress",C=>{let H=we();s.updateChunk&&C.loaded>_&&(s.updateChunk(ue(),C.loaded-_),_=C.loaded,se=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;(0,It.assertNonNullable)(n);let C=n.status;if(C>=200&&C<300){let{response:H,responseType:$}=n,Z=H==null?void 0:H.byteLength;if(typeof Z=="number"&&s){let W=Z-_;W&&s.updateChunk&&s.updateChunk(ue(),W)}$==="json"&&(!H||!(0,jb.default)(H).length)?w():(d&&d(),e(H))}else w()}),n.addEventListener("error",()=>{w()}),h){let C=()=>{(0,It.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=we(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=m,n.send(),re},re={withBitrateReporting:T,withParallel:P,withJSONResponse:x,withRetryCount:_=>(l=_,re),withRetryInterval:(_,se)=>((0,It.isNonNullable)(_)&&(g=_),(0,It.isNonNullable)(se)&&(f=se),re),withTimeout:_=>(o=_,re),withFinally:E,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return re}var zi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Gb=G(ri(),1);var Ki=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=we(),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=we()-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=ai(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=we()}_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=we();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Gb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Yb=require("@vkontakte/videoplayer-shared/es2015");var tn=1e4,Nu=3;var KA=6e4,XA=10,JA=1,ZA=500,Xi=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 Yb.Subject,this.chunkRateEstimator=new zi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ou(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=Ou(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*(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||{};!Vb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Wb.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,Ye.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=()=>{Qb(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 Ki(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,P,A)=>{u&&u.abort(),u=ai(this.urlResolver.resolve(w,!1),P,A,()=>this._retryCallback()).withTimeout(tn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Nu).withFinally(()=>{u=null}).send()},m=(w,P,A)=>{(0,Ye.assertNonNullable)(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),P,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=w=>{let P=r.playbackRate;r.playbackRate!==w&&(t(`Playback rate switch: ${P}=>${w}`),r.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 A=we()-1e4,U=0;for(let J=0;J<this.bufferStates.length;J++){let te=this.bufferStates[J];w=Math.min(w,te.buf),te.ts<A&&U++}this.bufferStates.splice(0,U),t(`update playback rate; minBuffer=${w} drop=${U} jitter=${this.sourceJitter}`);let oe=w-JA;this.sourceJitter>=0?oe-=this.sourceJitter/2:this.sourceJitter-=1,oe>3?f(1.15):oe>1?f(1.1):oe>.3?f(1.05):f(1)}},T=w=>{let P,A=()=>P&&P.start?P.start.length:0,U=C=>P.start[C]/1e3,oe=C=>P.dur[C]/1e3,J=C=>P.fragIndex+C,te=(C,H)=>({chunkIdx:J(C),startTS:U(C),dur:oe(C),discontinuity:H}),re=()=>{let C=0;if(P&&P.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,$=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=H;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let W=P.dur.length-1;for(;W>=0&&(Z-=P.dur[W],!(Z<=0));--W);C=Math.min(W,P.dur.length-1-$),C=Math.max(C,0)}return te(C,!0)},_=C=>{let H=A();if(!(H<=0)){if((0,Ye.isNonNullable)(C)){for(let $=0;$<H;$++)if(U($)>C)return te($)}return re()}},se=C=>{let H=A(),$=C?C.chunkIdx+1:0,Z=$-P.fragIndex;if(!(H<=0)){if(!C||Z<0||Z-H>XA)return t(`Resync: offset=${Z} bChunks=${H} chunk=`+JSON.stringify(C)),re();if(!(Z>=H))return te($-P.fragIndex,!1)}},K=(C,H,$)=>{l&&l.abort(),l=ai(this.urlResolver.resolve(C,!0,this.lowLatency),H,$,()=>this._retryCallback()).withTimeout(tn).withRetryCount(Nu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(C,H)=>{K(w,$=>{if(!d())return;P=$;let Z=!!P.lowLatency;Z!==this.lowLatency&&g(Z);let W=0;for(let rt=0;rt<P.dur.length;++rt)W+=P.dur[rt];W>0&&((0,Ye.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(W/P.dur.length)),i({name:"index",zeroTime:P.zeroTime,shiftDuration:P.shiftDuration}),this.sourceJitter=P.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,P.jitter/1e3)):1,C(_(H))},()=>this._handleNetworkError())},nextChunk:se}},E=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ye.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{let{videoElement:P,logger:A}=this.params,U=T(e.jidxUrl),oe,J,te,re,_=0,se,K,ue,C=()=>{se&&(clearTimeout(se),se=void 0);let ne=Math.max(ZA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Le=_+ne,Me=we(),_e=Math.min(1e4,Le-Me);_=Me;let it=()=>{l||d()&&U.seek(()=>{d()&&(_=we(),H(),C())})};_e>0?se=window.setTimeout(()=>{this.paused?C():it()},_e):it()},H=()=>{let ne;for(;ne=U.nextChunk(re);)re=ne,Ot(ne);let Le=U.nextChunk(te);if(Le){if(te&&Le.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?C():(E(),this._initPlayerWith(e));return}rt(Le)}else C()},$=(ne,Le)=>{if(!d()||!this.sourceBuffer)return;let Me,_e,it,$r=Nt=>{window.setTimeout(()=>{d()&&$(ne,Le)},Nt)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),$r(100);else{let Nt=we(),sr=P.currentTime;!this.paused&&P.buffered.length>1&&K===sr&&Nt-ue>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),K!==sr&&(K=sr,ue=Nt);let Rr=this._getBufferSizeSec();if(Rr>30)A(`Buffered ${Rr} seconds; delaying appendBuffer`),$r(2e3);else try{this.sourceBuffer.appendBuffer(ne),this.videoPlayStarted?(this.bufferStates.push({ts:Nt,buf:Rr}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Le&&Le()}catch(pi){if(pi.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),it=this.sourceBuffer.buffered.length,it!==0&&(Me=this.sourceBuffer.buffered.start(0),_e=sr,_e-Me>4&&this.sourceBuffer.remove(Me,_e-3)),$r(1e3);else throw pi}}},Z=()=>{J&&oe&&(A([`Appending chunk, sz=${J.byteLength}:`,JSON.stringify(te)]),$(J,function(){J=null,H()}))},W=ne=>e.fragUrlTemplate.replace("%%id%%",ne.chunkIdx),rt=ne=>{d()&&m(W(ne),(Le,Me)=>{if(d()){if(Me/=1e3,J=Le,te=ne,n=ne.startTS,Me){let _e=Math.min(10,ne.dur/Me);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*_e:_e}Z()}},()=>this._handleNetworkError())},Ot=ne=>{d()&&((0,Ye.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(W(ne),!1)))},kr=ne=>{d()&&(e.cachedHeader=ne,$(ne,()=>{oe=!0,Z()}))};s=!0,U.seek(ne=>{if(d()){if(_=we(),!ne){C();return}re=ne,!(0,Ye.isNullable)(w)||ne.startTS>w?rt(ne):(te=ne,H())}},w),e.cachedHeader?kr(e.cachedHeader):h(e.headerUrl,kr,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),(0,Ye.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,Ye.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ye.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=we();if(this.chunkRateEstimator.addInterval(h,f,m)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:f-h,speed:S}),!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&&Bu(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=we();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ai(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;Ue(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))},KA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var zb=G(Gr(),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,zb.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"),Kb=require("@vkontakte/videoplayer-shared/es2015");var Ji=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var ek=(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||Ji()))},R(R({},r),e));i.observe(a);let s=(0,Kb.fromEvent)(document,"visibilitychange").pipe((0,an.map)(n=>!document.hidden||Ji())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),et=ek;var tk=["paused","playing","ready"],rk=["paused","playing","ready"],Zi=class{constructor(e){this.subscription=new B.Subscription;this.videoState=new Y("stopped");this.representations$=new B.ValueSubject([]);this.droppedFramesManager=new rn;this.maxSeekBackTime$=new B.ValueSubject(1/0);this.zeroTime$=new B.ValueSubject(void 0);this.liveOffset=new Tr;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:B.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=Xt(u.name))!=null?r:(0,B.videoSizeToQuality)(u.video),d=u.bitrate/1e3,h=R({},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,B.isNonNullable)(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,qu.default)(rk,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,qu.default)(tk,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource($e(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($e(this.params.source.url,u))}return;default:return(0,B.assertNever)(e)}};this.textTracksManager=new Ze(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:B.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:i})};(0,B.merge)(this.videoState.stateChangeStarted$.pipe((0,B.map)(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,B.map)(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Oe(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(Pe(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=qe(this.video);this.subscription.add(this.representations$.pipe((0,B.map)(i=>i.map(({track:s})=>s)),(0,B.filter)(i=>!!i.length),(0,B.once)()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,B.filterChanged)(),(0,B.map)(i=>-i/1e3)).subscribe(this.params.output.duration$)).add((0,B.combine)({zeroTime:this.zeroTime$.pipe((0,B.filter)(B.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Tt(this.video,this.params.desiredState.isLooped,t)).add(Fe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Je(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(et(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,B.videoQualityToHeight)(i),min:s&&(0,B.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,B.assertNever)(i.to)}},t)).add((0,B.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,B.observableFrom)(["init"])).pipe((0,B.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ne(this.video)}createLiveDashPlayer(){let e=new Xi({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,B.isNonNullable)(t)?t:er(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:S})=>S.id===s))==null?void 0:f.representation;(0,B.assertNonNullable)(g,"Representations missing"),this.dash.startPlay(g,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;(0,B.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit($e(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Xb=Zi;var sS=G(Xe(),1);var Et=(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 j=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}},si=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)}},ea=class{constructor(){Object.defineProperty(this,"signal",{value:new si,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&&(ea.prototype[Symbol.toStringTag]="AbortController",si.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 ta=nn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Jb=ta?Uu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xt=ta?Jb.fetch:window.fetch,UV=ta?Jb.Request:window.Request,Re=ta?ea:window.AbortController,HV=ta?si:window.AbortSignal;var vl=G(ju(),1);var Og=G(Bg(),1),ni=require("@vkontakte/videoplayer-shared/es2015"),Ng=a=>{if(!a)return{id:"EmptyResponse",category:ni.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ni.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,Og.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ni.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:ni.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ni.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var tr=(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 v=require("@vkontakte/videoplayer-shared/es2015");var on=G(Xe(),1),li=G(Jt(),1),un=G(ju(),1);var qk=(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)},Uk=a=>window.clearTimeout(a),Fg=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),qg=!Fg(window.requestIdleCallback)||!Fg(window.cancelIdleCallback),zu=qg?qk:window.requestIdleCallback,ia=qg?Uk:window.cancelIdleCallback;var Wv=G(Hs(),1);var rr=require("@vkontakte/videoplayer-shared/es2015");var Hk=18,Ug=!1;try{Ug=ee.browser.isSafari&&!!ee.browser.safariVersion&&ee.browser.safariVersion<=Hk}catch(a){console.error(a)}var Ku=class{constructor(e){this.bufferFull$=new rr.Subject;this.error$=new rr.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:rr.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)};Ug&&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:rr.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,rr.assertNever)(t)}}},Hg=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 I=require("@vkontakte/videoplayer-shared/es2015");var ie=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 oi=class extends ie{};var aa=class extends ie{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 sa=class extends ie{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 na=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var de=class extends ie{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var oa=class extends de{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ua=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var la=class extends ie{constructor(e,t){super(e,t),this.data=this.content}};var Ir=class extends de{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ca=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends de{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ha=class extends de{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ma=class extends de{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var fa=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends de{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ga=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends de{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ya=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends de{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ia=class extends de{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Ea=class extends de{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var xa=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends de{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 wa=class extends ie{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var Qk={ftyp:sa,moov:na,mvhd:oa,moof:ua,mdat:la,sidx:Ir,trak:ca,mdia:fa,mfhd:Sa,tkhd:ba,traf:ya,tfhd:Ta,tfdt:Ia,trun:Ea,minf:ga,sv3d:da,st3d:pa,prhd:ha,proj:va,equi:ma,uuid:aa,stbl:xa,stsd:Pa,avc1:wa,unknown:oi},Mt=class a{constructor(e={}){this.options=R({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=Qk[e];return r?new r(t,new a):new oi(t,new a)}};var ir=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 Wk=new TextDecoder("ascii"),Yk=a=>Wk.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",zk=a=>{let e=new Ir(a,new Mt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},Kk=(a,e)=>{let r=new Mt().parse(a),i=new ir(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)},Xk=a=>{let t=new Mt().parse(a),r=new ir(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},Jk=a=>{var i;let t=new Mt().parse(a);return(i=new ir(t).find("sidx"))==null?void 0:i.timescale},Zk=(a,e)=>{let r=new Mt().parse(a),s=new ir(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},e$=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new Mt().parse(a),i=new ir(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},jg={validateData:Yk,parseInit:e$,getIndexRange:()=>{},parseSegments:zk,parseFeedableSegmentChunk:Kk,getChunkEndTime:Zk,getServerLatencyTimestamps:Xk,getTimescaleFromIndex:Jk};var ka=G(Xe(),1),Ct=require("@vkontakte/videoplayer-shared/es2015");var Gg=require("@vkontakte/videoplayer-shared/es2015");var Qg={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"}},Wg=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=Aa(a,t),i=r in Qg,s=i?Qg[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=Aa(u),d=l*bt(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}},Aa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*bt(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*bt(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*bt(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},pt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Aa(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,Gg.assertNever)(e)}},Er=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Wg(r);if(!e(i))return;i.type==="master"&&Er(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Yg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Wg(a);return Er(i.value,({tag:s,type:n,value:o})=>(s===17143?e=pt(o,n):s===17026?t=pt(o,n):s===17029&&(r=pt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var zg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],t$=[231,22612,22743,167,171,163,160,175],r$=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Er(a,({tag:h,type:m,value:f,valueSize:g})=>{if(h===21419){let S=pt(f,m);l=Aa(S)}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=pt(f,m):h===17545?i=pt(f,m):h===21420&&l===475249515?u=pt(f,m):h===374648427?Er(f,({tag:S,type:T,value:E})=>S===30321?(c=pt(E,T)===1,!1):!0):s&&n&&(0,ka.default)(zg,h)&&(o=!0),!o}),(0,Ct.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Ct.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Ct.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}}}},i$=a=>{if((0,Ct.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},a$=(a,e)=>{let t=!1,r=!1,i=o=>(0,Ct.isNonNullable)(o.time)&&(0,Ct.isNonNullable)(o.position),s=[],n;return Er(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=pt(l,u));break;case 183:break;case 241:n&&(n.position=pt(l,u));break;default:t&&(0,ka.default)(zg,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}}})},s$=a=>{let e=0,t=!1;try{Er(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ka.default)(t$,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ka.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},Kg={validateData:Yg,parseInit:r$,getIndexRange:i$,parseSegments:a$,parseFeedableSegmentChunk:s$};var $a=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Kg;case"mp4":return jg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var cl=G(bv(),1),Uv=G(Gr(),1),Hv=G(Mv(),1),jv=G(Jt(),1),dl=G(ri(),1);var Cv=G(Xe(),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,Cv.default)(["6E","7A","F4"],o)}}return!1};var La=require("@vkontakte/videoplayer-shared/es2015");var Dv=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Vv=a=>{var e;try{let t=eR(),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 eR(){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 pl=W(tr(),1);var Jv=require("@vkontakte/videoplayer-shared/es2015"),Zv=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?er(s):void 0)!=null?u:(0,Jv.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},eS=({id:a,bitrate:e})=>({id:a,bitrate:e}),tS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),rS=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),hl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,pl.default)(r.split("."),0),isDefault:i}),ml=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,pl.default)(i.split("."),0)}),fl=a=>"url"in a,Ce=a=>a.type==="template",Ba=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var iS=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},Ot=(a,e)=>{let t=a;t=(0,bl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,aS.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,bl.default)(t,n,(o,u)=>(0,Oa.isNullable)(s)?o:(0,Oa.isNullable)(u)?s:(0,sS.default)(s,parseInt(u,10),"0"))}return t},oS=(a,e)=>{var H,te,re,O,ie,X,ne,R,x,G,ae,J,Qe,bi,Rr,se,Pe,$e,Re,qt,Mr,Ut,or,Dr,gi,Dl,Cl,Vl,Bl,Ol,_l,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,dc,pc,hc,mc;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(st=>{var ue,ur;return(ur=(ue=st.textContent)==null?void 0:ue.trim())!=null?ur:""}),o=(H=(0,nS.default)(n,0))!=null?H:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],p=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=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:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let I,E=s.getAttribute("mediaPresentationDuration"),P=[...s.getElementsByTagName("Period")],w=P.reduce((st,ue)=>_(k({},st),{[ue.id]:ue.children}),{}),A=P.reduce((st,ue)=>_(k({},st),{[ue.id]:ue.getAttribute("duration")}),{});E?I=iS(E):(0,gl.default)(A).filter(st=>st).length&&!u?I=(0,gl.default)(A).reduce((st,ue)=>{var ur;return st+((ur=iS(ue))!=null?ur:0)},0):g&&(I=parseInt(g,10));let F=0,Q=(re=(te=s.getAttribute("profiles"))==null?void 0:te.split(","))!=null?re:[];for(let st of P.map(ue=>ue.id))for(let ue of w[st]){let ur=(O=ue.getAttribute("id"))!=null?O:"id"+(F++).toString(10),vi=(ie=ue.getAttribute("mimeType"))!=null?ie:"",Dn=(X=ue.getAttribute("codecs"))!=null?X:"",Cn=(ne=ue.getAttribute("contentType"))!=null?ne:vi==null?void 0:vi.split("/")[0],US=(x=(R=ue.getAttribute("profiles"))==null?void 0:R.split(","))!=null?x:[],fc=(ae=Xv((G=ue.getAttribute("lang"))!=null?G:""))!=null?ae:{},Za=(bi=(Qe=(J=ue.querySelector("Label"))==null?void 0:J.textContent)==null?void 0:Qe.trim())!=null?bi:void 0,HS=ue.querySelectorAll("Representation"),jS=ue.querySelector("SegmentTemplate"),QS=(se=(Rr=ue.querySelector("Role"))==null?void 0:Rr.getAttribute("value"))!=null?se:void 0,Cr=Cn,be={id:ur,language:fc.language,isDefault:QS==="main",label:Za,codecs:Dn,hdr:Cr==="video"&&cl(Dn),mime:vi,representations:[]};for(let oe of HS){let Ht=(Pe=oe.getAttribute("lang"))!=null?Pe:void 0,Si=(Re=($e=Za!=null?Za:ue.getAttribute("label"))!=null?$e:oe.getAttribute("label"))!=null?Re:void 0,es=(Ut=(Mr=(qt=oe.querySelector("BaseURL"))==null?void 0:qt.textContent)==null?void 0:Mr.trim())!=null?Ut:"",lr=new URL(es||o,e).toString(),jt=(or=oe.getAttribute("mimeType"))!=null?or:vi,ts=(gi=(Dr=oe.getAttribute("codecs"))!=null?Dr:Dn)!=null?gi:"",rs;if(Cn==="text"){let Qt=oe.getAttribute("id")||"",is=((Dl=fc.privateuse)==null?void 0:Dl.includes("x-auto"))||Qt.includes("_auto"),cr=oe.querySelector("SegmentTemplate");if(cr){let yi={representationId:(Cl=oe.getAttribute("id"))!=null?Cl:void 0,bandwidth:(Vl=oe.getAttribute("bandwidth"))!=null?Vl:void 0},as=parseInt((Bl=oe.getAttribute("bandwidth"))!=null?Bl:"",10)/1e3,ss=(_l=parseInt((Ol=cr.getAttribute("startNumber"))!=null?Ol:"",10))!=null?_l:1,Vr=parseInt((Nl=cr.getAttribute("timescale"))!=null?Nl:"",10),Vn=(Fl=cr.querySelectorAll("SegmentTimeline S"))!=null?Fl:[],Br=cr.getAttribute("media");if(!Br)continue;let ns=[],os=0,us="",Or=0,Ti=ss,Me=0;for(let nt of Vn){let dr=parseInt((ql=nt.getAttribute("d"))!=null?ql:"",10),Je=parseInt((Ul=nt.getAttribute("r"))!=null?Ul:"",10)||0,Gt=parseInt((Hl=nt.getAttribute("t"))!=null?Hl:"",10);Me=Number.isFinite(Gt)?Gt:Me;let pr=dr/Vr*1e3,Wt=Me/Vr*1e3;for(let ft=0;ft<Je+1;ft++){let Yt=Ot(Br,_(k({},yi),{segmentNumber:Ti.toString(10),segmentTime:(Me+ft*dr).toString(10)})),_r=(Wt!=null?Wt:0)+ft*pr,Ei=_r+pr;Ti++,ns.push({time:{from:_r,to:Ei},url:Yt})}Me+=(Je+1)*dr,os+=(Je+1)*pr}Or=Me/Vr*1e3,us=Ot(Br,_(k({},yi),{segmentNumber:Ti.toString(10),segmentTime:Me.toString(10)}));let Ii={time:{from:Or,to:1/0},url:us},At={type:"template",baseUrl:lr,segmentTemplateUrl:Br,initUrl:"",totalSegmentsDurationMs:os,segments:ns,nextSegmentBeyondManifest:Ii,timescale:Vr};rs={id:Qt,kind:"text",segmentReference:At,profiles:[],duration:I,bitrate:as,mime:"",codecs:"",width:0,height:0,isAuto:is}}else rs={id:Qt,isAuto:is,kind:"text",url:lr}}else{let Qt=(Ql=(jl=oe.getAttribute("contentType"))!=null?jl:jt==null?void 0:jt.split("/")[0])!=null?Ql:Cn,is=(Wl=(Gl=ue.getAttribute("profiles"))==null?void 0:Gl.split(","))!=null?Wl:[],cr=parseInt((Yl=oe.getAttribute("width"))!=null?Yl:"",10),yi=parseInt((zl=oe.getAttribute("height"))!=null?zl:"",10),as=parseInt((Kl=oe.getAttribute("bandwidth"))!=null?Kl:"",10)/1e3,ss=(Xl=oe.getAttribute("frameRate"))!=null?Xl:"",Vr=(Jl=oe.getAttribute("quality"))!=null?Jl:void 0,Vn=ss?Kv(ss):void 0,Br=(Zl=oe.getAttribute("id"))!=null?Zl:"id"+(F++).toString(10),ns=Qt==="video"?`${yi}p`:Qt==="audio"?`${as}Kbps`:ts,os=`${Br}@${ns}`,us=[...Q,...US,...is],Or,Ti=oe.querySelector("SegmentBase"),Me=(ec=oe.querySelector("SegmentTemplate"))!=null?ec:jS;if(Ti){let At=(rc=(tc=oe.querySelector("SegmentBase Initialization"))==null?void 0:tc.getAttribute("range"))!=null?rc:"",[nt,dr]=At.split("-").map(Yt=>parseInt(Yt,10)),Je={from:nt,to:dr},Gt=(ic=oe.querySelector("SegmentBase"))==null?void 0:ic.getAttribute("indexRange"),[pr,Wt]=Gt?Gt.split("-").map(Yt=>parseInt(Yt,10)):[],ft=Gt?{from:pr,to:Wt}:void 0;Or={type:"byteRange",url:lr,initRange:Je,indexRange:ft}}else if(Me){let At={representationId:(ac=oe.getAttribute("id"))!=null?ac:void 0,bandwidth:(sc=oe.getAttribute("bandwidth"))!=null?sc:void 0},nt=parseInt((nc=Me.getAttribute("timescale"))!=null?nc:"",10),dr=(oc=Me.getAttribute("initialization"))!=null?oc:"",Je=Me.getAttribute("media"),Gt=(lc=parseInt((uc=Me.getAttribute("startNumber"))!=null?uc:"",10))!=null?lc:1,pr=Ot(dr,At);if(!Je)throw new ReferenceError("No media attribute in SegmentTemplate");let Wt=(cc=Me.querySelectorAll("SegmentTimeline S"))!=null?cc:[],ft=[],Yt=0,_r="",Ei=0;if(Wt.length){let ls=Gt,ot=0;for(let Nr of Wt){let bt=parseInt((dc=Nr.getAttribute("d"))!=null?dc:"",10),hr=parseInt((pc=Nr.getAttribute("r"))!=null?pc:"",10)||0,cs=parseInt((hc=Nr.getAttribute("t"))!=null?hc:"",10);ot=Number.isFinite(cs)?cs:ot;let Bn=bt/nt*1e3,On=ot/nt*1e3;for(let ds=0;ds<hr+1;ds++){let WS=Ot(Je,_(k({},At),{segmentNumber:ls.toString(10),segmentTime:(ot+ds*bt).toString(10)})),bc=(On!=null?On:0)+ds*Bn,YS=bc+Bn;ls++,ft.push({time:{from:bc,to:YS},url:WS})}ot+=(hr+1)*bt,Yt+=(hr+1)*Bn}Ei=ot/nt*1e3,_r=Ot(Je,_(k({},At),{segmentNumber:ls.toString(10),segmentTime:ot.toString(10)}))}else if((0,Oa.isNonNullable)(I)){let ot=parseInt((mc=Me.getAttribute("duration"))!=null?mc:"",10)/nt*1e3,Nr=Math.ceil(I/ot),bt=0;for(let hr=1;hr<Nr;hr++){let cs=Ot(Je,_(k({},At),{segmentNumber:hr.toString(10),segmentTime:bt.toString(10)}));ft.push({time:{from:bt,to:bt+ot},url:cs}),bt+=ot}Ei=bt,_r=Ot(Je,_(k({},At),{segmentNumber:Nr.toString(10),segmentTime:bt.toString(10)}))}let GS={time:{from:Ei,to:1/0},url:_r};Or={type:"template",baseUrl:lr,segmentTemplateUrl:Je,initUrl:pr,totalSegmentsDurationMs:Yt,segments:ft,nextSegmentBeyondManifest:GS,timescale:nt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qt||!jt)continue;let Ii={video:"video",audio:"audio",text:"text"}[Qt];if(!Ii)continue;Cr||(Cr=Ii),rs={id:os,kind:Ii,segmentReference:Or,profiles:us,duration:I,bitrate:as,mime:jt,codecs:ts,width:cr,height:yi,fps:Vn,quality:Vr}}be.language||(be.language=Ht),be.label||(be.label=Si),be.mime||(be.mime=jt),be.codecs||(be.codecs=ts),be.hdr||(be.hdr=Cr==="video"&&cl(ts)),be.representations.push(rs)}if(Cr){let oe=i[Cr].find(Ht=>Ht.id===be.id);if(oe&&be.representations.every(Ht=>Ce(Ht.segmentReference)))for(let Ht of oe.representations){let Si=be.representations.find(jt=>jt.id===Ht.id),es=Si==null?void 0:Si.segmentReference,lr=Ht.segmentReference;lr.segments.push(...es.segments),lr.nextSegmentBeyondManifest=es.nextSegmentBeyondManifest}else i[Cr].push(be)}}return{duration:I,streams:i,baseUrls:n,live:S}};var uS=W(dt(),1),Sl=require("@vkontakte/videoplayer-shared/es2015"),Ve=(a,e)=>(0,Sl.isNonNullable)(a)&&(0,Sl.isNonNullable)(e)&&a.readyState==="open"&&(0,uS.default)([...a.activeSourceBuffers],e);var _a=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new T.ValueSubject(0);this.currentLowLatencySegmentLength$=new T.ValueSubject(0);this.currentSegmentLength$=new T.ValueSubject(0);this.onLastSegment$=new T.ValueSubject(!1);this.fullyBuffered$=new T.ValueSubject(!1);this.playingRepresentation$=new T.ValueSubject(void 0);this.playingRepresentationInit$=new T.ValueSubject(void 0);this.error$=new T.Subject;this.gaps=[];this.subscription=new T.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Le;this.switchAbortController=new Le;this.destroyAbortController=new Le;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(0,T.abortable)(this.destroyAbortController.signal,function(e){return ve(this,null,function*(){let t=this.representations.get(e);(0,T.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new sv(this.sourceBuffer),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,T.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Ve(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,il(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Et(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,T.assertNonNullable)(r,"No init buffer for starting representation"),(0,T.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,T.abortable)(this.destroyAbortController.signal,function(e,t=!1){return ve(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,T.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,T.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!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,T.isNonNullable)(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new hs(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=(0,T.abortable)(this.destroyAbortController.signal,function(e,t=!1){return ve(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,T.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,T.isNullable)(s)||(0,T.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,T.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!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,T.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new hs(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,T.abortable)(this.destroyAbortController.signal,function(e){return ve(this,null,function*(){var u,l;let t=(u=(0,bn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Ce(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);(0,T.assertNonNullable)(i);let s=this.segments.get(r);(0,T.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,T.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.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 Le,(0,T.abortable)(this.switchAbortController.signal,function(r,i=!1){return ve(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,T.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,T.isNullable)(o)||(0,T.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,T.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,T.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!(0,T.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return L(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Le,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,T.isNullable)(e)||(0,T.isNullable)(this.downloadingRepresentationId)||(0,T.isNullable)(this.playingRepresentationId)||(0,T.isNullable)(this.sourceBuffer)||!Ve(this.mediaSource,this.sourceBuffer)||(0,T.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,T.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);(0,T.isNonNullable)(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Et(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)&&il(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Et(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,fn.default)(o,i))l="high";else{let c=(0,hi.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&&Et(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,hi.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,T.isNonNullable)(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,bn.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,bn.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||!Ce(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>_(k({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,hi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,T.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Ce(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=Ot(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&&la&&la(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&la&&la(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let g=p<=r&&h>=r,S=p>r||g||f===0&&r===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&p<=r+I||h<=r+I;return(d==="none"||d==="partially_ejected"&&S&&E&&this.sourceBuffer&&Ve(this.mediaSource,this.sourceBuffer)&&!(ar(this.sourceBuffer.buffered,p)&&ar(this.sourceBuffer.buffered,h)))&&S&&E});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return L(this,null,function*(){Ce(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return L(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield(0,T.abortable)(o,function(){return ve(this,null,function*(){let c=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,T.now)(),!c)return;let d=new DataView(c),p=Va(t.mime);if(!isFinite(i.segment.time.to)){let g=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,g)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ba(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,r="auto"){return L(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield(0,T.abortable)(n,function(){return ve(this,null,function*(){let u=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,T.fromEvent)(window,"online").pipe((0,T.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=(0,T.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ba(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Ce(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,hi.default)(e,0).byte.from,to:(0,hi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>L(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.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:T.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 r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,T.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,fn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return L(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Va(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return L(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,f=d<i,g=p<=i;if(!f)continue;let S=Va(u.mime);if(c.status==="downloading"&&g){c.status="downloaded";let I=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(I,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(h,i-d),l.loadedBytes>l.feedingBytes)){let I=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===h?I:S.parseFeedableSegmentChunk(I);E!=null&&E.byteLength&&(c.status="partially_fed",l.feedingBytes+=E.byteLength,(yield this.sourceBufferTaskQueue.append(E,s))&&!s.aborted?(l.fedBytes+=E.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!((0,T.isNullable)(this.sourceBuffer)||!Ve(this.mediaSource,this.sourceBuffer))){!this.isLive&&T.clientChecker.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(ar(this.sourceBuffer.buffered,e.segment.time.from,100)&&ar(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",fl(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=tl(()=>(0,lS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return L(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?(0,T.abortable)(this.destroyAbortController.signal,function(){return ve(this,null,function*(){let o=(0,T.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Va(e.mime),i)).then(o=>L(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ce(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:T.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return L(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return L(this,null,function*(){if(!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,T.isNullable)(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(k({},u.time)),i=n(i);let l=fl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,fn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return L(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(){let e=this.getCurrentPosition();return!this.sourceBuffer||!Ve(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,T.isNullable)(e)?0:Et(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Ve(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||!Ve(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=tl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:T.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,T.isNullable)(this.sourceBuffer)||!Ve(this.mediaSource,this.sourceBuffer)||(0,T.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:T.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Na=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var cS=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 N=require("@vkontakte/videoplayer-shared/es2015");var dS=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var vn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new N.ValueSubject(void 0);this.lastConnectionReused$=new N.ValueSubject(void 0);this.lastRequestFirstBytes$=new N.ValueSubject(void 0);this.recoverableError$=new N.Subject;this.error$=new N.Subject;this.abortAllController=new Le;this.subscription=new N.Subscription;this.fetchManifest=(0,N.abortable)(this.abortAllController.signal,function(e){return ve(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Na(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=dS(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(gn);return i?(t.log("success",(0,N.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,N.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,N.abortable)(this.abortAllController.signal,function(l){return ve(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 O,ie;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let X=new URL(c,location.href);X.searchParams.append("bytes",`${r.from}-${r.to}`),c=X.toString();break}default:(0,N.assertNever)(t)}this.requestQuic&&(c=Na(c));let h=this.abortAllController.signal,f;if(n){let X=new Le;if(f=(0,N.merge)((0,N.fromEvent)(this.abortAllController.signal,"abort"),(0,N.fromEvent)(n,"abort")).subscribe(()=>{try{X.abort()}catch(ne){gn(ne)}}),this.abortAllController.signal.aborted||n.aborted)try{X.abort()}catch(ne){gn(ne)}h=X.signal}let g=(0,N.now)();p.log("startRequest",(0,N.flattenObject)({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let S=yield this.doFetch(c,{priority:s,headers:d,signal:h}),I=(0,N.now)();if(!S)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(I-g),!S.ok||!S.body){f==null||f.unsubscribe();let X=`Fetch error ${S.status}: ${S.statusText}`;return p.error("error",{message:X}),p.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!i&&!o){f==null||f.unsubscribe();let X=(0,N.now)(),ne={requestStartedAt:g,requestEndedAt:X,duration:X-g};return p.log("endRequest",(0,N.flattenObject)(ne)),p.end(),S.arrayBuffer()}let[E,P]=S.body.tee(),w=E.getReader();o&&((ie=this.throughputEstimator)==null||ie.trackStream(P,u));let A=0,F=new Uint8Array(0),Q=!1,de=X=>{f==null||f.unsubscribe(),Q=!0,gn(X)},H=(0,N.abortable)(h,function(R){return ve(this,arguments,function*({done:X,value:ne}){if(A===0&&this.lastRequestFirstBytes$.next((0,N.now)()-g),h.aborted){f==null||f.unsubscribe();return}if(!X&&ne){let x=new Uint8Array(F.length+ne.length);x.set(F),x.set(ne,F.length),F=x,A+=ne.byteLength,i==null||i(new DataView(F.buffer),A),yield w==null?void 0:w.read().then(H,de)}})}.bind(this));yield w==null?void 0:w.read().then(H,de),f==null||f.unsubscribe();let te=(0,N.now)(),re={failed:Q,requestStartedAt:g,requestEndedAt:te,duration:te-g};return Q?(p.error("endRequest",(0,N.flattenObject)(re)),p.end(),null):(p.log("endRequest",(0,N.flattenObject)(re)),p.end(),F.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,N.abortable)(this.abortAllController.signal,function(e,t,r){return ve(this,null,function*(){var I;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(I=e.indexRange)!=null?I:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,f.from-n,f.to-f.from+1);else{let E=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let S=t.parseSegments(g,h,f);return{init:h,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,N.abortable)(this.abortAllController.signal,function(e,t){return ve(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=>_(k({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=cS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return L(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:(0,N.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return L(this,null,function*(){let r=yield xt(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:N.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:N.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:N.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:N.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:N.ErrorCategory.FATAL})}})}},gn=a=>{if(!Ba(a))throw a};var Ar=(a,e,t)=>t*e+(1-t)*a,yl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,pS=(a,e,t,r)=>{let i=0,s=t,n=yl(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 Fa=require("@vkontakte/videoplayer-shared/es2015");var nr=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 Fa.ValueSubject(e.initial),this.debounced$=new Fa.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+=gt(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,Fa.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 Sn=class extends nr{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ar(this.slow,e,this.params.emaAlphaSlow),this.fast=Ar(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var yn=class extends nr{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=yl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ar(this.emaSmoothed,e,this.params.emaAlpha);let r=pS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Tn=class extends nr{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?Ar(this.smoothed,t,this.params.emaAlpha):t}};var kr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Sn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new yn({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 Tn(k({initial:e,label:"liveEdgeDelay"},t))}};var Tl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var In=require("@vkontakte/videoplayer-shared/es2015");var qa=class a{constructor(e,t){this.currentRepresentation$=new In.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,In.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(_(k({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ce(t.segmentReference))}};var v$=["timeupdate","progress","play","seeked","stalled","waiting"],S$=["timeupdate","progress","loadeddata","playing","seeked"];var En=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 Le;this.initManifest=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return ve(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ke(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:v.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,function(){return ve(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=oS(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=tv(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 r=(u,l,c)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=Ct())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,p=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*p),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";d||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=Dg(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(S=>S.hdr),g=i.video.some(S=>!S.hdr);v.clientChecker.isHDR&&h&&f?i.video=i.video.filter(S=>S.hdr):g&&(i.video=i.video.filter(S=>!S.hdr))}}let s=_(k({},t),{streams:i});return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return ve(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?bg():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&nn())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.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,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new _a("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new _a("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}qa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new qa(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)(...S$.map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?Et(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(h=>this.liveStreamEndTimestamp=(0,v.now)())),this.subscription.add((0,v.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,v.interval)(1e3).subscribe(h=>{let f=zs(this.manifestUrlString,2);this.manifestUrlString=ke(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()})})).add((0,v.fromEvent)(this.element,"play").subscribe(h=>{var f;return(f=this.livePauseWatchdogSubscription)==null?void 0:f.unsubscribe()})),this.representationSubscription.add((0,v.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.map)(({isActiveLive:h,isLowLatency:f})=>h&&f),(0,v.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Tl(this.element,1)})),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLive:f,isLowLatency:g})=>f&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/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:h})=>h),(0,v.filterChanged)((h,f)=>f.bufferLength<h.bufferLength),(0,v.map)(({rtt:h,bufferLength:f,segmentServerLatency:g})=>{let S=zs(this.manifestUrlString,2);return(h/2+f+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,v.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:g})=>{if(!g||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,I=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,P=h-S;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(P)>I&&(w=1+Math.sign(P)*E),Tl(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let f=0;if(h){let I=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;f=Math.min(...this.bufferManagers.map(P=>{var w,A;return(A=(w=P.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?A:I}))-I}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(g=>L(this,[g],function*({liveLoadBufferLength:h,bufferLength:f}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,I=zs(this.manifestUrlString,2),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,F=isFinite(h)?h:f,Q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),de=E<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(de);let H="none";if(Q?H="active_low_latency":this.isLowLatency$.getValue()&&de?(this.bufferManagers.forEach(te=>te.proceedLowLatencyLive()),H="active_low_latency"):I!==0&&F<P?H="live_forward_buffering":F<P+A&&(H="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),H==="live_forward_buffering"||H==="live_with_target_offset"){let te=p-(P+w),re=this.normolizeLiveOffset(Math.trunc(I+te/S)),O=Math.abs(re-I),ie=0;!h||O<=this.tuning.dashCmafLive.offsetCalculationError?ie=I:re>0&&O>this.tuning.dashCmafLive.offsetCalculationError&&(ie=re),this.manifestUrlString=ke(this.manifestUrlString,ie,2)}(H==="live_with_target_offset"||H==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:v.ErrorCategory.VIDEO_PIPELINE,thrown:h,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())));if(this.representationSubscription.add((0,v.merge)(this.forceEnded$,(0,v.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,v.filter)(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),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"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,El.default)((0,El.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Ce(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];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"),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,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new vn({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=kr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,k({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return L(this,null,function*(){var i,s,n;(0,v.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,v.now)()-this.liveStreamEndTimestamp:0,r=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(r===0),this.manifestUrlString=ke(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,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...v$.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&&ar(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,g,S,I,E,P,w,A,F;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=(0,v.now)(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(E=(I=this.videoBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,c=(w=(P=this.audioBufferManager)==null?void 0:P.getForwardBufferDuration())!=null?w:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let Q=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(Q).catch(de=>{this.error$.next({id:"stallIntervalCallback",category:v.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:de})}),i.liveLastOffset=Q}else{let Q=this.element.currentTime*1e3;(A=this.videoBufferManager)==null||A.maintain(Q),(F=this.audioBufferManager)==null||F.maintain(Q),i.position=Q}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return L(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return 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 L(this,null,function*(){var i,s,n,o,u;(0,v.assertNonNullable)(this.element),(0,v.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),ar(this.element.buffered,r)||(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(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:r})))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,v.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 L(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=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=_(k({},r),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,v.flattenObject)(r)))}}};var xn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Pn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/gt(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=k({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*gt(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 mS=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var nl=G(Jt(),1);var _v=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?Xt(s):void 0)!=null?u:(0,_v.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Ov=({id:a,bitrate:e})=>({id:a,bitrate:e}),Nv=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Fv=({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 qv=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},Dt=(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,Uv.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,cl.default)(t,n,(o,u)=>(0,La.isNullable)(s)?o:(0,La.isNullable)(u)?s:(0,Hv.default)(s,parseInt(u,10),"0"))}return t},Qv=(a,e)=>{var J,te,re,_,se,K,ue,C,H,$,Z,W,rt,Ot,kr,ne,Le,Me,_e,it,$r,Nt,sr,Rr,pi,kl,$l,Rl,Ll,Ml,Cl,Dl,Vl,_l,Bl,Ol,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;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(at=>{var ce,nr;return(nr=(ce=at.textContent)==null?void 0:ce.trim())!=null?nr:""}),o=(J=(0,jv.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,S;u&&(S={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,E=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],w=x.reduce((at,ce)=>F(R({},at),{[ce.id]:ce.children}),{}),P=x.reduce((at,ce)=>F(R({},at),{[ce.id]:ce.getAttribute("duration")}),{});E?T=qv(E):(0,dl.default)(P).filter(at=>at).length&&!u?T=(0,dl.default)(P).reduce((at,ce)=>{var nr;return at+((nr=qv(ce))!=null?nr:0)},0):g&&(T=parseInt(g,10));let A=0,U=(re=(te=s.getAttribute("profiles"))==null?void 0:te.split(","))!=null?re:[];for(let at of x.map(ce=>ce.id))for(let ce of w[at]){let nr=(_=ce.getAttribute("id"))!=null?_:"id"+(A++).toString(10),hi=(se=ce.getAttribute("mimeType"))!=null?se:"",An=(K=ce.getAttribute("codecs"))!=null?K:"",kn=(ue=ce.getAttribute("contentType"))!=null?ue:hi==null?void 0:hi.split("/")[0],$S=(H=(C=ce.getAttribute("profiles"))==null?void 0:C.split(","))!=null?H:[],cc=(Z=Vv(($=ce.getAttribute("lang"))!=null?$:""))!=null?Z:{},Ya=(Ot=(rt=(W=ce.querySelector("Label"))==null?void 0:W.textContent)==null?void 0:rt.trim())!=null?Ot:void 0,RS=ce.querySelectorAll("Representation"),LS=ce.querySelector("SegmentTemplate"),MS=(ne=(kr=ce.querySelector("Role"))==null?void 0:kr.getAttribute("value"))!=null?ne:void 0,Lr=kn,ge={id:nr,language:cc.language,isDefault:MS==="main",label:Ya,codecs:An,hdr:Lr==="video"&&al(An),mime:hi,representations:[]};for(let le of RS){let Ft=(Le=le.getAttribute("lang"))!=null?Le:void 0,mi=(_e=(Me=Ya!=null?Ya:ce.getAttribute("label"))!=null?Me:le.getAttribute("label"))!=null?_e:void 0,za=(Nt=($r=(it=le.querySelector("BaseURL"))==null?void 0:it.textContent)==null?void 0:$r.trim())!=null?Nt:"",or=new URL(za||o,e).toString(),qt=(sr=le.getAttribute("mimeType"))!=null?sr:hi,Ka=(pi=(Rr=le.getAttribute("codecs"))!=null?Rr:An)!=null?pi:"",Xa;if(kn==="text"){let Ut=le.getAttribute("id")||"",Ja=((kl=cc.privateuse)==null?void 0:kl.includes("x-auto"))||Ut.includes("_auto"),ur=le.querySelector("SegmentTemplate");if(ur){let fi={representationId:($l=le.getAttribute("id"))!=null?$l:void 0,bandwidth:(Rl=le.getAttribute("bandwidth"))!=null?Rl:void 0},Za=parseInt((Ll=le.getAttribute("bandwidth"))!=null?Ll:"",10)/1e3,es=(Cl=parseInt((Ml=ur.getAttribute("startNumber"))!=null?Ml:"",10))!=null?Cl:1,Mr=parseInt((Dl=ur.getAttribute("timescale"))!=null?Dl:"",10),$n=(Vl=ur.querySelectorAll("SegmentTimeline S"))!=null?Vl:[],Cr=ur.getAttribute("media");if(!Cr)continue;let ts=[],rs=0,is="",Dr=0,bi=es,Ce=0;for(let st of $n){let lr=parseInt((_l=st.getAttribute("d"))!=null?_l:"",10),Ke=parseInt((Bl=st.getAttribute("r"))!=null?Bl:"",10)||0,Ht=parseInt((Ol=st.getAttribute("t"))!=null?Ol:"",10);Ce=Number.isFinite(Ht)?Ht:Ce;let cr=lr/Mr*1e3,jt=Ce/Mr*1e3;for(let mt=0;mt<Ke+1;mt++){let Qt=Dt(Cr,F(R({},fi),{segmentNumber:bi.toString(10),segmentTime:(Ce+mt*lr).toString(10)})),Vr=(jt!=null?jt:0)+mt*cr,vi=Vr+cr;bi++,ts.push({time:{from:Vr,to:vi},url:Qt})}Ce+=(Ke+1)*lr,rs+=(Ke+1)*cr}Dr=Ce/Mr*1e3,is=Dt(Cr,F(R({},fi),{segmentNumber:bi.toString(10),segmentTime:Ce.toString(10)}));let gi={time:{from:Dr,to:1/0},url:is},wt={type:"template",baseUrl:or,segmentTemplateUrl:Cr,initUrl:"",totalSegmentsDurationMs:rs,segments:ts,nextSegmentBeyondManifest:gi,timescale:Mr};Xa={id:Ut,kind:"text",segmentReference:wt,profiles:[],duration:T,bitrate:Za,mime:"",codecs:"",width:0,height:0,isAuto:Ja}}else Xa={id:Ut,isAuto:Ja,kind:"text",url:or}}else{let Ut=(Fl=(Nl=le.getAttribute("contentType"))!=null?Nl:qt==null?void 0:qt.split("/")[0])!=null?Fl:kn,Ja=(Ul=(ql=ce.getAttribute("profiles"))==null?void 0:ql.split(","))!=null?Ul:[],ur=parseInt((Hl=le.getAttribute("width"))!=null?Hl:"",10),fi=parseInt((jl=le.getAttribute("height"))!=null?jl:"",10),Za=parseInt((Ql=le.getAttribute("bandwidth"))!=null?Ql:"",10)/1e3,es=(Gl=le.getAttribute("frameRate"))!=null?Gl:"",Mr=(Wl=le.getAttribute("quality"))!=null?Wl:void 0,$n=es?Dv(es):void 0,Cr=(Yl=le.getAttribute("id"))!=null?Yl:"id"+(A++).toString(10),ts=Ut==="video"?`${fi}p`:Ut==="audio"?`${Za}Kbps`:Ka,rs=`${Cr}@${ts}`,is=[...U,...$S,...Ja],Dr,bi=le.querySelector("SegmentBase"),Ce=(zl=le.querySelector("SegmentTemplate"))!=null?zl:LS;if(bi){let wt=(Xl=(Kl=le.querySelector("SegmentBase Initialization"))==null?void 0:Kl.getAttribute("range"))!=null?Xl:"",[st,lr]=wt.split("-").map(Qt=>parseInt(Qt,10)),Ke={from:st,to:lr},Ht=(Jl=le.querySelector("SegmentBase"))==null?void 0:Jl.getAttribute("indexRange"),[cr,jt]=Ht?Ht.split("-").map(Qt=>parseInt(Qt,10)):[],mt=Ht?{from:cr,to:jt}:void 0;Dr={type:"byteRange",url:or,initRange:Ke,indexRange:mt}}else if(Ce){let wt={representationId:(Zl=le.getAttribute("id"))!=null?Zl:void 0,bandwidth:(ec=le.getAttribute("bandwidth"))!=null?ec:void 0},st=parseInt((tc=Ce.getAttribute("timescale"))!=null?tc:"",10),lr=(rc=Ce.getAttribute("initialization"))!=null?rc:"",Ke=Ce.getAttribute("media"),Ht=(ac=parseInt((ic=Ce.getAttribute("startNumber"))!=null?ic:"",10))!=null?ac:1,cr=Dt(lr,wt);if(!Ke)throw new ReferenceError("No media attribute in SegmentTemplate");let jt=(sc=Ce.querySelectorAll("SegmentTimeline S"))!=null?sc:[],mt=[],Qt=0,Vr="",vi=0;if(jt.length){let as=Ht,nt=0;for(let _r of jt){let ft=parseInt((nc=_r.getAttribute("d"))!=null?nc:"",10),dr=parseInt((oc=_r.getAttribute("r"))!=null?oc:"",10)||0,ss=parseInt((uc=_r.getAttribute("t"))!=null?uc:"",10);nt=Number.isFinite(ss)?ss:nt;let Rn=ft/st*1e3,Ln=nt/st*1e3;for(let ns=0;ns<dr+1;ns++){let DS=Dt(Ke,F(R({},wt),{segmentNumber:as.toString(10),segmentTime:(nt+ns*ft).toString(10)})),dc=(Ln!=null?Ln:0)+ns*Rn,VS=dc+Rn;as++,mt.push({time:{from:dc,to:VS},url:DS})}nt+=(dr+1)*ft,Qt+=(dr+1)*Rn}vi=nt/st*1e3,Vr=Dt(Ke,F(R({},wt),{segmentNumber:as.toString(10),segmentTime:nt.toString(10)}))}else if((0,La.isNonNullable)(T)){let nt=parseInt((lc=Ce.getAttribute("duration"))!=null?lc:"",10)/st*1e3,_r=Math.ceil(T/nt),ft=0;for(let dr=1;dr<_r;dr++){let ss=Dt(Ke,F(R({},wt),{segmentNumber:dr.toString(10),segmentTime:ft.toString(10)}));mt.push({time:{from:ft,to:ft+nt},url:ss}),ft+=nt}vi=ft,Vr=Dt(Ke,F(R({},wt),{segmentNumber:_r.toString(10),segmentTime:ft.toString(10)}))}let CS={time:{from:vi,to:1/0},url:Vr};Dr={type:"template",baseUrl:or,segmentTemplateUrl:Ke,initUrl:cr,totalSegmentsDurationMs:Qt,segments:mt,nextSegmentBeyondManifest:CS,timescale:st}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ut||!qt)continue;let gi={video:"video",audio:"audio",text:"text"}[Ut];if(!gi)continue;Lr||(Lr=gi),Xa={id:rs,kind:gi,segmentReference:Dr,profiles:is,duration:T,bitrate:Za,mime:qt,codecs:Ka,width:ur,height:fi,fps:$n,quality:Mr}}ge.language||(ge.language=Ft),ge.label||(ge.label=mi),ge.mime||(ge.mime=qt),ge.codecs||(ge.codecs=Ka),ge.hdr||(ge.hdr=Lr==="video"&&al(Ka)),ge.representations.push(Xa)}if(Lr){let le=i[Lr].find(Ft=>Ft.id===ge.id);if(le&&ge.representations.every(Ft=>Ve(Ft.segmentReference)))for(let Ft of le.representations){let mi=ge.representations.find(qt=>qt.id===Ft.id),za=mi==null?void 0:mi.segmentReference,or=Ft.segmentReference;or.segments.push(...za.segments),or.nextSegmentBeyondManifest=za.nextSegmentBeyondManifest}else i[Lr].push(ge)}}return{duration:T,streams:i,baseUrls:n,live:S}};var Gv=G(Xe(),1),hl=require("@vkontakte/videoplayer-shared/es2015"),Ee=(a,e)=>(0,hl.isNonNullable)(a)&&(0,hl.isNonNullable)(e)&&a.readyState==="open"&&(0,Gv.default)([...a.activeSourceBuffers],e);var Ma=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new I.ValueSubject(0);this.currentLowLatencySegmentLength$=new I.ValueSubject(0);this.currentSegmentLength$=new I.ValueSubject(0);this.onLastSegment$=new I.ValueSubject(!1);this.fullyBuffered$=new I.ValueSubject(!1);this.playingRepresentation$=new I.ValueSubject(void 0);this.playingRepresentationInit$=new I.ValueSubject(void 0);this.error$=new I.Subject;this.gaps=[];this.subscription=new I.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new 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,I.abortable)(this.destroyAbortController.signal,function(e){return ye(this,null,function*(){let t=this.representations.get(e);(0,I.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hg(this.sourceBuffer),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add((0,I.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Ee(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Xu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Et(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,I.assertNonNullable)(r,"No init buffer for starting representation"),(0,I.assertNonNullable)(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=(0,I.abortable)(this.destroyAbortController.signal,function(e,t=!1){return ye(this,null,function*(){if(!Ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,I.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,I.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Ee(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,I.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,I.abortable)(this.destroyAbortController.signal,function(e,t=!1){return ye(this,null,function*(){if(!Ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);(0,I.assertNonNullable)(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if((0,I.isNullable)(s)||(0,I.isNullable)(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),(0,I.assertNonNullable)(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Ee(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,I.isNonNullable)(n)&&(this.isLive||(this.bufferLimit=1/0,yield new us(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=(0,I.abortable)(this.destroyAbortController.signal,function(e){return ye(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,I.assertNonNullable)(i);let s=this.segments.get(r);(0,I.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(r);if((0,I.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.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){!Ee(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Re,(0,I.abortable)(this.switchAbortController.signal,function(r,i=!1){return ye(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);(0,I.assertNonNullable)(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if((0,I.isNullable)(o)||(0,I.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),(0,I.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Ee(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,I.isNonNullable)(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!(0,I.isNullable)(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}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 Re,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if((0,I.isNullable)(e)||(0,I.isNullable)(this.downloadingRepresentationId)||(0,I.isNullable)(this.playingRepresentationId)||(0,I.isNullable)(this.sourceBuffer)||!Ee(this.mediaSource,this.sourceBuffer)||(0,I.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if((0,I.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(c=>e>=c.time.from&&e<c.time.to);(0,I.isNonNullable)(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Et(this.sourceBuffer.buffered,e),d=i?i.time.to+n:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Xu(this.sourceBuffer.buffered)>=this.bufferLimit){let c=Et(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(r,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,on.default)(u,i))c="high";else{let d=(0,li.default)(u,0);d&&d.time.from-i.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!u.length&&Et(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,li.default)(r,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration()<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;(0,I.isNonNullable)(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,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=>F(R({},m),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,li.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,I.assertNonNullable)(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!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=Dt(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&&ia&&ia(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ia&&ia(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,S=h>r||g||f===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=r+T||m<=r+T;return(d==="none"||d==="partially_ejected"&&S&&E&&this.sourceBuffer&&Ee(this.mediaSource,this.sourceBuffer)&&!(tr(this.sourceBuffer.buffered,h)&&tr(this.sourceBuffer.buffered,m)))&&S&&E});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let 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,I.abortable)(o,function(){return ye(this,null,function*(){let c=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,I.now)(),!c)return;let d=new DataView(c),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,I.abortable)(n,function(){return ye(this,null,function*(){let u=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,I.fromEvent)(window,"online").pipe((0,I.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=(0,I.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),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,li.default)(e,0).byte.from,to:(0,li.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,I.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:I.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,I.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,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 S=$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),E=l.loadedBytes===m?T:S.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(c.status="partially_fed",l.feedingBytes+=E.byteLength,(yield this.sourceBufferTaskQueue.append(E,s))&&!s.aborted?(l.fedBytes+=E.byteLength,l.fedBytes===m&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!((0,I.isNullable)(this.sourceBuffer)||!Ee(this.mediaSource,this.sourceBuffer))){!this.isLive&&ee.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(tr(this.sourceBuffer.buffered,e.segment.time.from,100)&&tr(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:I.ErrorCategory.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",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,Wv.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,I.abortable)(this.destroyAbortController.signal,function(){return ye(this,null,function*(){let o=(0,I.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,$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:I.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||!Ee(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,I.isNullable)(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to: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(R({},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||!Ee(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||!Ee(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||!Ee(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,I.isNullable)(e)?0:Et(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Ee(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||!Ee(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:I.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,I.isNullable)(this.sourceBuffer)||!Ee(this.mediaSource,this.sourceBuffer)||(0,I.isNullable)(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:I.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ca=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Yv=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 q=require("@vkontakte/videoplayer-shared/es2015");var zv=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 q.ValueSubject(void 0);this.lastConnectionReused$=new q.ValueSubject(void 0);this.lastRequestFirstBytes$=new q.ValueSubject(void 0);this.recoverableError$=new q.Subject;this.error$=new q.Subject;this.abortAllController=new Re;this.subscription=new q.Subscription;this.fetchManifest=(0,q.abortable)(this.abortAllController.signal,function(e){return ye(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ca(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=zv(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(ln);return i?(t.log("success",(0,q.flattenObject)({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",(0,q.flattenObject)({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=(0,q.abortable)(this.abortAllController.signal,function(l){return ye(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 _,se;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 K=new URL(c,location.href);K.searchParams.append("bytes",`${r.from}-${r.to}`),c=K.toString();break}default:(0,q.assertNever)(t)}this.requestQuic&&(c=Ca(c));let m=this.abortAllController.signal,f;if(n){let K=new Re;if(f=(0,q.merge)((0,q.fromEvent)(this.abortAllController.signal,"abort"),(0,q.fromEvent)(n,"abort")).subscribe(()=>{try{K.abort()}catch(ue){ln(ue)}}),this.abortAllController.signal.aborted||n.aborted)try{K.abort()}catch(ue){ln(ue)}m=K.signal}let g=(0,q.now)();h.log("startRequest",(0,q.flattenObject)({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:g}));let S=yield this.doFetch(c,{priority:s,headers:d,signal:m}),T=(0,q.now)();if(!S)return h.error("error",{message:"No response in request"}),h.end(),f==null||f.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(T-g),!S.ok||!S.body){f==null||f.unsubscribe();let K=`Fetch error ${S.status}: ${S.statusText}`;return h.error("error",{message:K}),h.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!i&&!o){f==null||f.unsubscribe();let K=(0,q.now)(),ue={requestStartedAt:g,requestEndedAt:K,duration:K-g};return h.log("endRequest",(0,q.flattenObject)(ue)),h.end(),S.arrayBuffer()}let[E,x]=S.body.tee(),w=E.getReader();o&&((se=this.throughputEstimator)==null||se.trackStream(x,u));let P=0,A=new Uint8Array(0),U=!1,oe=K=>{f==null||f.unsubscribe(),U=!0,ln(K)},J=(0,q.abortable)(m,function(C){return ye(this,arguments,function*({done:K,value:ue}){if(P===0&&this.lastRequestFirstBytes$.next((0,q.now)()-g),m.aborted){f==null||f.unsubscribe();return}if(!K&&ue){let H=new Uint8Array(A.length+ue.length);H.set(A),H.set(ue,A.length),A=H,P+=ue.byteLength,i==null||i(new DataView(A.buffer),P),yield w==null?void 0:w.read().then(J,oe)}})}.bind(this));yield w==null?void 0:w.read().then(J,oe),f==null||f.unsubscribe();let te=(0,q.now)(),re={failed:U,requestStartedAt:g,requestEndedAt:te,duration:te-g};return U?(h.error("endRequest",(0,q.flattenObject)(re)),h.end(),null):(h.log("endRequest",(0,q.flattenObject)(re)),h.end(),A.buffer)})}.bind(this));this.fetchByteRangeRepresentation=(0,q.abortable)(this.abortAllController.signal,function(e,t,r){return ye(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 E=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!E)return null;g=new DataView(E)}let S=t.parseSegments(g,m,f);return{init:m,dataView:new DataView(d),segments:S}})}.bind(this));this.fetchTemplateRepresentation=(0,q.abortable)(this.abortAllController.signal,function(e,t){return ye(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>F(R({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=Yv(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,q.assertNever)(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return k(this,null,function*(){let r=yield xt(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:q.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:q.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:q.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:q.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:q.ErrorCategory.FATAL})}})}},ln=a=>{if(!Ra(a))throw a};var xr=(a,e,t)=>t*e+(1-t)*a,ml=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Kv=(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 Da=require("@vkontakte/videoplayer-shared/es2015");var ar=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 Da.ValueSubject(e.initial),this.debounced$=new Da.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+=bt(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,Da.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 ar{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=xr(this.slow,e,this.params.emaAlphaSlow),this.fast=xr(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 ar{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ml(this.pastMeasures,this.takenMeasures);this.emaSmoothed=xr(this.emaSmoothed,e,this.params.emaAlpha);let r=Kv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var hn=class extends ar{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?xr(this.smoothed,t,this.params.emaAlpha):t}};var Pr=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(R({initial:e,label:"liveEdgeDelay"},t))}};var fl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var mn=require("@vkontakte/videoplayer-shared/es2015");var Va=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(F(R({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ve(t.segmentReference))}};var bn=G(Jt(),1);var _a=require("@vkontakte/videoplayer-shared/es2015");var Xv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let{containers:i,protocols:s,codecs:n,nativeHlsSupported:o}=ee.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,_a.assertNever)(c)}})},fn=a=>{let{webmDecodingInfo:e}=ee.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,_a.assertNever)(a)}return[t,r]},Jv=({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(ee.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,_a.assertNever)(e)}return ee.video.nativeHlsSupported?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Zv=({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=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,_a.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"]},bl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],eS=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,bn.default)(t.value.split("."),0)}for(let t of a){let r=(0,bn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,bn.default)(e.value.split("."),0)};var nR=["timeupdate","progress","play","seeked","stalled","waiting"],oR=["timeupdate","progress","loadeddata","playing","seeked"];var gn=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,r){return ye(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=$e(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: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;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Qv(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Ng(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 r=(u,l,c)=>{var d,h,m,f;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((f=(m=dt())==null?void 0:m.isTypeSupported)!=null&&f.call(m,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let m="active";d||(m=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(m)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:m,codecs:f})=>r(u,m,f)),d=new Set(c.map(({codecs:m})=>m)),h=eS(d);if(h&&(i[u]=c.filter(({codecs:m})=>m.startsWith(h))),u==="video"){let m=this.tuning.preferHDR,f=i.video.some(S=>S.hdr),g=i.video.some(S=>!S.hdr);ee.display.isHDR&&m&&f?i.video=i.video.filter(S=>S.hdr):g&&(i.video=i.video.filter(S=>!S.hdr))}}let s=F(R({},t),{streams:i});return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s})}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,function(e,t,r){return ye(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:r})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=m=>{this.representationSubscription.add((0,v.fromEvent)(m,"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?yb():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 m=document.createElement("source");i(m),m.type="application/x-mpegurl",m.src=r.url,this.element.appendChild(m)}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((m,f)=>[...m,...f.representations],[]);if(this.videoBufferManager=new Ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let m=this.manifest.streams.audio.reduce((f,g)=>[...f,...g.representations],[]);this.audioBufferManager=new Ma("audio",this.source,m,n),this.bufferManagers.push(this.audioBufferManager)}Va.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Va(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 m;(m=this.stallWatchdogSubscription)==null||m.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,v.merge)(...oR.map(m=>(0,v.fromEvent)(this.element,m))).pipe((0,v.map)(m=>this.element?Et(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(m=>{m>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=js(this.manifestUrlString,2);this.manifestUrlString=$e(this.manifestUrlString,g+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()})})).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()||fl(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 T=js(this.manifestUrlString,2);return(f/2+g+S+T)/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 T=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,x=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,w=f-T;if(this.isManualDecreasePlaybackInLive())return;let P=1;Math.abs(w)>E&&(P=1+Math.sign(w)*x),fl(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var S,T;let g=0;if(f){let E=((T=(S=this.element)==null?void 0:S.currentTime)!=null?T:0)*1e3;g=Math.min(...this.bufferManagers.map(w=>{var P,A;return(A=(P=w.getLiveSegmentsToLoadState(this.manifest))==null?void 0:P.to)!=null?A:E}))-E}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let m=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(S=>k(this,[S],function*({liveLoadBufferLength:f,bufferLength:g}){if(!this.element||this.isUpdatingLive)return;let T=this.element.playbackRate,E=js(this.manifestUrlString,2),x=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,w=Math.min(x,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*T),P=this.tuning.dashCmafLive.normalizedActualBufferOffset*T,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*T,U=isFinite(f)?f:g,oe=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),J=x<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(J);let te="none";if(oe?te="active_low_latency":this.isLowLatency$.getValue()&&J?(this.bufferManagers.forEach(re=>re.proceedLowLatencyLive()),te="active_low_latency"):E!==0&&U<w?te="live_forward_buffering":U<w+A&&(te="live_with_target_offset"),isFinite(f)&&(m=f>m?f:m),te==="live_forward_buffering"||te==="live_with_target_offset"){let re=m-(w+P),_=this.normolizeLiveOffset(Math.trunc(E+re/T)),se=Math.abs(_-E),K=0;!f||se<=this.tuning.dashCmafLive.offsetCalculationError?K=E:_>0&&se>this.tuning.dashCmafLive.offsetCalculationError&&(K=_),this.manifestUrlString=$e(this.manifestUrlString,K,2)}(te==="live_with_target_offset"||te==="live_forward_buffering")&&(m=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(m=>m.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),c=(0,v.merge)(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue()))),d=(0,v.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,v.filterChanged)(),(0,v.map)(({allBuffersFull:m,someBufferEnded:f})=>m&&f),(0,v.filter)(m=>m));if(this.representationSubscription.add((0,v.merge)(this.forceEnded$,d).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(m=this.source)==null||m.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(m=>m.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(m=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",m)})),!this.isLive$.getValue()){let m=[(h=this.manifest.duration)!=null?h:0,...(0,vl.default)((0,vl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let g=[];return f.duration&&g.push(f.duration),Ve(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&g.push(f.segmentReference.totalSegmentsDurationMs),g})];this.source.duration=Math.max(...m)/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"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i,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),(r=this.audioBufferManager)==null||r.maintain(e),(i=this.liveTextManager)==null||i.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.tracer=e.tracer.createComponentTracer(this.constructor.name),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=Pr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,R({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return k(this,null,function*(){var i,s,n;(0,v.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,v.now)()-this.liveStreamEndTimestamp:0,r=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(r===0),this.manifestUrlString=$e(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,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...nR.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&&tr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var m,f,g,S,T,E,x,w,P,A,U;if(!this.element||((m=this.source)==null?void 0:m.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},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=(T=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?T:0,l=(x=(E=this.videoBufferManager)==null?void 0:E.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,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 oe=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(oe).catch(J=>{this.error$.next({id:"stallIntervalCallback",category:v.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:J})}),i.liveLastOffset=oe}else{let oe=this.element.currentTime*1e3;(A=this.videoBufferManager)==null||A.maintain(oe),(U=this.audioBufferManager)==null||U.maintain(oe),i.position=oe}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:v.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,v.assertNonNullable)(this.element),(0,v.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),this.warmUpMediaSourceIfNeeded(r),tr(this.element.buffered,r)||(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(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:r})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var r;(0,v.isNonNullable)(this.element)&&(0,v.isNonNullable)(this.source)&&(0,v.isNonNullable)(e)&&((r=this.source)==null?void 0:r.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(i=>i.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=(0,v.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=F(R({},r),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",(0,v.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/bt(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=R({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*bt(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 rS=`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 iS=`#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 wn=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 xn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Pn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(mS,this.gl.VERTEX_SHADER),r=this.createShader(fS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Te=require("@vkontakte/videoplayer-shared/es2015"),xl=class{constructor(){this.isSeeked$=new Te.ValueSubject(!1);this.isBuffering$=new Te.ValueSubject(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new Te.Subscription;this.severeStallOccurred$=new Te.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,Te.combine)({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe((0,Te.filter)(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add((0,Te.combine)({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if((0,Te.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,Te.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,Te.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,Te.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},bS=xl;var je=require("@vkontakte/videoplayer-shared/es2015"),An=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 Lr=class{constructor(e){this.subscription=new U.Subscription;this.videoState=new Y("stopped");this.droppedFramesManager=new tn;this.stallsManager=new bS;this.elementSizeManager=new An;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,U.assertNever)(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new wn(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=Oe(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(Ee(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 En({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Fe(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:U.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,U.filter)(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$:r.playing$,pause$:r.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$: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,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(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Tt(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(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();if((0,U.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(hl(h));let f=[];for(let g of h.representations){let S=eS(g);f.push(S),this.audioTracksMap.set(S,{stream:h,representation:g})}this.audioStreamsMap.set(h,f)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(ml(p));let h=[];for(let f of p.representations){let g=Zv(_(k({},f),{streamId:p.id}));g&&(h.push(g),this.videoTracksMap.set(g,{stream:p,representation:f}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let f=tS(p,h);this.textTracksMap.set(f,{stream:p,representation:h})}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())},i)),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(()=>L(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,gS.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,f=[...this.videoTracksMap.keys()].find(S=>{var I;return((I=this.videoTracksMap.get(S))==null?void 0:I.representation.id)===p.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(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),h){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,S)}}),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,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:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(ml(p))},i)),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:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(hl(p))},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(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}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,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,i))}selectVideoAudioRepresentations(){var Q,de,H,te,re,O,ie,X,ne,R,x,G,ae;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:J})=>J===i),o=t.currentVideoTrack$.getValue(),u=((te=(H=e.videoStream.getState())!=null?H:n&&((de=this.videoTracksMap.get(n))==null?void 0:de.stream))!=null?te:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:J})=>J===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Et(this.video.buffered,this.video.currentTime*1e3),p;this.player.isActiveLive$.getValue()?p=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?p=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(p,h||1/0),1),g=(re=e.audioStream.getState())!=null?re:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,S=(O=[...this.audioStreamsMap.keys()].find(({id:J})=>J===(g==null?void 0:g.id)))!=null?O:this.audioStreamsMap.keys().next().value,I=0;if(S){if(n&&!r){let J=Zs(n,c,(ie=this.audioStreamsMap.get(S))!=null?ie:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(X=J==null?void 0:J.bitrate)!=null?X:-1/0)}if(o){let J=Zs(o,c,(ne=this.audioStreamsMap.get(S))!=null?ne:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(R=J==null?void 0:J.bitrate)!=null?R:-1/0)}}let E=ir(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth: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}),P=r?E!=null?E:n:n!=null?n:E,w=S&&_b(P,c,(x=this.audioStreamsMap.get(S))!=null?x:[],{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=(G=this.videoTracksMap.get(P))==null?void 0:G.representation,F=w&&((ae=this.audioTracksMap.get(w))==null?void 0:ae.representation);if(A&&F)return[A,F];if(A&&!F&&this.audioTracksMap.size===0)return[A,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"),$(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),_e(this.video),this.tracer.end()}};var Ua=class extends Lr{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 pe=require("@vkontakte/videoplayer-shared/es2015");var Ha=class extends Lr{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 pe.ValueSubject(1);s(r.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.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)(r.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)(r.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 p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=rS(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 vS=W(Ys(),1);var K=require("@vkontakte/videoplayer-shared/es2015");var mt={};var mi=(a,e)=>new K.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),ja=class{constructor(e){this.subscription=new K.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,K.assertNever)(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:(0,K.assertNever)(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:(0,K.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,K.assertNever)(e)}break;default:(0,K.assertNever)(t)}};this.textTracksManager=new et(e.source.url),this.video=Oe(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(Ee(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),_e(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:K.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,vS.default)(import("hls.js").then(i=>{e||(mt.Hls=i.default,mt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,K.assertNonNullable)(mt.Hls,"hls.js not loaded"),this.hls=new mt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,K.assertNonNullable)(mt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:K.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Fe(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(Tt(this.video,e.isLooped,r)),this.subscription.add(Ne(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,K.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(mi(this.hls,mt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:K.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(mi(this.hls,mt.Events.MANIFEST_PARSED).pipe((0,K.map)(({levels:l})=>l.reduce((c,d)=>{var E,P;let p=d.name||d.height.toString(10),{width:h,height:f}=d,g=(P=er((E=d.attrs.QUALITY)!=null?E:""))!=null?P:(0,K.videoSizeToQuality)({width:h,height:f});if(!g)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,I={id:p.toString(),quality:g,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:S};return this.trackLevels.set(p,{track:I,level:d}),c.push(I),c},[]))),t.availableVideoTracks$),s(mi(this.hls,mt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(mi(this.hls,mt.Events.LEVEL_LOADING).pipe((0,K.map)(({url:l})=>Ee(l))),t.hostname$),s(mi(this.hls,mt.Events.FRAG_CHANGED),l=>{var p,h,f,g;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((g=d==null?void 0:d.startPTS)!=null?g:0))*1e3)}),this.subscription.add(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=mi(this.hls,mt.Events.LEVEL_SWITCHED).pipe((0,K.map)(({level:l})=>n(this.hls.levels[l])));o.pipe((0,K.filter)(K.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Zt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if((0,K.isNullable)(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=(0,K.merge)(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,K.observableFrom)(["init"])).pipe((0,K.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return L(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:K.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 SS="X-Playback-Duration",Pl=a=>L(void 0,null,function*(){var i;let e=yield xt(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(SS)?parseInt(e.headers.get(SS),10):void 0});var z=require("@vkontakte/videoplayer-shared/es2015");var Al=W(jo(),1);var kn=require("@vkontakte/videoplayer-shared/es2015");var E$=a=>{let e=null;if(a.QUALITY&&(e=er(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=(0,kn.videoSizeToQuality)({width:t,height:r})}return e!=null?e:null},x$=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
-
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,
|
|
126
|
-
`),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,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([_(k({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return L(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Le;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return L(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:Xe.ErrorCategory.WTF,thrown:t,message:e})}};var Qa=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 Er;this.manifestStartTime$=new z.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,z.assertNever)(t)}};var r;this.params=e,this.video=Oe(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=(i,s)=>Ln(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 $n(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: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,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:z.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(Ee(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new z.ValueSubject((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:z.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Fe(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(Ne(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,z.filterChanged)(),(0,z.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,z.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Ee(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add((0,z.combine)({startTime:this.manifestStartTime$.pipe((0,z.filter)(z.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,z.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=(0,z.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,z.observableFrom)(["init"])).pipe((0,z.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),_e(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,z.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ke(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Pl(n).then(c=>{var d;if(!(0,z.isNullable)(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,z.isNullable)(p)||!isFinite(p))&&xt(n).then(h=>h.text()).then(h=>{var g;let f=(g=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:g[1];if(f){let S=new URL(f,n).toString();Pl(S).then(I=>{(0,z.isNullable)(I)||this.maxSeekBackTime$.next(I)})}}).catch(()=>{})}})}playIfAllowed(){qe(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:z.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=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 ee=require("@vkontakte/videoplayer-shared/es2015");var Ga=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new Y("stopped");this.manifests$=new ee.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(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,ee.assertNever)(t)}};this.textTracksManager=new et(e.source.url),this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ee.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ee(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ln(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:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:ee.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&(!i||!i.from)&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:ee.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Fe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,ee.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Tt(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(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 h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ee.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(Ee(g.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe((0,ee.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!ee.clientChecker.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,ee.merge)((0,ee.fromEvent)(o,"addtrack"),(0,ee.fromEvent)(o,"removetrack"),(0,ee.fromEvent)(o,"change"),(0,ee.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=(0,ee.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ee.observableFrom)(["init"])).pipe((0,ee.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),_e(this.video)}prepare(){var s,n;let e=this.selectManifest();if((0,ee.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){qe(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:ee.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var TS=W(zr(),1),kl=W(si(),1),IS=W(tr(),1);var ce=require("@vkontakte/videoplayer-shared/es2015");var Wa=class{constructor(e){this.subscription=new ce.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,ce.assertNever)(e)}};this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,TS.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,kl.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:ce.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Fe(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,ce.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Tt(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(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,ce.isNonNullable)(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=(0,ce.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,ce.observableFrom)(["init"])).pipe((0,ce.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),_e(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,ce.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,ce.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Na(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Ee(t))}playIfAllowed(){qe(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:ce.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 p=ir(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(p)},i=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,kl.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Ji({limits:e,lowestAvailableQuality:(c=(0,IS.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?(0,ce.isLowerOrEqual)(i,e.max):!0,u=e.min?(0,ce.isHigherOrEqual)(i,e.min):!0;o&&u||r(e)}};var he=require("@vkontakte/videoplayer-shared/es2015");var xS=require("@vkontakte/videoplayer-shared/es2015");var ES=["stun:videostun.mycdn.me:80"],w$=1e3,A$=3,Ll=()=>null,Rn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Ll;this.externalStopCallback=Ll;this.externalErrorCallback=Ll;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return L(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return L(this,null,function*(){try{let e={iceServers:[{urls:ES}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return L(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return L(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:xS.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return L(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return L(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),w$)}normalizeOptions(e={}){let t={stunServerList:ES,maxRetryNumber:A$,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ya=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(),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,he.assertNever)(e)}};this.subscription=new he.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Oe(e.container,e.tuning),this.liveStreamClient=new Rn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),_e(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:he.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};(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 i=Fe(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(Ne(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,he.assertNever)(n.to)}},r)).add((0,he.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,he.observableFrom)(["init"])).pipe((0,he.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(Ee(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,$(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"),$(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 za=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared/es2015");var _t=require("@vkontakte/videoplayer-shared/es2015"),PS=a=>new _t.Observable(e=>{let t=new _t.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,_t.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,_t.map)(({type:l})=>l!==void 0)),n=new _t.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 at=require("@vkontakte/videoplayer-shared/es2015");function wS(){return new(window.AudioContext||window.webkitAudioContext)}var AS=require("@vkontakte/videoplayer-shared/es2015");var Ka=class Ka{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new Le;this.subscriptions=new at.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,at.filter)(s=>!!s.type),(0,at.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){AS.clientChecker.isSafari&&e!=="MPEG"||this.subscriptions.add((0,at.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,at.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,at.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return L(this,null,function*(){let{volumeMultiplier:t}=this,r=wS();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:Ka.errorId,category:at.ErrorCategory.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ka.errorId} exception`,thrown:e})}};Ka.errorId="VolumeMultiplierManager";var fi=Ka;var k$={chunkDuration:5e3,maxParallelRequests:5},Xa=class{constructor(e){this.current$=new y.ValueSubject({type:void 0});this.providerError$=new y.Subject;this.noAvailableProvidersError$=new y.Subject;this.volumeMultiplierError$=new y.Subject;this.providerOutput={position$:new y.ValueSubject(0),duration$:new y.ValueSubject(1/0),volume$:new y.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new y.ValueSubject([]),currentVideoStream$:new y.ValueSubject(void 0),availableVideoTracks$:new y.ValueSubject([]),currentVideoTrack$:new y.ValueSubject(void 0),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,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=$g([...Mg(this.params.tuning),...Rg(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,$l.default)(i,l)),...t.filter(l=>(0,$l.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new za(s);let n=[...Ku(!0),...Ku(!1)];this.chromecastFormatsIterator=new za(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&&fi.isSupported()&&(this.volumeMultiplierManager=new fi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new Ua(_(k({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ha(_(k({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),li||!this.params.tuning.useHlsJs?new Ga(_(k({},n),{source:o})):new ja(_(k({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Qa(_(k({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Wa(_(k({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Yb(_(k({},n),{source:o,config:_(k({},k$),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ya({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new Ki({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 _(k({},e),{url:r(e.url)})}return(0,LS.default)((0,kS.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))),PS({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=l&&!u&&(o&&t||!c);n=_(k({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var B=require("@vkontakte/videoplayer-shared/es2015");var L$=5e3,$S="one_video_throughput",RS="one_video_rtt",Nt=window.navigator.connection,MS=()=>{let a=Nt==null?void 0:Nt.downlink;if((0,B.isNonNullable)(a)&&a!==10)return a*1e3},DS=()=>{let a=Nt==null?void 0:Nt.rtt;if((0,B.isNonNullable)(a)&&a!==3e3)return a},CS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Rl=class a{constructor(e){this.subscription=new B.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load($S)||(e.useBrowserEstimation?MS():void 0)||L$,r=(s=(i=a.load(RS))!=null?i:e.useBrowserEstimation?DS():void 0)!=null?s:0;if(this.throughput$=new B.ValueSubject(t),this.rtt$=new B.ValueSubject(r),this.rttAdjustedThroughput$=new B.ValueSubject(CS(t,r,e.rttPenaltyRequestSize)),this.throughput=kr.getSmoothedValue(t,-1,e),this.rtt=kr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=MS();u&&this.throughput.next(u);let l=DS();(0,B.isNonNullable)(l)&&this.rtt.next(l)};Nt&&"onchange"in Nt&&this.subscription.add((0,B.fromEvent)(Nt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{B.safeStorage.set($S,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{B.safeStorage.set(RS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,B.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,B.map)(({throughput:n,rtt:o})=>CS(n,o,e.rttPenaltyRequestSize)),(0,B.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,B.now)(),i=new B.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,B.fromEvent)(e,"progress").pipe((0,B.once)()).subscribe(s=>{t=s.loaded,r=(0,B.now)()}));break;case 1:case 0:i.add((0,B.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,B.now)()}));break}i.add((0,B.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,B.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,B.now)(),n=0,o=(0,B.now)(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>L(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,(0,B.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=(0,B.now)();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let g=o-s;g&&this.addRawSpeed(n,g,1,t),n=d.byteLength,s=(0,B.now)()}else n+=d.byteLength;o=(0,B.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,B.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,B.now)()-o,this.concurrentDownloads.size),n=0,o=(0,B.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=B.safeStorage.get(e);if((0,B.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},VS=Rl;var $r=require("@vkontakte/videoplayer-shared/es2015");var BS={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:$r.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:$r.VideoQuality.Q_720P,trafficSavingLimit:$r.VideoQuality.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:$r.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},OS=a=>{var e;return _(k({},(0,$r.fillWithDefault)(a,BS)),{configName:[...(e=a.configName)!=null?e:[],...BS.configName]})};var m=require("@vkontakte/videoplayer-shared/es2015");var Ft=require("@vkontakte/videoplayer-shared/es2015"),Ml=({seekState:a,position$:e})=>(0,Ft.merge)(a.stateChangeEnded$.pipe((0,Ft.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Ft.filter)(Ft.isNonNullable)),e.pipe((0,Ft.filter)(()=>a.getState().state==="none")));var _S=require("@vkontakte/videoplayer-shared/es2015"),NS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,_S.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Mn=require("@vkontakte/videoplayer-shared/es2015"),FS=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe((0,Mn.filter)(i=>i.length>0),(0,Mn.once)()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Ja=class{constructor(e={configName:[]},t=m.Tracer.createRootTracer(!1)){this.subscription=new m.Subscription;this.logger=new m.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new m.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new 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 m.ValueSubject(void 0),position$:new m.ValueSubject(0),duration$:new m.ValueSubject(1/0),muted$:new m.ValueSubject(!1),volume$:new m.ValueSubject(1),availableVideoStreams$:new m.ValueSubject([]),currentVideoStream$:new m.ValueSubject(void 0),availableQualities$:new m.ValueSubject([]),availableQualitiesFps$:new m.ValueSubject({}),currentQuality$:new m.ValueSubject(void 0),isAutoQualityEnabled$:new m.ValueSubject(!0),autoQualityLimitingAvailable$:new m.ValueSubject(!1),autoQualityLimits$:new m.ValueSubject({}),predefinedQualityLimitType$:new m.ValueSubject("unknown"),availableAudioStreams$:new m.ValueSubject([]),currentAudioStream$:new m.ValueSubject(void 0),availableAudioTracks$:new m.ValueSubject([]),isAudioAvailable$:new m.ValueSubject(!0),currentPlaybackRate$:new m.ValueSubject(1),currentBuffer$:new m.ValueSubject({start:0,end:0}),isBuffering$:new m.ValueSubject(!0),isStalled$:new m.ValueSubject(!1),isEnded$:new m.ValueSubject(!1),isLooped$:new m.ValueSubject(!1),isLive$:new m.ValueSubject(void 0),isLiveEnded$:new m.ValueSubject(null),canChangePlaybackSpeed$:new m.ValueSubject(void 0),atLiveEdge$:new m.ValueSubject(void 0),atLiveDurationEdge$:new m.ValueSubject(void 0),liveTime$:new m.ValueSubject(void 0),liveBufferTime$:new m.ValueSubject(void 0),liveLatency$:new m.ValueSubject(void 0),currentFormat$:new m.ValueSubject(void 0),availableTextTracks$:new m.ValueSubject([]),currentTextTrack$:new m.ValueSubject(void 0),throughputEstimation$:new m.ValueSubject(void 0),rttEstimation$:new m.ValueSubject(void 0),videoBitrate$:new m.ValueSubject(void 0),hostname$:new m.ValueSubject(void 0),httpConnectionType$:new m.ValueSubject(void 0),httpConnectionReused$:new m.ValueSubject(void 0),surface$:new m.ValueSubject("none"),chromecastState$:new m.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new m.ValueSubject(void 0),intrinsicVideoSize$:new m.ValueSubject(void 0),availableSources$:new m.ValueSubject(void 0),is3DVideo$:new m.ValueSubject(!1),currentVideoSegmentLength$:new m.ValueSubject(0),currentAudioSegmentLength$:new m.ValueSubject(0)};this.events={inited$:new m.Subject,ready$:new m.Subject,started$:new m.Subject,playing$:new m.Subject,paused$:new m.Subject,stopped$:new m.Subject,willStart$:new m.Subject,willResume$:new m.Subject,willPause$:new m.Subject,willStop$:new m.Subject,willDestruct$:new m.Subject,watchCoverageRecord$:new m.Subject,watchCoverageLive$:new m.Subject,managedError$:new m.Subject,fatalError$:new m.Subject,fetcherRecoverableError$:new m.Subject,ended$:new m.Subject,looped$:new m.Subject,seeked$:new m.Subject,willSeek$:new m.Subject,autoplaySoundProhibited$:new m.Subject,firstBytes$:new m.Subject,loadedMetadata$:new m.Subject,firstFrame$:new m.Subject,canplay$:new m.Subject,log$:new m.Subject,fetcherError$:new m.Subject,severeStallOccured$:new m.Subject};this.experimental={element$:new m.ValueSubject(void 0),tuningConfigName$:new m.ValueSubject([]),enableDebugTelemetry$:new m.ValueSubject(!1),dumpTelemetry:Rb,getCurrentTime$:new m.ValueSubject(null)};if(this.initLogs(),this.tuning=OS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ys({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new VS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new m.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let g=typeof f;return(0,qS.default)(["number","string","boolean"],g)?f:f===null?null:`<${g}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:m.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=Sc(i,["container"]);return this.tracer.log("initVideo",(0,m.flattenObject)(r)),this.domContainer=NS(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Xa({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ia()?(this.tracer.log("request play from hidden tab"),(0,m.fromEvent)(document,"visibilitychange").pipe((0,m.once)()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.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){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e,t){let r=this.desiredState.volume,i=this.info.muted$.getValue(),s=t!=null?t:this.tuning.isAudioDisabled||i;return 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){let t=this.tuning.isAudioDisabled||e,r=this.info.volume$.getValue();return 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.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){(0,m.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,m.filter)(r=>r.length>0),(0,m.once)()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",(0,m.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.setAutoQualityLimits(i),this}setPlaybackRate(e){var r;(0,m.assertNonNullable)(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",(0,m.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>k({type:"external"},t))),this}selectTextTrack(e){var t;return FS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",k({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,m.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return(0,m.isNonNullable)(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,m.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Nu({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.filter)(({from:e})=>e==="stopped"),(0,m.once)()).subscribe(()=>{this.initedAt=(0,m.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,m.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState(_(k({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:m.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,m.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,m.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,m.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,m.map)(n=>n.destination),(0,m.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,m.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,m.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,m.isInvariantQuality)(u)?1:(0,m.isInvariantQuality)(l)?-1:(0,m.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,m.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,m.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,m.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,m.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe((0,m.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,m.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,m.combine)({hasLiveOffsetByPaused:(0,m.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,m.map)(n=>n.to),(0,m.filterChanged)(),(0,m.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,m.combine)({atLiveEdge:(0,m.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ml({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,m.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,m.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,m.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,m.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,m.filterChanged)(),(0,m.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.muted),(0,m.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,m.map)(n=>n.volume),(0,m.filterChanged)()).subscribe(this.info.volume$)).add(Ml({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,m.merge)(e.providerOutput.endedEvent$.pipe((0,m.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,m.mapTo)(!1))).pipe((0,m.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.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,m.map)(n=>({id:n?`No${n}`:"NoProviders",category:m.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,m.once)(),(0,m.map)(n=>n!=null?n:(0,m.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,m.once)(),(0,m.map)(()=>(0,m.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new m.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new m.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.filter)(({to:n})=>n==="playing"),(0,m.once)()).subscribe(()=>r.next(!1)));let i=0,s=(0,m.merge)(e.providerOutput.isBuffering$,t,r).pipe((0,m.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),(0,m.filterChanged)());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add((0,m.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,m.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,m.map)(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new m.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,m.filterChanged)((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,m.filter)(r=>r.length>0),(0,m.once)()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i;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=ir(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,m.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,m.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,m.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;(0,m.assertNonNullable)(this.providerContainer),(0,m.assertNonNullable)(e),$b(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Lb(r)),this.providerContainer.current$.subscribe(({type:r})=>Xi("provider",r)),e.duration$.subscribe(r=>Xi("duration",r)),e.availableVideoTracks$.pipe((0,m.filter)(r=>!!r.length),(0,m.once)()).subscribe(r=>Xi("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,m.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)),Xi("codecs",Lg())}initTracerSubscription(){let e=(0,m.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,m.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,m.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,m.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,m.filter)(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),(0,m.filterChanged)((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,m.filter)(r=>r>0),(0,m.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,m.filter)(r=>r>0),(0,m.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,m.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,m.filter)(r=>r.end>0),(0,m.filterChanged)((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe((0,m.filterChanged)())}).pipe((0,m.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,m.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,m.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,m.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,m.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,m.filter)(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),(0,m.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,m.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,m.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,m.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,m.filter)(({throughputEstimation:r,rtt:i})=>!!r&&!!i),(0,m.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,m.filterChanged)(),(0,m.filter)(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>L(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:m.ErrorCategory.DOM,message:String(i)})})});this.subscription.add((0,m.merge)((0,m.fromEvent)(document,"visibilitychange"),(0,m.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,m.flattenObject)({quality:t,availableTracks:(0,m.flattenObject)(e),track:(0,m.flattenObject)(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};var wt=require("@vkontakte/videoplayer-shared/es2015"),$$=`@vkontakte/videoplayer-core@${Nn}`;
|
|
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(rS,this.gl.VERTEX_SHADER),r=this.createShader(iS,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 Se=require("@vkontakte/videoplayer-shared/es2015"),Sl=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:r})=>t&&!r)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add((0,Se.combine)({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,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=i&&this.currentStallsCount>=i,h=r&&c-this.lastUniqueVideoTrackSelectedTimestamp>=r+o&&c-l>=r+o&&t>=r;(d||h)&&(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()}},aS=Sl;var He=require("@vkontakte/videoplayer-shared/es2015"),Tn=class{constructor(){this.subscription=new He.Subscription;this.pipSize$=new He.ValueSubject(void 0);this.videoSize$=new He.ValueSubject(void 0);this.elementSize$=new He.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=He.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,He.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,He.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,He.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 wr=class{constructor(e){this.subscription=new j.Subscription;this.videoState=new Y("stopped");this.droppedFramesManager=new rn;this.stallsManager=new aS;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 Yi;this.audioTrackSwitchHistory=new Yi;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"),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()):(r==null?void 0:r.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():(r==null?void 0:r.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return(0,j.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 Ze(e.source.url),this.params=e,this.video=Oe(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(Pe(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}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=qe(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:j.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,j.filter)(l=>!!l.length),(0,j.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,j.map)(l=>l.to.state!=="none"),(0,j.filterChanged)());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe((0,j.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$,looped$:r.looped$}),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,j.filter)(j.isNonNullable),(0,j.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,j.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.timeUpdate$.subscribe(l=>{this.video.loop&&this.video.duration-l<.1&&t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(r.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),i)),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Tt(this.video,t.isLooped,i)),this.subscription.add(Fe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Je(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(et(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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();if((0,j.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of c.audio){h.push(ol(m));let f=[];for(let g of m.representations){let S=Ov(g);f.push(S),this.audioTracksMap.set(S,{stream:m,representation:g})}this.audioStreamsMap.set(m,f)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(ul(h));let m=[];for(let f of h.representations){let g=Bv(F(R({},f),{streamId:h.id}));g&&(m.push(g),this.videoTracksMap.set(g,{stream:h,representation:f}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let m of h.representations){let f=Nv(h,m);this.textTracksMap.set(f,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i)),this.subscription.add((0,j.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,j.fromEvent)(this.video,"progress")).subscribe(()=>k(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,sS.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(S=>{var T;return((T=this.videoTracksMap.get(S))==null?void 0:T.representation.id)===h.id});(0,j.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 S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",m.id,S)}}),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,j.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,j.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,j.map)(({to:l})=>l==="ready"),(0,j.filterChanged)());this.subscription.add((0,j.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,j.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,j.merge)(o,this.player.state$.stateChangeEnded$,(0,j.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,j.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,j.observableFrom)(["init"])).pipe((0,j.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var U,oe,J,te,re,_,se,K,ue,C,H,$,Z;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(U=e.videoTrack.getState())==null?void 0:U.id,n=[...this.videoTracksMap.keys()].find(({id:W})=>W===i),o=t.currentVideoTrack$.getValue(),u=((te=(J=e.videoStream.getState())!=null?J:n&&((oe=this.videoTracksMap.get(n))==null?void 0:oe.stream))!=null?te: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=Et(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,S=(_=[...this.audioStreamsMap.keys()].find(({id:W})=>W===(g==null?void 0:g.id)))!=null?_:this.audioStreamsMap.keys().next().value,T=0;if(S){if(n&&!r){let W=en(n,c,(se=this.audioStreamsMap.get(S))!=null?se:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(K=W==null?void 0:W.bitrate)!=null?K:-1/0)}if(o){let W=en(o,c,(ue=this.audioStreamsMap.get(S))!=null?ue:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,(C=W==null?void 0:W.bitrate)!=null?C:-1/0)}}let E=er(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?E!=null?E:n:n!=null?n:E,w=S&&qb(x,c,(H=this.audioStreamsMap.get(S))!=null?H:[],{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=($=this.videoTracksMap.get(x))==null?void 0:$.representation,A=w&&((Z=this.audioTracksMap.get(w))==null?void 0:Z.representation);if(P&&A)return[P,A];if(P&&!A&&this.audioTracksMap.size===0)return[P,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ue(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:j.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),Ne(this.video),this.tracer.end()}};var Ba=class extends wr{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 Oa=class extends wr{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=Fv(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 nS=G(Hs(),1);var X=require("@vkontakte/videoplayer-shared/es2015");var ht={};var ci=(a,e)=>new X.Observable(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Na=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"),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 Ze(e.source.url),this.video=Oe(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(Pe(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),Ne(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,nS.default)(import("hls.js").then(i=>{e||(ht.Hls=i.default,ht.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){(0,X.assertNonNullable)(ht.Hls,"hls.js not loaded"),this.hls=new ht.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){(0,X.assertNonNullable)(ht.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=qe(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(Tt(this.video,e.isLooped,r)),this.subscription.add(Fe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Je(this.video,e.playbackRate,i.playbackRateState$,r)),s(et(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe((0,X.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ci(this.hls,ht.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"),L(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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(ci(this.hls,ht.Events.MANIFEST_PARSED).pipe((0,X.map)(({levels:l})=>l.reduce((c,d)=>{var E,x;let h=d.name||d.height.toString(10),{width:m,height:f}=d,g=(x=Xt((E=d.attrs.QUALITY)!=null?E:""))!=null?x:(0,X.videoSizeToQuality)({width:m,height:f});if(!g)return c;let S=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:S};return this.trackLevels.set(h,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(ci(this.hls,ht.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(ci(this.hls,ht.Events.LEVEL_LOADING).pipe((0,X.map)(({url:l})=>Pe(l))),t.hostname$),s(ci(this.hls,ht.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(Kt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ci(this.hls,ht.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(Kt(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 Ue(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 oS="X-Playback-Duration",yl=a=>k(void 0,null,function*(){var i;let e=yield xt(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(oS)?parseInt(e.headers.get(oS),10):void 0});var z=require("@vkontakte/videoplayer-shared/es2015");var Il=G(Oo(),1);var In=require("@vkontakte/videoplayer-shared/es2015");var dR=a=>{let e=null;if(a.QUALITY&&(e=Xt(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},pR=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
+
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Il.default)(l[1].split(",").map(E=>E.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,m=dR(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[E,x]=d.RESOLUTION.split("x").map(w=>parseInt(w,10));E&&x&&(S={width:E,height:x})}let T=new URL(t[++o],e).toString();m&&r.push({id:h,quality:m,url:T,bandwidth:f,size:S,fps:g})}if(c){let d=(0,Il.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,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),m=d.LANGUAGE,f=d.NAME;h&&m&&i.push({type:"internal",id:m,label:f,language:m,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},hR=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Tl=0,uS=(i,...s)=>k(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield xt(a,r)).text();Tl+=1;try{let{qualityManifests:u,textTracks:l}=pR(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(Tl<=t.manifestRetryMaxCount)return yield hR((0,In.getExponentialDelay)(Tl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),uS(a,e,t)}return{qualityManifests:[],textTracks:[]}}),En=uS;var ze=require("@vkontakte/videoplayer-shared/es2015");var xn=class{constructor(e,t,r,i,s){this.subscription=new ze.Subscription;this.abortControllers={destroy:new Re,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new ze.ValueSubject(null);this.getCurrentTime$=new ze.ValueSubject(null);this.error$=new ze.Subject;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe((0,ze.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 k(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return k(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return k(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield xt(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
|
|
126
|
+
`),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),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,ze.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([F(R({},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 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 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:ze.ErrorCategory.WTF,thrown:t,message:e})}};var Fa=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 Tr;this.manifestStartTime$=new z.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"),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((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"?L(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),L(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"&&L(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"&&(L(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,z.assertNever)(t)}};var r;this.params=e,this.video=Oe(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=(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 Ze(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: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,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:z.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(Pe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new z.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:z.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=qe(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(Fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Je(this.video,t.playbackRate,i.playbackRateState$,r)),s(et(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"),L(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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,z.filterChanged)(),(0,z.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,z.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(Pe(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,z.combine)({startTime:this.manifestStartTime$.pipe((0,z.filter)(z.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,z.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,z.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,z.observableFrom)(["init"])).pipe((0,z.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){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),Ne(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if((0,z.isNullable)(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max: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=$e(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),yl(n).then(c=>{var d;if(!(0,z.isNullable)(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();((0,z.isNullable)(h)||!isFinite(h))&&xt(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 S=new URL(f,n).toString();yl(S).then(T=>{(0,z.isNullable)(T)||this.maxSeekBackTime$.next(T)})}}).catch(()=>{})}})}playIfAllowed(){Ue(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,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=$e(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 qa=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"),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((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?L(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),L(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"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,ae.assertNever)(t)}};this.textTracksManager=new Ze(e.source.url),this.params=e,this.video=Oe(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(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),En($e(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=qe(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(Tt(this.video,t.isLooped,r)),this.subscription.add(Fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Je(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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(S=>S.id===f);g&&(this.params.output.currentVideoTrack$.next(g),this.params.output.hostname$.next(Pe(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)),!ee.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),Ne(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(){Ue(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:ae.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var lS=G(Gr(),1),El=G(ri(),1),cS=G(Jt(),1);var pe=require("@vkontakte/videoplayer-shared/es2015");var Ua=class{constructor(e){this.subscription=new pe.Subscription;this.videoState=new Y("stopped");this.trackUrls={};this.textTracksManager=new Ze;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"),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((r==null?void 0:r.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()):(r==null?void 0:r.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return(0,pe.assertNever)(e)}};this.params=e,this.video=Oe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,lS.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,El.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:pe.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},i=qe(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,pe.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Tt(this.video,t.isLooped,r)),this.subscription.add(Fe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Je(this.video,t.playbackRate,i.playbackRateState$,r)),s(et(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(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,pe.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,pe.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,pe.observableFrom)(["init"])).pipe((0,pe.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),Ne(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;(0,pe.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,pe.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ca(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Pe(t))}playIfAllowed(){Ue(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:pe.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=er(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,El.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Wi({limits:e,lowestAvailableQuality:(c=(0,cS.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?(0,pe.isLowerOrEqual)(i,e.max):!0,u=e.min?(0,pe.isHigherOrEqual)(i,e.min):!0;o&&u||r(e)}};var me=require("@vkontakte/videoplayer-shared/es2015");var pS=require("@vkontakte/videoplayer-shared/es2015");var dS=["stun:videostun.mycdn.me:80"],mR=1e3,fR=3,xl=()=>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=xl;this.externalStopCallback=xl;this.externalErrorCallback=xl;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:dS}]};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:pS.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),mR)}normalizeOptions(e={}){let t={stunServerList:dS,maxRetryNumber:fR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ha=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"),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()):(r==null?void 0:r.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&L(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=Oe(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),Ne(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=qe(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(et(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(Fe(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(Pe(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,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:me.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ue(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:me.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ja=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var y=require("@vkontakte/videoplayer-shared/es2015");var Vt=require("@vkontakte/videoplayer-shared/es2015"),hS=a=>new Vt.Observable(e=>{let t=new Vt.Subscription,r=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Vt.map)(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Vt.map)(({type:l})=>l!==void 0)),n=new Vt.Subject,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var tt=require("@vkontakte/videoplayer-shared/es2015");function mS(){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 Re;this.subscriptions=new tt.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,tt.filter)(s=>!!s.type),(0,tt.once)()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){ee.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,tt.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,tt.filter)(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),(0,tt.once)()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return k(this,null,function*(){let{volumeMultiplier:t}=this,r=mS();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:tt.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 bR={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),availableAudioStreams$:new y.ValueSubject([]),currentAudioStream$:new y.ValueSubject(void 0),availableAudioTracks$:new y.ValueSubject([]),currentVideoSegmentLength$:new y.ValueSubject(0),currentAudioSegmentLength$:new y.ValueSubject(0),isAudioAvailable$:new y.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new y.ValueSubject(!1),autoVideoTrackLimits$:new y.ValueSubject(void 0),currentBuffer$:new y.ValueSubject(void 0),isBuffering$:new y.ValueSubject(!0),error$:new y.Subject,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=Xv([...Zv(this.params.tuning),...Jv(this.params.tuning)],this.params.tuning).filter(l=>(0,y.isNonNullable)(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Pl.default)(i,l)),...t.filter(l=>(0,Pl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,y.flattenObject)(s)),this.screenFormatsIterator=new ja(s);let n=[...bl(!0),...bl(!1)];this.chromecastFormatsIterator=new ja(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()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((0,y.isNullable)(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:y.ErrorCategory.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,y.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,y.assertNonNullable)(o),new Ba(F(R({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Oa(F(R({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),ee.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new qa(F(R({},n),{source:o})):new Na(F(R({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Fa(F(R({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ua(F(R({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Xb(F(R({},n),{source:o,config:F(R({},bR),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,y.assertNonNullable)(o),new Ha({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,y.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,y.assertNonNullable)(o),new Qi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,y.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,y.assertNever)(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return(0,y.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return F(R({},e),{url:r(e.url)})}return(0,bS.default)((0,fS.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))),hS({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=l&&!u&&(o&&t||!c);n=F(R({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",(0,y.flattenObject)(n))})),e}};var N=require("@vkontakte/videoplayer-shared/es2015");var gR=5e3,gS="one_video_throughput",vS="one_video_rtt",_t=window.navigator.connection,SS=()=>{let a=_t==null?void 0:_t.downlink;if((0,N.isNonNullable)(a)&&a!==10)return a*1e3},yS=()=>{let a=_t==null?void 0:_t.rtt;if((0,N.isNonNullable)(a)&&a!==3e3)return a},TS=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},wl=class a{constructor(e){this.subscription=new N.Subscription;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(gS)||(e.useBrowserEstimation?SS():void 0)||gR,r=(s=(i=a.load(vS))!=null?i:e.useBrowserEstimation?yS():void 0)!=null?s:0;if(this.throughput$=new N.ValueSubject(t),this.rtt$=new N.ValueSubject(r),this.rttAdjustedThroughput$=new N.ValueSubject(TS(t,r,e.rttPenaltyRequestSize)),this.throughput=Pr.getSmoothedValue(t,-1,e),this.rtt=Pr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=SS();u&&this.throughput.next(u);let l=yS();(0,N.isNonNullable)(l)&&this.rtt.next(l)};_t&&"onchange"in _t&&this.subscription.add((0,N.fromEvent)(_t,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{N.safeStorage.set(gS,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{N.safeStorage.set(vS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,N.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,N.map)(({throughput:n,rtt:o})=>TS(n,o,e.rttPenaltyRequestSize)),(0,N.filter)(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=(0,N.now)(),i=new N.Subscription;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add((0,N.fromEvent)(e,"progress").pipe((0,N.once)()).subscribe(s=>{t=s.loaded,r=(0,N.now)()}));break;case 1:case 0:i.add((0,N.fromEvent)(e,"loadstart").subscribe(()=>{t=0,r=(0,N.now)()}));break}i.add((0,N.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,N.now)(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=(0,N.now)(),n=0,o=(0,N.now)(),u=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,N.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let m=(0,N.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,N.now)()}else n+=d.byteLength;o=(0,N.now)()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,N.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,N.now)()-o,this.concurrentDownloads.size),n=0,o=(0,N.now)());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=N.safeStorage.get(e);if((0,N.isNonNullable)(t))return(r=parseInt(t,10))!=null?r:void 0}},IS=wl;var Ar=require("@vkontakte/videoplayer-shared/es2015");var ES={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:Ar.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ar.VideoQuality.Q_720P,trafficSavingLimit:Ar.VideoQuality.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ar.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},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},xS=a=>{var e;return F(R({},(0,Ar.fillWithDefault)(a,ES)),{configName:[...(e=a.configName)!=null?e:[],...ES.configName]})};var p=require("@vkontakte/videoplayer-shared/es2015");var Bt=require("@vkontakte/videoplayer-shared/es2015"),Al=({seekState:a,position$:e})=>(0,Bt.merge)(a.stateChangeEnded$.pipe((0,Bt.map)(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),(0,Bt.filter)(Bt.isNonNullable)),e.pipe((0,Bt.filter)(()=>a.getState().state==="none")));var PS=require("@vkontakte/videoplayer-shared/es2015"),wS=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,PS.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var wn=require("@vkontakte/videoplayer-shared/es2015"),AS=(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:Db,getCurrentTime$:new p.ValueSubject(null)};if(this.initLogs(),this.tuning=xS(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 IS(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,kS.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=mc(o,["container"]);this.tracer.log("initVideo",(0,p.flattenObject)(n)),this.domContainer=wS(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?ee.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-1),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=>R({type:"external"},t)))}),this}selectTextTrack(e){return this.playerInited.pipe((0,p.filter)(t=>!!t),(0,p.once)()).subscribe(()=>{var t;AS(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",R({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.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(F(R({},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:Al({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(Al({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=er(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),Cb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Mb(r)),this.providerContainer.current$.subscribe(({type:r})=>Gi("provider",r)),e.duration$.subscribe(r=>Gi("duration",r)),e.availableVideoTracks$.pipe((0,p.filter)(r=>!!r.length),(0,p.once)()).subscribe(r=>Gi("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)),Gi("codecs",ee.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&&!Ji()}};var Pt=require("@vkontakte/videoplayer-shared/es2015"),vR=`@vkontakte/videoplayer-core@${Cn}`;
|