@vkontakte/videoplayer-core 2.0.128-dev.6c63bff4.0 → 2.0.128-dev.d52ca770.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 +24 -24
- package/es2015.esm.js +21 -21
- package/es2018.cjs.js +22 -22
- package/es2018.esm.js +20 -20
- package/esnext.cjs.js +25 -25
- package/esnext.esm.js +22 -22
- package/evergreen.esm.js +20 -20
- package/package.json +2 -2
- package/types/index.d.ts +1 -0
- package/types/player/Player.d.ts +2 -1
- package/types/player/types.d.ts +0 -4
- package/types/providers/DashProvider/baseDashProvider.d.ts +2 -0
- package/types/providers/DashProvider/consts.d.ts +1 -1
- package/types/providers/DashProvider/lib/player.d.ts +4 -7
- package/types/providers/DashProvider/lib/types.d.ts +2 -13
- package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +0 -2
- package/types/providers/types.d.ts +0 -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 +1 -0
package/es2015.esm.js
CHANGED
|
@@ -1,52 +1,52 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.128-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.128-dev.d52ca770.0
|
|
3
|
+
* Wed, 05 Mar 2025 10:42:12 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-128/doc/
|
|
5
5
|
*/
|
|
6
|
-
var fI=Object.create;var lo=Object.defineProperty,bI=Object.defineProperties,gI=Object.getOwnPropertyDescriptor,vI=Object.getOwnPropertyDescriptors,SI=Object.getOwnPropertyNames,fs=Object.getOwnPropertySymbols,yI=Object.getPrototypeOf,co=Object.prototype.hasOwnProperty,Sd=Object.prototype.propertyIsEnumerable;var TI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,vd=(a,e,t)=>e in a?lo(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,x=(a,e)=>{for(var t in e||(e={}))co.call(e,t)&&vd(a,t,e[t]);if(fs)for(var t of fs(e))Sd.call(e,t)&&vd(a,t,e[t]);return a},$=(a,e)=>bI(a,vI(e));var yd=(a,e)=>{var t={};for(var r in a)co.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&fs)for(var r of fs(a))e.indexOf(r)<0&&Sd.call(a,r)&&(t[r]=a[r]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var II=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of SI(e))!co.call(a,i)&&i!==t&&lo(a,i,{get:()=>e[i],enumerable:!(r=gI(e,i))||r.enumerable});return a};var O=(a,e,t)=>(t=a!=null?fI(yI(a)):{},II(e||!a||!a.__esModule?lo(t,"default",{value:a,enumerable:!0}):t,a));var P=(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())}),bs=function(a,e){this[0]=a,this[1]=e},ae=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof bs,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[TI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var ie=f((mo,Id)=>{"use strict";var Ti=function(a){return a&&a.Math===Math&&a};Id.exports=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof global=="object"&&global)||Ti(typeof mo=="object"&&mo)||function(){return this}()||Function("return this")()});var de=f((J0,Ed)=>{"use strict";Ed.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ii=f((Z0,xd)=>{"use strict";var EI=de();xd.exports=!EI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var fo=f((eV,kd)=>{"use strict";var xI=Ii(),Ad=Function.prototype,Pd=Ad.apply,wd=Ad.call;kd.exports=typeof Reflect=="object"&&Reflect.apply||(xI?wd.bind(Pd):function(){return wd.apply(Pd,arguments)})});var ne=f((tV,Rd)=>{"use strict";var Ld=Ii(),$d=Function.prototype,bo=$d.call,PI=Ld&&$d.bind.bind(bo,bo);Rd.exports=Ld?PI:function(a){return function(){return bo.apply(a,arguments)}}});var ir=f((rV,Dd)=>{"use strict";var Md=ne(),wI=Md({}.toString),AI=Md("".slice);Dd.exports=function(a){return AI(wI(a),8,-1)}});var go=f((iV,Cd)=>{"use strict";var kI=ir(),LI=ne();Cd.exports=function(a){if(kI(a)==="Function")return LI(a)}});var te=f((aV,Vd)=>{"use strict";var vo=typeof document=="object"&&document.all;Vd.exports=typeof vo=="undefined"&&vo!==void 0?function(a){return typeof a=="function"||a===vo}:function(a){return typeof a=="function"}});var De=f((sV,Bd)=>{"use strict";var $I=de();Bd.exports=!$I(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ce=f((nV,Od)=>{"use strict";var RI=Ii(),Ss=Function.prototype.call;Od.exports=RI?Ss.bind(Ss):function(){return Ss.apply(Ss,arguments)}});var So=f(Fd=>{"use strict";var _d={}.propertyIsEnumerable,Nd=Object.getOwnPropertyDescriptor,MI=Nd&&!_d.call({1:2},1);Fd.f=MI?function(e){var t=Nd(this,e);return!!t&&t.enumerable}:_d});var Ei=f((uV,qd)=>{"use strict";qd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Hd=f((lV,Ud)=>{"use strict";var DI=ne(),CI=de(),VI=ir(),yo=Object,BI=DI("".split);Ud.exports=CI(function(){return!yo("z").propertyIsEnumerable(0)})?function(a){return VI(a)==="String"?BI(a,""):yo(a)}:yo});var Mr=f((cV,jd)=>{"use strict";jd.exports=function(a){return a==null}});var Dt=f((dV,Qd)=>{"use strict";var OI=Mr(),_I=TypeError;Qd.exports=function(a){if(OI(a))throw new _I("Can't call method on "+a);return a}});var ar=f((pV,Gd)=>{"use strict";var NI=Hd(),FI=Dt();Gd.exports=function(a){return NI(FI(a))}});var Ve=f((hV,Wd)=>{"use strict";var qI=te();Wd.exports=function(a){return typeof a=="object"?a!==null:qI(a)}});var Dr=f((mV,Yd)=>{"use strict";Yd.exports={}});var ht=f((fV,Kd)=>{"use strict";var To=Dr(),Io=ie(),UI=te(),zd=function(a){return UI(a)?a:void 0};Kd.exports=function(a,e){return arguments.length<2?zd(To[a])||zd(Io[a]):To[a]&&To[a][e]||Io[a]&&Io[a][e]}});var xi=f((bV,Xd)=>{"use strict";var HI=ne();Xd.exports=HI({}.isPrototypeOf)});var sr=f((gV,ep)=>{"use strict";var jI=ie(),Jd=jI.navigator,Zd=Jd&&Jd.userAgent;ep.exports=Zd?String(Zd):""});var xo=f((vV,np)=>{"use strict";var sp=ie(),Eo=sr(),tp=sp.process,rp=sp.Deno,ip=tp&&tp.versions||rp&&rp.version,ap=ip&&ip.v8,Ye,ys;ap&&(Ye=ap.split("."),ys=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!ys&&Eo&&(Ye=Eo.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=Eo.match(/Chrome\/(\d+)/),Ye&&(ys=+Ye[1])));np.exports=ys});var Po=f((SV,up)=>{"use strict";var op=xo(),QI=de(),GI=ie(),WI=GI.String;up.exports=!!Object.getOwnPropertySymbols&&!QI(function(){var a=Symbol("symbol detection");return!WI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&op&&op<41})});var wo=f((yV,lp)=>{"use strict";var YI=Po();lp.exports=YI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Ao=f((TV,cp)=>{"use strict";var zI=ht(),KI=te(),XI=xi(),JI=wo(),ZI=Object;cp.exports=JI?function(a){return typeof a=="symbol"}:function(a){var e=zI("Symbol");return KI(e)&&XI(e.prototype,ZI(a))}});var Pi=f((IV,dp)=>{"use strict";var eE=String;dp.exports=function(a){try{return eE(a)}catch(e){return"Object"}}});var at=f((EV,pp)=>{"use strict";var tE=te(),rE=Pi(),iE=TypeError;pp.exports=function(a){if(tE(a))return a;throw new iE(rE(a)+" is not a function")}});var wi=f((xV,hp)=>{"use strict";var aE=at(),sE=Mr();hp.exports=function(a,e){var t=a[e];return sE(t)?void 0:aE(t)}});var fp=f((PV,mp)=>{"use strict";var ko=Ce(),Lo=te(),$o=Ve(),nE=TypeError;mp.exports=function(a,e){var t,r;if(e==="string"&&Lo(t=a.toString)&&!$o(r=ko(t,a))||Lo(t=a.valueOf)&&!$o(r=ko(t,a))||e!=="string"&&Lo(t=a.toString)&&!$o(r=ko(t,a)))return r;throw new nE("Can't convert object to primitive value")}});var ze=f((wV,bp)=>{"use strict";bp.exports=!0});var Sp=f((AV,vp)=>{"use strict";var gp=ie(),oE=Object.defineProperty;vp.exports=function(a,e){try{oE(gp,a,{value:e,configurable:!0,writable:!0})}catch(t){gp[a]=e}return e}});var Ai=f((kV,Ip)=>{"use strict";var uE=ze(),lE=ie(),cE=Sp(),yp="__core-js_shared__",Tp=Ip.exports=lE[yp]||cE(yp,{});(Tp.versions||(Tp.versions=[])).push({version:"3.38.0",mode:uE?"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 Ro=f((LV,xp)=>{"use strict";var Ep=Ai();xp.exports=function(a,e){return Ep[a]||(Ep[a]=e||{})}});var Cr=f(($V,Pp)=>{"use strict";var dE=Dt(),pE=Object;Pp.exports=function(a){return pE(dE(a))}});var Ke=f((RV,wp)=>{"use strict";var hE=ne(),mE=Cr(),fE=hE({}.hasOwnProperty);wp.exports=Object.hasOwn||function(e,t){return fE(mE(e),t)}});var Mo=f((MV,Ap)=>{"use strict";var bE=ne(),gE=0,vE=Math.random(),SE=bE(1 .toString);Ap.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+SE(++gE+vE,36)}});var pe=f((DV,Lp)=>{"use strict";var yE=ie(),TE=Ro(),kp=Ke(),IE=Mo(),EE=Po(),xE=wo(),Vr=yE.Symbol,Do=TE("wks"),PE=xE?Vr.for||Vr:Vr&&Vr.withoutSetter||IE;Lp.exports=function(a){return kp(Do,a)||(Do[a]=EE&&kp(Vr,a)?Vr[a]:PE("Symbol."+a)),Do[a]}});var Dp=f((CV,Mp)=>{"use strict";var wE=Ce(),$p=Ve(),Rp=Ao(),AE=wi(),kE=fp(),LE=pe(),$E=TypeError,RE=LE("toPrimitive");Mp.exports=function(a,e){if(!$p(a)||Rp(a))return a;var t=AE(a,RE),r;if(t){if(e===void 0&&(e="default"),r=wE(t,a,e),!$p(r)||Rp(r))return r;throw new $E("Can't convert object to primitive value")}return e===void 0&&(e="number"),kE(a,e)}});var Co=f((VV,Cp)=>{"use strict";var ME=Dp(),DE=Ao();Cp.exports=function(a){var e=ME(a,"string");return DE(e)?e:e+""}});var Ts=f((BV,Bp)=>{"use strict";var CE=ie(),Vp=Ve(),Vo=CE.document,VE=Vp(Vo)&&Vp(Vo.createElement);Bp.exports=function(a){return VE?Vo.createElement(a):{}}});var Bo=f((OV,Op)=>{"use strict";var BE=De(),OE=de(),_E=Ts();Op.exports=!BE&&!OE(function(){return Object.defineProperty(_E("div"),"a",{get:function(){return 7}}).a!==7})});var Fp=f(Np=>{"use strict";var NE=De(),FE=Ce(),qE=So(),UE=Ei(),HE=ar(),jE=Co(),QE=Ke(),GE=Bo(),_p=Object.getOwnPropertyDescriptor;Np.f=NE?_p:function(e,t){if(e=HE(e),t=jE(t),GE)try{return _p(e,t)}catch(r){}if(QE(e,t))return UE(!FE(qE.f,e,t),e[t])}});var Oo=f((NV,qp)=>{"use strict";var WE=de(),YE=te(),zE=/#|\.prototype\./,ki=function(a,e){var t=XE[KE(a)];return t===ZE?!0:t===JE?!1:YE(e)?WE(e):!!e},KE=ki.normalize=function(a){return String(a).replace(zE,".").toLowerCase()},XE=ki.data={},JE=ki.NATIVE="N",ZE=ki.POLYFILL="P";qp.exports=ki});var Br=f((FV,Hp)=>{"use strict";var Up=go(),ex=at(),tx=Ii(),rx=Up(Up.bind);Hp.exports=function(a,e){return ex(a),e===void 0?a:tx?rx(a,e):function(){return a.apply(e,arguments)}}});var _o=f((qV,jp)=>{"use strict";var ix=De(),ax=de();jp.exports=ix&&ax(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=f((UV,Qp)=>{"use strict";var sx=Ve(),nx=String,ox=TypeError;Qp.exports=function(a){if(sx(a))return a;throw new ox(nx(a)+" is not an object")}});var nr=f(Wp=>{"use strict";var ux=De(),lx=Bo(),cx=_o(),Is=st(),Gp=Co(),dx=TypeError,No=Object.defineProperty,px=Object.getOwnPropertyDescriptor,Fo="enumerable",qo="configurable",Uo="writable";Wp.f=ux?cx?function(e,t,r){if(Is(e),t=Gp(t),Is(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Uo in r&&!r[Uo]){var i=px(e,t);i&&i[Uo]&&(e[t]=r.value,r={configurable:qo in r?r[qo]:i[qo],enumerable:Fo in r?r[Fo]:i[Fo],writable:!1})}return No(e,t,r)}:No:function(e,t,r){if(Is(e),t=Gp(t),Is(r),lx)try{return No(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new dx("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Or=f((jV,Yp)=>{"use strict";var hx=De(),mx=nr(),fx=Ei();Yp.exports=hx?function(a,e,t){return mx.f(a,e,fx(1,t))}:function(a,e,t){return a[e]=t,a}});var se=f((QV,Kp)=>{"use strict";var Li=ie(),bx=fo(),gx=go(),vx=te(),Sx=Fp().f,yx=Oo(),_r=Dr(),Tx=Br(),Nr=Or(),zp=Ke();Ai();var Ix=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 bx(a,this,arguments)};return e.prototype=a.prototype,e};Kp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Li:i?Li[t]:Li[t]&&Li[t].prototype,o=r?_r:_r[t]||Nr(_r,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=yx(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&zp(n,p),m=o[p],c&&(a.dontCallGetSet?(v=Sx(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?g=Tx(h,Li):a.wrap&&c?g=Ix(h):s&&vx(h)?g=gx(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Nr(g,"sham",!0),Nr(o,p,g),s&&(d=t+"Prototype",zp(_r,d)||Nr(_r,d,{}),Nr(_r[d],p,h),a.real&&u&&(l||!u[p])&&Nr(u,p,h)))}});var Jp=f((GV,Xp)=>{"use strict";var Ex=Math.ceil,xx=Math.floor;Xp.exports=Math.trunc||function(e){var t=+e;return(t>0?xx:Ex)(t)}});var $i=f((WV,Zp)=>{"use strict";var Px=Jp();Zp.exports=function(a){var e=+a;return e!==e||e===0?0:Px(e)}});var th=f((YV,eh)=>{"use strict";var wx=$i(),Ax=Math.max,kx=Math.min;eh.exports=function(a,e){var t=wx(a);return t<0?Ax(t+e,0):kx(t,e)}});var Ho=f((zV,rh)=>{"use strict";var Lx=$i(),$x=Math.min;rh.exports=function(a){var e=Lx(a);return e>0?$x(e,9007199254740991):0}});var Fr=f((KV,ih)=>{"use strict";var Rx=Ho();ih.exports=function(a){return Rx(a.length)}});var jo=f((XV,sh)=>{"use strict";var Mx=ar(),Dx=th(),Cx=Fr(),ah=function(a){return function(e,t,r){var i=Mx(e),s=Cx(i);if(s===0)return!a&&-1;var n=Dx(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}};sh.exports={includes:ah(!0),indexOf:ah(!1)}});var Ri=f((JV,nh)=>{"use strict";nh.exports=function(){}});var oh=f(()=>{"use strict";var Vx=se(),Bx=jo().includes,Ox=de(),_x=Ri(),Nx=Ox(function(){return!Array(1).includes()});Vx({target:"Array",proto:!0,forced:Nx},{includes:function(e){return Bx(this,e,arguments.length>1?arguments[1]:void 0)}});_x("includes")});var Ct=f((tB,uh)=>{"use strict";var Fx=ht();uh.exports=Fx});var ch=f((rB,lh)=>{"use strict";oh();var qx=Ct();lh.exports=qx("Array","includes")});var ph=f((iB,dh)=>{"use strict";var Ux=ch();dh.exports=Ux});var Xe=f((aB,hh)=>{"use strict";var Hx=ph();hh.exports=Hx});var Ps=f((bB,Th)=>{"use strict";var Xx=Ro(),Jx=Mo(),yh=Xx("keys");Th.exports=function(a){return yh[a]||(yh[a]=Jx(a))}});var Eh=f((gB,Ih)=>{"use strict";var Zx=de();Ih.exports=!Zx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ws=f((vB,Ph)=>{"use strict";var eP=Ke(),tP=te(),rP=Cr(),iP=Ps(),aP=Eh(),xh=iP("IE_PROTO"),Wo=Object,sP=Wo.prototype;Ph.exports=aP?Wo.getPrototypeOf:function(a){var e=rP(a);if(eP(e,xh))return e[xh];var t=e.constructor;return tP(t)&&e instanceof t?t.prototype:e instanceof Wo?sP:null}});var As=f((SB,wh)=>{"use strict";wh.exports={}});var Lh=f((yB,kh)=>{"use strict";var nP=ne(),Yo=Ke(),oP=ar(),uP=jo().indexOf,lP=As(),Ah=nP([].push);kh.exports=function(a,e){var t=oP(a),r=0,i=[],s;for(s in t)!Yo(lP,s)&&Yo(t,s)&&Ah(i,s);for(;e.length>r;)Yo(t,s=e[r++])&&(~uP(i,s)||Ah(i,s));return i}});var zo=f((TB,$h)=>{"use strict";$h.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ko=f((IB,Rh)=>{"use strict";var cP=Lh(),dP=zo();Rh.exports=Object.keys||function(e){return cP(e,dP)}});var Xo=f((EB,Bh)=>{"use strict";var Dh=De(),pP=de(),Ch=ne(),hP=ws(),mP=Ko(),fP=ar(),bP=So().f,Vh=Ch(bP),gP=Ch([].push),vP=Dh&&pP(function(){var a=Object.create(null);return a[2]=2,!Vh(a,2)}),Mh=function(a){return function(e){for(var t=fP(e),r=mP(t),i=vP&&hP(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Dh||(i?u in t:Vh(t,u)))&&gP(o,a?[u,t[u]]:t[u]);return o}};Bh.exports={entries:Mh(!0),values:Mh(!1)}});var Oh=f(()=>{"use strict";var SP=se(),yP=Xo().entries;SP({target:"Object",stat:!0},{entries:function(e){return yP(e)}})});var Nh=f((wB,_h)=>{"use strict";Oh();var TP=Dr();_h.exports=TP.Object.entries});var qh=f((AB,Fh)=>{"use strict";var IP=Nh();Fh.exports=IP});var qr=f((kB,Uh)=>{"use strict";var EP=qh();Uh.exports=EP});var or=f((LB,Hh)=>{"use strict";Hh.exports={}});var Gh=f(($B,Qh)=>{"use strict";var xP=ie(),PP=te(),jh=xP.WeakMap;Qh.exports=PP(jh)&&/native code/.test(String(jh))});var tu=f((RB,zh)=>{"use strict";var wP=Gh(),Yh=ie(),AP=Ve(),kP=Or(),Jo=Ke(),Zo=Ai(),LP=Ps(),$P=As(),Wh="Object already initialized",eu=Yh.TypeError,RP=Yh.WeakMap,ks,Mi,Ls,MP=function(a){return Ls(a)?Mi(a):ks(a,{})},DP=function(a){return function(e){var t;if(!AP(e)||(t=Mi(e)).type!==a)throw new eu("Incompatible receiver, "+a+" required");return t}};wP||Zo.state?(Je=Zo.state||(Zo.state=new RP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,ks=function(a,e){if(Je.has(a))throw new eu(Wh);return e.facade=a,Je.set(a,e),e},Mi=function(a){return Je.get(a)||{}},Ls=function(a){return Je.has(a)}):(ur=LP("state"),$P[ur]=!0,ks=function(a,e){if(Jo(a,ur))throw new eu(Wh);return e.facade=a,kP(a,ur,e),e},Mi=function(a){return Jo(a,ur)?a[ur]:{}},Ls=function(a){return Jo(a,ur)});var Je,ur;zh.exports={set:ks,get:Mi,has:Ls,enforce:MP,getterFor:DP}});var au=f((MB,Xh)=>{"use strict";var ru=De(),CP=Ke(),Kh=Function.prototype,VP=ru&&Object.getOwnPropertyDescriptor,iu=CP(Kh,"name"),BP=iu&&function(){}.name==="something",OP=iu&&(!ru||ru&&VP(Kh,"name").configurable);Xh.exports={EXISTS:iu,PROPER:BP,CONFIGURABLE:OP}});var Zh=f(Jh=>{"use strict";var _P=De(),NP=_o(),FP=nr(),qP=st(),UP=ar(),HP=Ko();Jh.f=_P&&!NP?Object.defineProperties:function(e,t){qP(e);for(var r=UP(t),i=HP(t),s=i.length,n=0,o;s>n;)FP.f(e,o=i[n++],r[o]);return e}});var su=f((CB,em)=>{"use strict";var jP=ht();em.exports=jP("document","documentElement")});var lu=f((VB,om)=>{"use strict";var QP=st(),GP=Zh(),tm=zo(),WP=As(),YP=su(),zP=Ts(),KP=Ps(),rm=">",im="<",ou="prototype",uu="script",sm=KP("IE_PROTO"),nu=function(){},nm=function(a){return im+uu+rm+a+im+"/"+uu+rm},am=function(a){a.write(nm("")),a.close();var e=a.parentWindow.Object;return a=null,e},XP=function(){var a=zP("iframe"),e="java"+uu+":",t;return a.style.display="none",YP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(nm("document.F=Object")),t.close(),t.F},$s,Rs=function(){try{$s=new ActiveXObject("htmlfile")}catch(e){}Rs=typeof document!="undefined"?document.domain&&$s?am($s):XP():am($s);for(var a=tm.length;a--;)delete Rs[ou][tm[a]];return Rs()};WP[sm]=!0;om.exports=Object.create||function(e,t){var r;return e!==null?(nu[ou]=QP(e),r=new nu,nu[ou]=null,r[sm]=e):r=Rs(),t===void 0?r:GP.f(r,t)}});var Ur=f((BB,um)=>{"use strict";var JP=Or();um.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:JP(a,e,t),a}});var hu=f((OB,dm)=>{"use strict";var ZP=de(),ew=te(),tw=Ve(),rw=lu(),lm=ws(),iw=Ur(),aw=pe(),sw=ze(),pu=aw("iterator"),cm=!1,mt,cu,du;[].keys&&(du=[].keys(),"next"in du?(cu=lm(lm(du)),cu!==Object.prototype&&(mt=cu)):cm=!0);var nw=!tw(mt)||ZP(function(){var a={};return mt[pu].call(a)!==a});nw?mt={}:sw&&(mt=rw(mt));ew(mt[pu])||iw(mt,pu,function(){return this});dm.exports={IteratorPrototype:mt,BUGGY_SAFARI_ITERATORS:cm}});var Ms=f((_B,hm)=>{"use strict";var ow=pe(),uw=ow("toStringTag"),pm={};pm[uw]="z";hm.exports=String(pm)==="[object z]"});var Di=f((NB,mm)=>{"use strict";var lw=Ms(),cw=te(),Ds=ir(),dw=pe(),pw=dw("toStringTag"),hw=Object,mw=Ds(function(){return arguments}())==="Arguments",fw=function(a,e){try{return a[e]}catch(t){}};mm.exports=lw?Ds:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=fw(e=hw(a),pw))=="string"?t:mw?Ds(e):(r=Ds(e))==="Object"&&cw(e.callee)?"Arguments":r}});var bm=f((FB,fm)=>{"use strict";var bw=Ms(),gw=Di();fm.exports=bw?{}.toString:function(){return"[object "+gw(this)+"]"}});var Ci=f((qB,vm)=>{"use strict";var vw=Ms(),Sw=nr().f,yw=Or(),Tw=Ke(),Iw=bm(),Ew=pe(),gm=Ew("toStringTag");vm.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(Tw(i,gm)||Sw(i,gm,{configurable:!0,value:e}),r&&!vw&&yw(i,"toString",Iw))}});var ym=f((UB,Sm)=>{"use strict";var xw=hu().IteratorPrototype,Pw=lu(),ww=Ei(),Aw=Ci(),kw=or(),Lw=function(){return this};Sm.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=Pw(xw,{next:ww(+!r,t)}),Aw(a,i,!1,!0),kw[i]=Lw,a}});var Im=f((HB,Tm)=>{"use strict";var $w=ne(),Rw=at();Tm.exports=function(a,e,t){try{return $w(Rw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var xm=f((jB,Em)=>{"use strict";var Mw=Ve();Em.exports=function(a){return Mw(a)||a===null}});var wm=f((QB,Pm)=>{"use strict";var Dw=xm(),Cw=String,Vw=TypeError;Pm.exports=function(a){if(Dw(a))return a;throw new Vw("Can't set "+Cw(a)+" as a prototype")}});var mu=f((GB,Am)=>{"use strict";var Bw=Im(),Ow=Ve(),_w=Dt(),Nw=wm();Am.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Bw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return _w(i),Nw(s),Ow(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var _m=f((WB,Om)=>{"use strict";var Fw=se(),qw=Ce(),Cs=ze(),Vm=au(),Uw=te(),Hw=ym(),km=ws(),Lm=mu(),jw=Ci(),Qw=Or(),fu=Ur(),Gw=pe(),$m=or(),Bm=hu(),Ww=Vm.PROPER,Yw=Vm.CONFIGURABLE,Rm=Bm.IteratorPrototype,Vs=Bm.BUGGY_SAFARI_ITERATORS,Vi=Gw("iterator"),Mm="keys",Bi="values",Dm="entries",Cm=function(){return this};Om.exports=function(a,e,t,r,i,s,n){Hw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Vs&&v&&v in c)return c[v];switch(v){case Mm:return function(){return new t(this,v)};case Bi:return function(){return new t(this,v)};case Dm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Vi]||c["@@iterator"]||i&&c[i],p=!Vs&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=km(h.call(new a)),m!==Object.prototype&&m.next&&(!Cs&&km(m)!==Rm&&(Lm?Lm(m,Rm):Uw(m[Vi])||fu(m,Vi,Cm)),jw(m,u,!0,!0),Cs&&($m[u]=Cm))),Ww&&i===Bi&&d&&d.name!==Bi&&(!Cs&&Yw?Qw(c,"name",Bi):(l=!0,p=function(){return qw(d,this)})),i)if(b={values:o(Bi),keys:s?p:o(Mm),entries:o(Dm)},n)for(g in b)(Vs||l||!(g in c))&&fu(c,g,b[g]);else Fw({target:e,proto:!0,forced:Vs||l},b);return(!Cs||n)&&c[Vi]!==p&&fu(c,Vi,p,{name:i}),$m[e]=p,b}});var Fm=f((YB,Nm)=>{"use strict";Nm.exports=function(a,e){return{value:a,done:e}}});var gu=f((zB,Qm)=>{"use strict";var zw=ar(),bu=Ri(),qm=or(),Hm=tu(),Kw=nr().f,Xw=_m(),Bs=Fm(),Jw=ze(),Zw=De(),jm="Array Iterator",eA=Hm.set,tA=Hm.getterFor(jm);Qm.exports=Xw(Array,"Array",function(a,e){eA(this,{type:jm,target:zw(a),index:0,kind:e})},function(){var a=tA(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Bs(void 0,!0);switch(a.kind){case"keys":return Bs(t,!1);case"values":return Bs(e[t],!1)}return Bs([t,e[t]],!1)},"values");var Um=qm.Arguments=qm.Array;bu("keys");bu("values");bu("entries");if(!Jw&&Zw&&Um.name!=="values")try{Kw(Um,"name",{value:"values"})}catch(a){}});var Wm=f((KB,Gm)=>{"use strict";var rA=pe(),iA=or(),aA=rA("iterator"),sA=Array.prototype;Gm.exports=function(a){return a!==void 0&&(iA.Array===a||sA[aA]===a)}});var vu=f((XB,zm)=>{"use strict";var nA=Di(),Ym=wi(),oA=Mr(),uA=or(),lA=pe(),cA=lA("iterator");zm.exports=function(a){if(!oA(a))return Ym(a,cA)||Ym(a,"@@iterator")||uA[nA(a)]}});var Xm=f((JB,Km)=>{"use strict";var dA=Ce(),pA=at(),hA=st(),mA=Pi(),fA=vu(),bA=TypeError;Km.exports=function(a,e){var t=arguments.length<2?fA(a):e;if(pA(t))return hA(dA(t,a));throw new bA(mA(a)+" is not iterable")}});var ef=f((ZB,Zm)=>{"use strict";var gA=Ce(),Jm=st(),vA=wi();Zm.exports=function(a,e,t){var r,i;Jm(a);try{if(r=vA(a,"return"),!r){if(e==="throw")throw t;return t}r=gA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Jm(r),t}});var _s=f((eO,sf)=>{"use strict";var SA=Br(),yA=Ce(),TA=st(),IA=Pi(),EA=Wm(),xA=Fr(),tf=xi(),PA=Xm(),wA=vu(),rf=ef(),AA=TypeError,Os=function(a,e){this.stopped=a,this.result=e},af=Os.prototype;sf.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=SA(e,r),l,c,d,p,h,m,b,g=function(S){return l&&rf(l,"normal",S),new Os(!0,S)},v=function(S){return i?(TA(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=wA(a),!c)throw new AA(IA(a)+" is not iterable");if(EA(c)){for(d=0,p=xA(a);p>d;d++)if(h=v(a[d]),h&&tf(af,h))return h;return new Os(!1)}l=PA(a,c)}for(m=s?a.next:l.next;!(b=yA(m,l)).done;){try{h=v(b.value)}catch(S){rf(l,"throw",S)}if(typeof h=="object"&&h&&tf(af,h))return h}return new Os(!1)}});var of=f((tO,nf)=>{"use strict";var kA=De(),LA=nr(),$A=Ei();nf.exports=function(a,e,t){kA?LA.f(a,e,$A(0,t)):a[e]=t}});var uf=f(()=>{"use strict";var RA=se(),MA=_s(),DA=of();RA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return MA(e,function(r,i){DA(t,r,i)},{AS_ENTRIES:!0}),t}})});var cf=f((aO,lf)=>{"use strict";gu();uf();var CA=Dr();lf.exports=CA.Object.fromEntries});var pf=f((sO,df)=>{"use strict";df.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 mf=f(()=>{"use strict";gu();var VA=pf(),BA=ie(),OA=Ci(),hf=or();for(Ns in VA)OA(BA[Ns],Ns),hf[Ns]=hf.Array;var Ns});var bf=f((uO,ff)=>{"use strict";var _A=cf();mf();ff.exports=_A});var Su=f((lO,gf)=>{"use strict";var NA=bf();gf.exports=NA});var vf=f(()=>{"use strict"});var yu=f((pO,Sf)=>{"use strict";var Oi=ie(),FA=sr(),qA=ir(),Fs=function(a){return FA.slice(0,a.length)===a};Sf.exports=function(){return Fs("Bun/")?"BUN":Fs("Cloudflare-Workers")?"CLOUDFLARE":Fs("Deno/")?"DENO":Fs("Node.js/")?"NODE":Oi.Bun&&typeof Bun.version=="string"?"BUN":Oi.Deno&&typeof Deno.version=="object"?"DENO":qA(Oi.process)==="process"?"NODE":Oi.window&&Oi.document?"BROWSER":"REST"}()});var qs=f((hO,yf)=>{"use strict";var UA=yu();yf.exports=UA==="NODE"});var If=f((mO,Tf)=>{"use strict";var HA=nr();Tf.exports=function(a,e,t){return HA.f(a,e,t)}});var Pf=f((fO,xf)=>{"use strict";var jA=ht(),QA=If(),GA=pe(),WA=De(),Ef=GA("species");xf.exports=function(a){var e=jA(a);WA&&e&&!e[Ef]&&QA(e,Ef,{configurable:!0,get:function(){return this}})}});var Af=f((bO,wf)=>{"use strict";var YA=xi(),zA=TypeError;wf.exports=function(a,e){if(YA(e,a))return a;throw new zA("Incorrect invocation")}});var Iu=f((gO,kf)=>{"use strict";var KA=ne(),XA=te(),Tu=Ai(),JA=KA(Function.toString);XA(Tu.inspectSource)||(Tu.inspectSource=function(a){return JA(a)});kf.exports=Tu.inspectSource});var xu=f((vO,Df)=>{"use strict";var ZA=ne(),ek=de(),Lf=te(),tk=Di(),rk=ht(),ik=Iu(),$f=function(){},Rf=rk("Reflect","construct"),Eu=/^\s*(?:class|function)\b/,ak=ZA(Eu.exec),sk=!Eu.test($f),_i=function(e){if(!Lf(e))return!1;try{return Rf($f,[],e),!0}catch(t){return!1}},Mf=function(e){if(!Lf(e))return!1;switch(tk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return sk||!!ak(Eu,ik(e))}catch(t){return!0}};Mf.sham=!0;Df.exports=!Rf||ek(function(){var a;return _i(_i.call)||!_i(Object)||!_i(function(){a=!0})||a})?Mf:_i});var Vf=f((SO,Cf)=>{"use strict";var nk=xu(),ok=Pi(),uk=TypeError;Cf.exports=function(a){if(nk(a))return a;throw new uk(ok(a)+" is not a constructor")}});var Pu=f((yO,Of)=>{"use strict";var Bf=st(),lk=Vf(),ck=Mr(),dk=pe(),pk=dk("species");Of.exports=function(a,e){var t=Bf(a).constructor,r;return t===void 0||ck(r=Bf(t)[pk])?e:lk(r)}});var Nf=f((TO,_f)=>{"use strict";var hk=ne();_f.exports=hk([].slice)});var qf=f((IO,Ff)=>{"use strict";var mk=TypeError;Ff.exports=function(a,e){if(a<e)throw new mk("Not enough arguments");return a}});var wu=f((EO,Uf)=>{"use strict";var fk=sr();Uf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(fk)});var Vu=f((xO,Xf)=>{"use strict";var Be=ie(),bk=fo(),gk=Br(),Hf=te(),vk=Ke(),Kf=de(),jf=su(),Sk=Nf(),Qf=Ts(),yk=qf(),Tk=wu(),Ik=qs(),Mu=Be.setImmediate,Du=Be.clearImmediate,Ek=Be.process,Au=Be.Dispatch,xk=Be.Function,Gf=Be.MessageChannel,Pk=Be.String,ku=0,Ni={},Wf="onreadystatechange",Fi,lr,Lu,$u;Kf(function(){Fi=Be.location});var Cu=function(a){if(vk(Ni,a)){var e=Ni[a];delete Ni[a],e()}},Ru=function(a){return function(){Cu(a)}},Yf=function(a){Cu(a.data)},zf=function(a){Be.postMessage(Pk(a),Fi.protocol+"//"+Fi.host)};(!Mu||!Du)&&(Mu=function(e){yk(arguments.length,1);var t=Hf(e)?e:xk(e),r=Sk(arguments,1);return Ni[++ku]=function(){bk(t,void 0,r)},lr(ku),ku},Du=function(e){delete Ni[e]},Ik?lr=function(a){Ek.nextTick(Ru(a))}:Au&&Au.now?lr=function(a){Au.now(Ru(a))}:Gf&&!Tk?(Lu=new Gf,$u=Lu.port2,Lu.port1.onmessage=Yf,lr=gk($u.postMessage,$u)):Be.addEventListener&&Hf(Be.postMessage)&&!Be.importScripts&&Fi&&Fi.protocol!=="file:"&&!Kf(zf)?(lr=zf,Be.addEventListener("message",Yf,!1)):Wf in Qf("script")?lr=function(a){jf.appendChild(Qf("script"))[Wf]=function(){jf.removeChild(this),Cu(a)}}:lr=function(a){setTimeout(Ru(a),0)});Xf.exports={set:Mu,clear:Du}});var eb=f((PO,Zf)=>{"use strict";var Jf=ie(),wk=De(),Ak=Object.getOwnPropertyDescriptor;Zf.exports=function(a){if(!wk)return Jf[a];var e=Ak(Jf,a);return e&&e.value}});var Bu=f((wO,rb)=>{"use strict";var tb=function(){this.head=null,this.tail=null};tb.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}}};rb.exports=tb});var ab=f((AO,ib)=>{"use strict";var kk=sr();ib.exports=/ipad|iphone|ipod/i.test(kk)&&typeof Pebble!="undefined"});var nb=f((kO,sb)=>{"use strict";var Lk=sr();sb.exports=/web0s(?!.*chrome)/i.test(Lk)});var hb=f((LO,pb)=>{"use strict";var jr=ie(),$k=eb(),ob=Br(),Ou=Vu().set,Rk=Bu(),Mk=wu(),Dk=ab(),Ck=nb(),_u=qs(),ub=jr.MutationObserver||jr.WebKitMutationObserver,lb=jr.document,cb=jr.process,Us=jr.Promise,qu=$k("queueMicrotask"),Hr,Nu,Fu,Hs,db;qu||(qi=new Rk,Ui=function(){var a,e;for(_u&&(a=cb.domain)&&a.exit();e=qi.get();)try{e()}catch(t){throw qi.head&&Hr(),t}a&&a.enter()},!Mk&&!_u&&!Ck&&ub&&lb?(Nu=!0,Fu=lb.createTextNode(""),new ub(Ui).observe(Fu,{characterData:!0}),Hr=function(){Fu.data=Nu=!Nu}):!Dk&&Us&&Us.resolve?(Hs=Us.resolve(void 0),Hs.constructor=Us,db=ob(Hs.then,Hs),Hr=function(){db(Ui)}):_u?Hr=function(){cb.nextTick(Ui)}:(Ou=ob(Ou,jr),Hr=function(){Ou(Ui)}),qu=function(a){qi.head||Hr(),qi.add(a)});var qi,Ui;pb.exports=qu});var fb=f(($O,mb)=>{"use strict";mb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var js=f((RO,bb)=>{"use strict";bb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var cr=f((MO,gb)=>{"use strict";var Vk=ie();gb.exports=Vk.Promise});var Qr=f((DO,Tb)=>{"use strict";var Bk=ie(),Hi=cr(),Ok=te(),_k=Oo(),Nk=Iu(),Fk=pe(),vb=yu(),qk=ze(),Uu=xo(),Sb=Hi&&Hi.prototype,Uk=Fk("species"),Hu=!1,yb=Ok(Bk.PromiseRejectionEvent),Hk=_k("Promise",function(){var a=Nk(Hi),e=a!==String(Hi);if(!e&&Uu===66||qk&&!(Sb.catch&&Sb.finally))return!0;if(!Uu||Uu<51||!/native code/.test(a)){var t=new Hi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Uk]=r,Hu=t.then(function(){})instanceof r,!Hu)return!0}return!e&&(vb==="BROWSER"||vb==="DENO")&&!yb});Tb.exports={CONSTRUCTOR:Hk,REJECTION_EVENT:yb,SUBCLASSING:Hu}});var Gr=f((CO,Eb)=>{"use strict";var Ib=at(),jk=TypeError,Qk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new jk("Bad Promise constructor");e=r,t=i}),this.resolve=Ib(e),this.reject=Ib(t)};Eb.exports.f=function(a){return new Qk(a)}});var Ub=f(()=>{"use strict";var Gk=se(),Wk=ze(),Ys=qs(),Vt=ie(),Kr=Ce(),xb=Ur(),Pb=mu(),Yk=Ci(),zk=Pf(),Kk=at(),Ws=te(),Xk=Ve(),Jk=Af(),Zk=Pu(),$b=Vu().set,Yu=hb(),eL=fb(),tL=js(),rL=Bu(),Rb=tu(),zs=cr(),zu=Qr(),Mb=Gr(),Ks="Promise",Db=zu.CONSTRUCTOR,iL=zu.REJECTION_EVENT,aL=zu.SUBCLASSING,ju=Rb.getterFor(Ks),sL=Rb.set,Wr=zs&&zs.prototype,dr=zs,Qs=Wr,Cb=Vt.TypeError,Qu=Vt.document,Ku=Vt.process,Gu=Mb.f,nL=Gu,oL=!!(Qu&&Qu.createEvent&&Vt.dispatchEvent),Vb="unhandledrejection",uL="rejectionhandled",wb=0,Bb=1,lL=2,Xu=1,Ob=2,Gs,Ab,cL,kb,_b=function(a){var e;return Xk(a)&&Ws(e=a.then)?e:!1},Nb=function(a,e){var t=e.value,r=e.state===Bb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Ob&&pL(e),e.rejection=Xu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Cb("Promise-chain cycle")):(l=_b(u))?Kr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Fb=function(a,e){a.notified||(a.notified=!0,Yu(function(){for(var t=a.reactions,r;r=t.get();)Nb(r,a);a.notified=!1,e&&!a.rejection&&dL(a)}))},qb=function(a,e,t){var r,i;oL?(r=Qu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Vt.dispatchEvent(r)):r={promise:e,reason:t},!iL&&(i=Vt["on"+a])?i(r):a===Vb&&eL("Unhandled promise rejection",t)},dL=function(a){Kr($b,Vt,function(){var e=a.facade,t=a.value,r=Lb(a),i;if(r&&(i=tL(function(){Ys?Ku.emit("unhandledRejection",t,e):qb(Vb,e,t)}),a.rejection=Ys||Lb(a)?Ob:Xu,i.error))throw i.value})},Lb=function(a){return a.rejection!==Xu&&!a.parent},pL=function(a){Kr($b,Vt,function(){var e=a.facade;Ys?Ku.emit("rejectionHandled",e):qb(uL,e,a.value)})},Yr=function(a,e,t){return function(r){a(e,r,t)}},zr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=lL,Fb(a,!0))},Wu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Cb("Promise can't be resolved itself");var r=_b(e);r?Yu(function(){var i={done:!1};try{Kr(r,e,Yr(Wu,i,a),Yr(zr,i,a))}catch(s){zr(i,s,a)}}):(a.value=e,a.state=Bb,Fb(a,!1))}catch(i){zr({done:!1},i,a)}}};if(Db&&(dr=function(e){Jk(this,Qs),Kk(e),Kr(Gs,this);var t=ju(this);try{e(Yr(Wu,t),Yr(zr,t))}catch(r){zr(t,r)}},Qs=dr.prototype,Gs=function(e){sL(this,{type:Ks,done:!1,notified:!1,parent:!1,reactions:new rL,rejection:!1,state:wb,value:void 0})},Gs.prototype=xb(Qs,"then",function(e,t){var r=ju(this),i=Gu(Zk(this,dr));return r.parent=!0,i.ok=Ws(e)?e:!0,i.fail=Ws(t)&&t,i.domain=Ys?Ku.domain:void 0,r.state===wb?r.reactions.add(i):Yu(function(){Nb(i,r)}),i.promise}),Ab=function(){var a=new Gs,e=ju(a);this.promise=a,this.resolve=Yr(Wu,e),this.reject=Yr(zr,e)},Mb.f=Gu=function(a){return a===dr||a===cL?new Ab(a):nL(a)},!Wk&&Ws(zs)&&Wr!==Object.prototype)){kb=Wr.then,aL||xb(Wr,"then",function(e,t){var r=this;return new dr(function(i,s){Kr(kb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Wr.constructor}catch(a){}Pb&&Pb(Wr,Qs)}Gk({global:!0,constructor:!0,wrap:!0,forced:Db},{Promise:dr});Yk(dr,Ks,!1,!0);zk(Ks)});var Wb=f((OO,Gb)=>{"use strict";var hL=pe(),jb=hL("iterator"),Qb=!1;try{Hb=0,Ju={next:function(){return{done:!!Hb++}},return:function(){Qb=!0}},Ju[jb]=function(){return this},Array.from(Ju,function(){throw 2})}catch(a){}var Hb,Ju;Gb.exports=function(a,e){try{if(!e&&!Qb)return!1}catch(i){return!1}var t=!1;try{var r={};r[jb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Zu=f((_O,Yb)=>{"use strict";var mL=cr(),fL=Wb(),bL=Qr().CONSTRUCTOR;Yb.exports=bL||!fL(function(a){mL.all(a).then(void 0,function(){})})});var zb=f(()=>{"use strict";var gL=se(),vL=Ce(),SL=at(),yL=Gr(),TL=js(),IL=_s(),EL=Zu();gL({target:"Promise",stat:!0,forced:EL},{all:function(e){var t=this,r=yL.f(t),i=r.resolve,s=r.reject,n=TL(function(){var o=SL(t.resolve),u=[],l=0,c=1;IL(e,function(d){var p=l++,h=!1;c++,vL(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Xb=f(()=>{"use strict";var xL=se(),PL=ze(),wL=Qr().CONSTRUCTOR,tl=cr(),AL=ht(),kL=te(),LL=Ur(),Kb=tl&&tl.prototype;xL({target:"Promise",proto:!0,forced:wL,real:!0},{catch:function(a){return this.then(void 0,a)}});!PL&&kL(tl)&&(el=AL("Promise").prototype.catch,Kb.catch!==el&&LL(Kb,"catch",el,{unsafe:!0}));var el});var Jb=f(()=>{"use strict";var $L=se(),RL=Ce(),ML=at(),DL=Gr(),CL=js(),VL=_s(),BL=Zu();$L({target:"Promise",stat:!0,forced:BL},{race:function(e){var t=this,r=DL.f(t),i=r.reject,s=CL(function(){var n=ML(t.resolve);VL(e,function(o){RL(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Zb=f(()=>{"use strict";var OL=se(),_L=Gr(),NL=Qr().CONSTRUCTOR;OL({target:"Promise",stat:!0,forced:NL},{reject:function(e){var t=_L.f(this),r=t.reject;return r(e),t.promise}})});var rl=f((WO,eg)=>{"use strict";var FL=st(),qL=Ve(),UL=Gr();eg.exports=function(a,e){if(FL(a),qL(e)&&e.constructor===a)return e;var t=UL.f(a),r=t.resolve;return r(e),t.promise}});var ig=f(()=>{"use strict";var HL=se(),jL=ht(),tg=ze(),QL=cr(),rg=Qr().CONSTRUCTOR,GL=rl(),WL=jL("Promise"),YL=tg&&!rg;HL({target:"Promise",stat:!0,forced:tg||rg},{resolve:function(e){return GL(YL&&this===WL?QL:this,e)}})});var ag=f(()=>{"use strict";Ub();zb();Xb();Jb();Zb();ig()});var ug=f(()=>{"use strict";var zL=se(),KL=ze(),Xs=cr(),XL=de(),ng=ht(),og=te(),JL=Pu(),sg=rl(),ZL=Ur(),al=Xs&&Xs.prototype,e$=!!Xs&&XL(function(){al.finally.call({then:function(){}},function(){})});zL({target:"Promise",proto:!0,real:!0,forced:e$},{finally:function(a){var e=JL(this,ng("Promise")),t=og(a);return this.then(t?function(r){return sg(e,a()).then(function(){return r})}:a,t?function(r){return sg(e,a()).then(function(){throw r})}:a)}});!KL&&og(Xs)&&(il=ng("Promise").prototype.finally,al.finally!==il&&ZL(al,"finally",il,{unsafe:!0}));var il});var cg=f((e_,lg)=>{"use strict";vf();ag();ug();var t$=Ct();lg.exports=t$("Promise","finally")});var pg=f((t_,dg)=>{"use strict";var r$=cg();dg.exports=r$});var Js=f((r_,hg)=>{"use strict";var i$=pg();hg.exports=i$});var wg=f(()=>{"use strict";var g$=se(),v$=Xo().values;g$({target:"Object",stat:!0},{values:function(e){return v$(e)}})});var kg=f((F_,Ag)=>{"use strict";wg();var S$=Dr();Ag.exports=S$.Object.values});var $g=f((q_,Lg)=>{"use strict";var y$=kg();Lg.exports=y$});var Jr=f((U_,Rg)=>{"use strict";var T$=$g();Rg.exports=T$});var jg=f(()=>{"use strict";var O$=se(),_$=Cr(),N$=Fr(),F$=$i(),q$=Ri();O$({target:"Array",proto:!0},{at:function(e){var t=_$(this),r=N$(t),i=F$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});q$("at")});var Gg=f((bN,Qg)=>{"use strict";jg();var U$=Ct();Qg.exports=U$("Array","at")});var Yg=f((gN,Wg)=>{"use strict";var H$=Gg();Wg.exports=H$});var Ft=f((vN,zg)=>{"use strict";var j$=Yg();zg.exports=j$});var Al=f((aq,$v)=>{"use strict";var AR=ir();$v.exports=Array.isArray||function(e){return AR(e)==="Array"}});var Mv=f((sq,Rv)=>{"use strict";var kR=TypeError,LR=9007199254740991;Rv.exports=function(a){if(a>LR)throw kR("Maximum allowed index exceeded");return a}});var Vv=f((nq,Cv)=>{"use strict";var $R=Al(),RR=Fr(),MR=Mv(),DR=Br(),Dv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?DR(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&$R(d)?(p=RR(d),u=Dv(a,e,d,p,u,s-1)-1):(MR(u+1),a[u]=d),u++),l++;return u};Cv.exports=Dv});var Nv=f((oq,_v)=>{"use strict";var Bv=Al(),CR=xu(),VR=Ve(),BR=pe(),OR=BR("species"),Ov=Array;_v.exports=function(a){var e;return Bv(a)&&(e=a.constructor,CR(e)&&(e===Ov||Bv(e.prototype))?e=void 0:VR(e)&&(e=e[OR],e===null&&(e=void 0))),e===void 0?Ov:e}});var qv=f((uq,Fv)=>{"use strict";var _R=Nv();Fv.exports=function(a,e){return new(_R(a))(e===0?0:e)}});var Uv=f(()=>{"use strict";var NR=se(),FR=Vv(),qR=at(),UR=Cr(),HR=Fr(),jR=qv();NR({target:"Array",proto:!0},{flatMap:function(e){var t=UR(this),r=HR(t),i;return qR(e),i=jR(t,0),i.length=FR(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Hv=f(()=>{"use strict";var QR=Ri();QR("flatMap")});var Qv=f((hq,jv)=>{"use strict";Uv();Hv();var GR=Ct();jv.exports=GR("Array","flatMap")});var Wv=f((mq,Gv)=>{"use strict";var WR=Qv();Gv.exports=WR});var kl=f((fq,Yv)=>{"use strict";var YR=Wv();Yv.exports=YR});var sa=f((wq,mS)=>{"use strict";var rM=Di(),iM=String;mS.exports=function(a){if(rM(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return iM(a)}});var $l=f((Aq,fS)=>{"use strict";fS.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 vS=f((kq,gS)=>{"use strict";var aM=ne(),sM=Dt(),nM=sa(),Ml=$l(),bS=aM("".replace),oM=RegExp("^["+Ml+"]+"),uM=RegExp("(^|[^"+Ml+"])["+Ml+"]+$"),Rl=function(a){return function(e){var t=nM(sM(e));return a&1&&(t=bS(t,oM,"")),a&2&&(t=bS(t,uM,"$1")),t}};gS.exports={start:Rl(1),end:Rl(2),trim:Rl(3)}});var IS=f((Lq,TS)=>{"use strict";var lM=au().PROPER,cM=de(),SS=$l(),yS="\u200B\x85\u180E";TS.exports=function(a){return cM(function(){return!!SS[a]()||yS[a]()!==yS||lM&&SS[a].name!==a})}});var Dl=f(($q,ES)=>{"use strict";var dM=vS().start,pM=IS();ES.exports=pM("trimStart")?function(){return dM(this)}:"".trimStart});var PS=f(()=>{"use strict";var hM=se(),xS=Dl();hM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==xS},{trimLeft:xS})});var AS=f(()=>{"use strict";PS();var mM=se(),wS=Dl();mM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==wS},{trimStart:wS})});var LS=f((Vq,kS)=>{"use strict";AS();var fM=Ct();kS.exports=fM("String","trimLeft")});var RS=f((Bq,$S)=>{"use strict";var bM=LS();$S.exports=bM});var DS=f((Oq,MS)=>{"use strict";var gM=RS();MS.exports=gM});var zS=f(()=>{"use strict"});var KS=f(()=>{"use strict"});var JS=f((SH,XS)=>{"use strict";var FM=Ve(),qM=ir(),UM=pe(),HM=UM("match");XS.exports=function(a){var e;return FM(a)&&((e=a[HM])!==void 0?!!e:qM(a)==="RegExp")}});var ey=f((yH,ZS)=>{"use strict";var jM=st();ZS.exports=function(){var a=jM(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 iy=f((TH,ry)=>{"use strict";var QM=Ce(),GM=Ke(),WM=xi(),YM=ey(),ty=RegExp.prototype;ry.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in ty)&&!GM(a,"flags")&&WM(ty,a)?QM(YM,a):e}});var sy=f((IH,ay)=>{"use strict";var Ul=ne(),zM=Cr(),KM=Math.floor,Fl=Ul("".charAt),XM=Ul("".replace),ql=Ul("".slice),JM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,ZM=/\$([$&'`]|\d{1,2})/g;ay.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=ZM;return i!==void 0&&(i=zM(i),u=JM),XM(s,u,function(l,c){var d;switch(Fl(c,0)){case"$":return"$";case"&":return a;case"`":return ql(e,0,t);case"'":return ql(e,n);case"<":d=i[ql(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=KM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Fl(c,1):r[h-1]+Fl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var uy=f(()=>{"use strict";var eD=se(),tD=Ce(),jl=ne(),ny=Dt(),rD=te(),iD=Mr(),aD=JS(),si=sa(),sD=wi(),nD=iy(),oD=sy(),uD=pe(),lD=ze(),cD=uD("replace"),dD=TypeError,Hl=jl("".indexOf),pD=jl("".replace),oy=jl("".slice),hD=Math.max;eD({target:"String",proto:!0},{replaceAll:function(e,t){var r=ny(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!iD(e)){if(i=aD(e),i&&(s=si(ny(nD(e))),!~Hl(s,"g")))throw new dD("`.replaceAll` does not allow non-global regexes");if(n=sD(e,cD),n)return tD(n,e,r,t);if(lD&&i)return pD(si(r),e,t)}for(o=si(r),u=si(e),l=rD(t),l||(t=si(t)),c=u.length,d=hD(1,c),p=Hl(o,u);p!==-1;)h=l?si(t(u,p,o)):oD(u,o,p,[],void 0,t),b+=oy(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Hl(o,u,p+d);return m<o.length&&(b+=oy(o,m)),b}})});var cy=f((PH,ly)=>{"use strict";zS();KS();uy();var mD=Ct();ly.exports=mD("String","replaceAll")});var py=f((wH,dy)=>{"use strict";var fD=cy();dy.exports=fD});var my=f((AH,hy)=>{"use strict";var bD=py();hy.exports=bD});var by=f((kH,fy)=>{"use strict";var gD=$i(),vD=sa(),SD=Dt(),yD=RangeError;fy.exports=function(e){var t=vD(SD(this)),r="",i=gD(e);if(i<0||i===1/0)throw new yD("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var Ty=f((LH,yy)=>{"use strict";var Sy=ne(),TD=Ho(),gy=sa(),ID=by(),ED=Dt(),xD=Sy(ID),PD=Sy("".slice),wD=Math.ceil,vy=function(a){return function(e,t,r){var i=gy(ED(e)),s=TD(t),n=i.length,o=r===void 0?" ":gy(r),u,l;return s<=n||o===""?i:(u=s-n,l=xD(o,wD(u/o.length)),l.length>u&&(l=PD(l,0,u)),a?i+l:l+i)}};yy.exports={start:vy(!1),end:vy(!0)}});var Ey=f(($H,Iy)=>{"use strict";var AD=sr();Iy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(AD)});var xy=f(()=>{"use strict";var kD=se(),LD=Ty().start,$D=Ey();kD({target:"String",proto:!0,forced:$D},{padStart:function(e){return LD(this,e,arguments.length>1?arguments[1]:void 0)}})});var wy=f((DH,Py)=>{"use strict";xy();var RD=Ct();Py.exports=RD("String","padStart")});var ky=f((CH,Ay)=>{"use strict";var MD=wy();Ay.exports=MD});var $y=f((VH,Ly)=>{"use strict";var DD=ky();Ly.exports=DD});var Td="2.0.128-dev.6c63bff4.0";var Me=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Me||{}),Mt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(Mt||{});var gs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(gs||{}),po=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(po||{});var ho=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ho||{}),vs=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(vs||{});var oI=O(Xe(),1);import{assertNever as Sh,assertNonNullable as jx,isNonNullable as Es,ValueSubject as Qo,Subject as Qx,Subscription as Gx,merge as Wx,observableFrom as Yx,fromEvent as fh,map as bh,tap as gh,filterChanged as zx,isNullable as Go,ErrorCategory as vh}from"@vkontakte/videoplayer-shared/es2015";var mh=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 xs=class{constructor(e){this.connection$=new Qo(void 0);this.castState$=new Qo("NOT_AVAILABLE");this.errorEvent$=new Qx;this.realCastState$=new Qo("NOT_AVAILABLE");this.subscription=new Gx;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=Es((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||mh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:vh.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(){Es(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Go(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Go(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(fh(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 Sh(i.sessionState)}})).add(Wx(fh(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(gh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),bh(i=>i.castState)),Yx([r.getCastState()])).pipe(zx(),bh(Kx),gh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Es(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();jx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Go(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"?Es(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:vh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Kx=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 Sh(a)}};var wc=O(Xe(),1),HT=O(qr(),1),jT=O(Su(),1);var Eg=O(Js(),1);import{assertNever as mg}from"@vkontakte/videoplayer-shared/es2015";var he=(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:mg(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:mg(e)}};var w=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as a$,Subject as en,merge as fg}from"@vkontakte/videoplayer-shared/es2015";var V=class{constructor(e){this.transitionStarted$=new en;this.transitionEnded$=new en;this.transitionUpdated$=new en;this.forceChanged$=new en;this.stateChangeStarted$=fg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=fg(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||a$(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}};import{assertNever as s$}from"@vkontakte/videoplayer-shared/es2015";var bg=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 s$(a)}};import{assertNever as Xr,assertNonNullable as pr,debounce as gg,ErrorCategory as vg,fromEvent as hr,isNonNullable as Sg,map as yg,merge as Tg,observableFrom as n$,Subject as o$,Subscription as sl,timeout as u$,getHighestQuality as l$}from"@vkontakte/videoplayer-shared/es2015";var c$=5,d$=5,p$=500,Ig=7e3,ji=class{constructor(e){this.subscription=new sl;this.loadMediaTimeoutSubscription=new sl;this.videoState=new V("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:Xr(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:Xr(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:Xr(e)}break}default:Xr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(bg(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 sl;this.subscription.add(e),this.subscription.add(Tg(this.videoState.stateChangeStarted$.pipe(yg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(yg(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 o$;e.add(i.pipe(gg(p$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(hr(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)>c$)&&i.next(o),s=o})),e.add(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(hr(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<d$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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:Xr(n)}}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Tg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,n$(["init"])).pipe(gg(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"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(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"),w(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"),w(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"&&w(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];pr(c);let d=l$(Object.keys(c));pr(d);let p=c[d];pr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];pr(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];pr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];pr(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];pr(c),r=he(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:vg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Xr(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 Sg(o)&&(n.metadata.title=o),Sg(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(u$(Ig).subscribe(()=>s(`timeout(${Ig})`)))});(0,Eg.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:vg.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Pl=O(Xe(),1);import{clearVideoElement as Pg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as h$}from"@vkontakte/videoplayer-shared/es2015";var xg=a=>{try{a.pause(),a.playbackRate=0,h$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as m$,Subscription as f$}from"@vkontakte/videoplayer-shared/es2015";var nl=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)}},ol=window.WeakMap?new WeakMap:new nl,ul=window.WeakMap?new WeakMap:new Map,b$=(a,e=20)=>{let t=0;return m$(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?Pg(r):(r=document.createElement("video"),a.appendChild(r)),ol.set(r,i);let s=new f$;return s.add(b$(r,e)),ul.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},xe=a=>{let e=ul.get(a);e==null||e.unsubscribe(),ul.delete(a);let t=ol.get(a);ol.delete(a),t?Pg(a):xg(a)};var cl=O(Jr(),1);import{assertNonNullable as Qi,isNonNullable as ot,isNullable as x$,fromEvent as Zr,merge as Mg,observableFrom as Dg,filterChanged as Cg,map as Gi,Subject as Vg,Subscription as P$,ValueSubject as w$,ErrorCategory as A$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as ll,isNullable as I$,Subscription as E$}from"@vkontakte/videoplayer-shared/es2015";var tn=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=I$(i),l=new E$;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},nt=(a,e,t)=>tn(e,()=>a.loop,r=>{ll(r)&&(a.loop=r)},{onError:t}),Pe=(a,e,t,r)=>tn(e,()=>({muted:a.muted,volume:a.volume}),i=>{ll(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}),Fe=(a,e,t,r)=>tn(e,()=>a.playbackRate,i=>{ll(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Bt=tn;var k$=a=>["__",a.language,a.label].join("|"),L$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},dl=class a{constructor(e){this.available$=new Vg;this.current$=new w$(void 0);this.error$=new Vg;this.subscription=new P$;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:A$.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(Bt(t.internalTextTracks,()=>(0,cl.default)(this.internalTracks),s=>{ot(s)&&this.setInternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Bt(t.externalTextTracks,()=>(0,cl.default)(this.externalTracks),s=>{ot(s)&&this.setExternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Bt(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(Bt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Qi(this.video);let{textTracks:e}=this.video;this.subscription.add(Zr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Mg(Zr(e,"addtrack"),Zr(e,"removetrack"),Dg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Cg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Mg(Zr(e,"change"),Dg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Gi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Cg()).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(Zr(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(Zr(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;ot(t.align)&&(i.align=t.align),ot(t.position)&&(i.position=t.position),ot(t.size)&&(i.size=t.size),ot(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Qi(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:k$(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){Qi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(x$(e)||!L$(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){Qi(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){Qi(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)}},qe=dl;var mr=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 Bg=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},pl=a=>{let e=Bg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Og=a=>{let e=Bg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ue,map as Ot,merge as Ng,filterChanged as R$,isNonNullable as Fg,Subject as M$,filter as qg,mapTo as Ug,combine as D$,once as C$,ErrorCategory as V$,ValueSubject as Hg,clientChecker as B$}from"@vkontakte/videoplayer-shared/es2015";var $$=3,_g=(a,e,t=$$)=>{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 we=a=>{let e=T=>Ue(a,T).pipe(Ug(void 0)),r=Ng(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Ue(a,T))).pipe(Ot(T=>T.type==="ended"?a.readyState<2:a.readyState<3),R$()),i=Ng(Ue(a,"progress"),Ue(a,"timeupdate")).pipe(Ot(()=>_g(a.buffered,a.currentTime))),s=B$.isSafari?D$({play:e("play").pipe(C$()),playing:e("playing")}).pipe(Ug(void 0)):e("playing"),n=Ue(a,"volumechange").pipe(Ot(()=>({muted:a.muted,volume:a.volume}))),o=Ue(a,"ratechange").pipe(Ot(()=>a.playbackRate)),u=Ue(a,"error").pipe(qg(()=>!!(a.error||a.played.length)),Ot(()=>{var I;let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:V$.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=Ue(a,"timeupdate").pipe(Ot(()=>a.currentTime)),c=new M$,d=.3,p;l.subscribe(T=>{a.loop&&Fg(p)&&Fg(T)&&p>=a.duration-d&&T<=d&&c.next(p),p=T});let h=e("pause").pipe(qg(()=>!a.error&&p!==a.duration)),m=Ue(a,"enterpictureinpicture"),b=Ue(a,"leavepictureinpicture"),g=new Hg(Og(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Hg(pl(a));return Ue(a,"fullscreenchange").pipe(Ot(()=>pl(a))).subscribe(v),{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$:Ue(a,"durationchange").pipe(Ot(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as _t}from"@vkontakte/videoplayer-shared/es2015";var Nt=a=>{switch(a){case"mobile":return _t.Q_144P;case"lowest":return _t.Q_240P;case"low":return _t.Q_360P;case"sd":case"medium":return _t.Q_480P;case"hd":case"high":return _t.Q_720P;case"fullhd":case"full":return _t.Q_1080P;case"quadhd":case"quad":return _t.Q_1440P;case"ultrahd":case"ultra":return _t.Q_2160P}};var qt=O(Ft(),1),sv=O(Xe(),1),sn=O(qr(),1);import{isNonNullable as Oe,isNullable as tv,now as nv,isHigher as rv,isHigherOrEqual as bl,isInvariantQuality as iv,isLowerOrEqual as gl,videoSizeToQuality as W$,assertNotEmptyArray as ov,assertNonNullable as Y$}from"@vkontakte/videoplayer-shared/es2015";var hl=!1,bt={},Kg=a=>{hl=a},Xg=()=>{bt={}},Jg=a=>{a(bt)},Wi=(a,e)=>{var t;hl&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},Se=class{constructor(e){this.name=e}next(e){var r,i;if(!hl)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};import{isHigher as Q$,isHigherOrEqual as xN,isLower as Zg,isLowerOrEqual as PN,isNonNullable as rn,isNullable as G$,videoHeightToQuality as an}from"@vkontakte/videoplayer-shared/es2015";function ml({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function fl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&ml({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Yi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return G$(a)||rn(a.min)&&rn(a.max)&&Zg(a.max,a.min)||rn(a.min)&&e&&Q$(a.min,e)||rn(a.max)&&t&&Zg(a.max,t)}function ev({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Yi({limits:{max:a!=null&&a.max?an(a.max):void 0,min:a!=null&&a.min?an(a.min):void 0},highestAvailableQuality:e?an(e):void 0,lowestAvailableQuality:t?an(t):void 0})}var z$=new Se("best_bitrate"),uv=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var vl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),zi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=nv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},lv='Assertion "ABR Tracks is empty array" failed',nn=(a,e,t,r)=>{var u;let i=[...e].sort(vl(1)),s=[...t].sort(vl(1)),n=s.filter(l=>Oe(l.bitrate)&&Oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,qt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,qt.default)(s,-1);return o&&(0,sv.default)(n,o)?o:n.length?(0,qt.default)(n,-1):(0,qt.default)(s,0)},av=a=>"quality"in a,cv=(a,e,t,r)=>{var n;let i=Oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&Oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&nv()-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=av(o)?"video":"audio",l=av(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var GT=Object.create;var to=Object.defineProperty,WT=Object.defineProperties,YT=Object.getOwnPropertyDescriptor,zT=Object.getOwnPropertyDescriptors,KT=Object.getOwnPropertyNames,ps=Object.getOwnPropertySymbols,XT=Object.getPrototypeOf,ro=Object.prototype.hasOwnProperty,id=Object.prototype.propertyIsEnumerable;var JT=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,rd=(a,e,t)=>e in a?to(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,P=(a,e)=>{for(var t in e||(e={}))ro.call(e,t)&&rd(a,t,e[t]);if(ps)for(var t of ps(e))id.call(e,t)&&rd(a,t,e[t]);return a},$=(a,e)=>WT(a,zT(e));var ad=(a,e)=>{var t={};for(var r in a)ro.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&&id.call(a,r)&&(t[r]=a[r]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var ZT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of KT(e))!ro.call(a,i)&&i!==t&&to(a,i,{get:()=>e[i],enumerable:!(r=YT(e,i))||r.enumerable});return a};var _=(a,e,t)=>(t=a!=null?GT(XT(a)):{},ZT(e||!a||!a.__esModule?to(t,"default",{value:a,enumerable:!0}):t,a));var x=(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},oe=(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[JT("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var se=f((so,nd)=>{"use strict";var gi=function(a){return a&&a.Math===Math&&a};nd.exports=gi(typeof globalThis=="object"&&globalThis)||gi(typeof window=="object"&&window)||gi(typeof self=="object"&&self)||gi(typeof global=="object"&&global)||gi(typeof so=="object"&&so)||function(){return this}()||Function("return this")()});var me=f((P0,od)=>{"use strict";od.exports=function(a){try{return!!a()}catch(e){return!0}}});var vi=f((w0,ud)=>{"use strict";var eI=me();ud.exports=!eI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var no=f((k0,pd)=>{"use strict";var tI=vi(),dd=Function.prototype,ld=dd.apply,cd=dd.call;pd.exports=typeof Reflect=="object"&&Reflect.apply||(tI?cd.bind(ld):function(){return cd.apply(ld,arguments)})});var le=f((A0,fd)=>{"use strict";var hd=vi(),md=Function.prototype,oo=md.call,rI=hd&&md.bind.bind(oo,oo);fd.exports=hd?rI:function(a){return function(){return oo.apply(a,arguments)}}});var tr=f((L0,gd)=>{"use strict";var bd=le(),iI=bd({}.toString),aI=bd("".slice);gd.exports=function(a){return aI(iI(a),8,-1)}});var uo=f((R0,vd)=>{"use strict";var sI=tr(),nI=le();vd.exports=function(a){if(sI(a)==="Function")return nI(a)}});var ie=f(($0,Sd)=>{"use strict";var lo=typeof document=="object"&&document.all;Sd.exports=typeof lo=="undefined"&&lo!==void 0?function(a){return typeof a=="function"||a===lo}:function(a){return typeof a=="function"}});var Ce=f((M0,yd)=>{"use strict";var oI=me();yd.exports=!oI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var De=f((C0,Td)=>{"use strict";var uI=vi(),bs=Function.prototype.call;Td.exports=uI?bs.bind(bs):function(){return bs.apply(bs,arguments)}});var co=f(xd=>{"use strict";var Id={}.propertyIsEnumerable,Ed=Object.getOwnPropertyDescriptor,lI=Ed&&!Id.call({1:2},1);xd.f=lI?function(e){var t=Ed(this,e);return!!t&&t.enumerable}:Id});var Si=f((V0,Pd)=>{"use strict";Pd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var kd=f((_0,wd)=>{"use strict";var cI=le(),dI=me(),pI=tr(),po=Object,hI=cI("".split);wd.exports=dI(function(){return!po("z").propertyIsEnumerable(0)})?function(a){return pI(a)==="String"?hI(a,""):po(a)}:po});var $r=f((O0,Ad)=>{"use strict";Ad.exports=function(a){return a==null}});var $t=f((B0,Ld)=>{"use strict";var mI=$r(),fI=TypeError;Ld.exports=function(a){if(mI(a))throw new fI("Can't call method on "+a);return a}});var rr=f((N0,Rd)=>{"use strict";var bI=kd(),gI=$t();Rd.exports=function(a){return bI(gI(a))}});var Ve=f((F0,$d)=>{"use strict";var vI=ie();$d.exports=function(a){return typeof a=="object"?a!==null:vI(a)}});var Mr=f((q0,Md)=>{"use strict";Md.exports={}});var ht=f((U0,Dd)=>{"use strict";var ho=Mr(),mo=se(),SI=ie(),Cd=function(a){return SI(a)?a:void 0};Dd.exports=function(a,e){return arguments.length<2?Cd(ho[a])||Cd(mo[a]):ho[a]&&ho[a][e]||mo[a]&&mo[a][e]}});var yi=f((H0,Vd)=>{"use strict";var yI=le();Vd.exports=yI({}.isPrototypeOf)});var ir=f((j0,Bd)=>{"use strict";var TI=se(),_d=TI.navigator,Od=_d&&_d.userAgent;Bd.exports=Od?String(Od):""});var bo=f((Q0,jd)=>{"use strict";var Hd=se(),fo=ir(),Nd=Hd.process,Fd=Hd.Deno,qd=Nd&&Nd.versions||Fd&&Fd.version,Ud=qd&&qd.v8,Ye,gs;Ud&&(Ye=Ud.split("."),gs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!gs&&fo&&(Ye=fo.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=fo.match(/Chrome\/(\d+)/),Ye&&(gs=+Ye[1])));jd.exports=gs});var go=f((G0,Gd)=>{"use strict";var Qd=bo(),II=me(),EI=se(),xI=EI.String;Gd.exports=!!Object.getOwnPropertySymbols&&!II(function(){var a=Symbol("symbol detection");return!xI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Qd&&Qd<41})});var vo=f((W0,Wd)=>{"use strict";var PI=go();Wd.exports=PI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var So=f((Y0,Yd)=>{"use strict";var wI=ht(),kI=ie(),AI=yi(),LI=vo(),RI=Object;Yd.exports=LI?function(a){return typeof a=="symbol"}:function(a){var e=wI("Symbol");return kI(e)&&AI(e.prototype,RI(a))}});var Ti=f((z0,zd)=>{"use strict";var $I=String;zd.exports=function(a){try{return $I(a)}catch(e){return"Object"}}});var at=f((K0,Kd)=>{"use strict";var MI=ie(),CI=Ti(),DI=TypeError;Kd.exports=function(a){if(MI(a))return a;throw new DI(CI(a)+" is not a function")}});var Ii=f((X0,Xd)=>{"use strict";var VI=at(),_I=$r();Xd.exports=function(a,e){var t=a[e];return _I(t)?void 0:VI(t)}});var Zd=f((J0,Jd)=>{"use strict";var yo=De(),To=ie(),Io=Ve(),OI=TypeError;Jd.exports=function(a,e){var t,r;if(e==="string"&&To(t=a.toString)&&!Io(r=yo(t,a))||To(t=a.valueOf)&&!Io(r=yo(t,a))||e!=="string"&&To(t=a.toString)&&!Io(r=yo(t,a)))return r;throw new OI("Can't convert object to primitive value")}});var ze=f((Z0,ep)=>{"use strict";ep.exports=!0});var ip=f((eV,rp)=>{"use strict";var tp=se(),BI=Object.defineProperty;rp.exports=function(a,e){try{BI(tp,a,{value:e,configurable:!0,writable:!0})}catch(t){tp[a]=e}return e}});var Ei=f((tV,np)=>{"use strict";var NI=ze(),FI=se(),qI=ip(),ap="__core-js_shared__",sp=np.exports=FI[ap]||qI(ap,{});(sp.versions||(sp.versions=[])).push({version:"3.38.0",mode:NI?"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 Eo=f((rV,up)=>{"use strict";var op=Ei();up.exports=function(a,e){return op[a]||(op[a]=e||{})}});var Cr=f((iV,lp)=>{"use strict";var UI=$t(),HI=Object;lp.exports=function(a){return HI(UI(a))}});var Ke=f((aV,cp)=>{"use strict";var jI=le(),QI=Cr(),GI=jI({}.hasOwnProperty);cp.exports=Object.hasOwn||function(e,t){return GI(QI(e),t)}});var xo=f((sV,dp)=>{"use strict";var WI=le(),YI=0,zI=Math.random(),KI=WI(1 .toString);dp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+KI(++YI+zI,36)}});var fe=f((nV,hp)=>{"use strict";var XI=se(),JI=Eo(),pp=Ke(),ZI=xo(),eE=go(),tE=vo(),Dr=XI.Symbol,Po=JI("wks"),rE=tE?Dr.for||Dr:Dr&&Dr.withoutSetter||ZI;hp.exports=function(a){return pp(Po,a)||(Po[a]=eE&&pp(Dr,a)?Dr[a]:rE("Symbol."+a)),Po[a]}});var gp=f((oV,bp)=>{"use strict";var iE=De(),mp=Ve(),fp=So(),aE=Ii(),sE=Zd(),nE=fe(),oE=TypeError,uE=nE("toPrimitive");bp.exports=function(a,e){if(!mp(a)||fp(a))return a;var t=aE(a,uE),r;if(t){if(e===void 0&&(e="default"),r=iE(t,a,e),!mp(r)||fp(r))return r;throw new oE("Can't convert object to primitive value")}return e===void 0&&(e="number"),sE(a,e)}});var wo=f((uV,vp)=>{"use strict";var lE=gp(),cE=So();vp.exports=function(a){var e=lE(a,"string");return cE(e)?e:e+""}});var vs=f((lV,yp)=>{"use strict";var dE=se(),Sp=Ve(),ko=dE.document,pE=Sp(ko)&&Sp(ko.createElement);yp.exports=function(a){return pE?ko.createElement(a):{}}});var Ao=f((cV,Tp)=>{"use strict";var hE=Ce(),mE=me(),fE=vs();Tp.exports=!hE&&!mE(function(){return Object.defineProperty(fE("div"),"a",{get:function(){return 7}}).a!==7})});var xp=f(Ep=>{"use strict";var bE=Ce(),gE=De(),vE=co(),SE=Si(),yE=rr(),TE=wo(),IE=Ke(),EE=Ao(),Ip=Object.getOwnPropertyDescriptor;Ep.f=bE?Ip:function(e,t){if(e=yE(e),t=TE(t),EE)try{return Ip(e,t)}catch(r){}if(IE(e,t))return SE(!gE(vE.f,e,t),e[t])}});var Lo=f((pV,Pp)=>{"use strict";var xE=me(),PE=ie(),wE=/#|\.prototype\./,xi=function(a,e){var t=AE[kE(a)];return t===RE?!0:t===LE?!1:PE(e)?xE(e):!!e},kE=xi.normalize=function(a){return String(a).replace(wE,".").toLowerCase()},AE=xi.data={},LE=xi.NATIVE="N",RE=xi.POLYFILL="P";Pp.exports=xi});var Vr=f((hV,kp)=>{"use strict";var wp=uo(),$E=at(),ME=vi(),CE=wp(wp.bind);kp.exports=function(a,e){return $E(a),e===void 0?a:ME?CE(a,e):function(){return a.apply(e,arguments)}}});var Ro=f((mV,Ap)=>{"use strict";var DE=Ce(),VE=me();Ap.exports=DE&&VE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=f((fV,Lp)=>{"use strict";var _E=Ve(),OE=String,BE=TypeError;Lp.exports=function(a){if(_E(a))return a;throw new BE(OE(a)+" is not an object")}});var ar=f($p=>{"use strict";var NE=Ce(),FE=Ao(),qE=Ro(),Ss=st(),Rp=wo(),UE=TypeError,$o=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,Mo="enumerable",Co="configurable",Do="writable";$p.f=NE?qE?function(e,t,r){if(Ss(e),t=Rp(t),Ss(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Do in r&&!r[Do]){var i=HE(e,t);i&&i[Do]&&(e[t]=r.value,r={configurable:Co in r?r[Co]:i[Co],enumerable:Mo in r?r[Mo]:i[Mo],writable:!1})}return $o(e,t,r)}:$o:function(e,t,r){if(Ss(e),t=Rp(t),Ss(r),FE)try{return $o(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new UE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=f((gV,Mp)=>{"use strict";var jE=Ce(),QE=ar(),GE=Si();Mp.exports=jE?function(a,e,t){return QE.f(a,e,GE(1,t))}:function(a,e,t){return a[e]=t,a}});var ue=f((vV,Dp)=>{"use strict";var Pi=se(),WE=no(),YE=uo(),zE=ie(),KE=xp().f,XE=Lo(),Or=Mr(),JE=Vr(),Br=_r(),Cp=Ke();Ei();var ZE=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 WE(a,this,arguments)};return e.prototype=a.prototype,e};Dp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Pi:i?Pi[t]:Pi[t]&&Pi[t].prototype,o=r?Or:Or[t]||Br(Or,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=XE(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Cp(n,p),m=o[p],c&&(a.dontCallGetSet?(v=KE(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?g=JE(h,Pi):a.wrap&&c?g=ZE(h):s&&zE(h)?g=YE(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Br(g,"sham",!0),Br(o,p,g),s&&(d=t+"Prototype",Cp(Or,d)||Br(Or,d,{}),Br(Or[d],p,h),a.real&&u&&(l||!u[p])&&Br(u,p,h)))}});var _p=f((SV,Vp)=>{"use strict";var ex=Math.ceil,tx=Math.floor;Vp.exports=Math.trunc||function(e){var t=+e;return(t>0?tx:ex)(t)}});var wi=f((yV,Op)=>{"use strict";var rx=_p();Op.exports=function(a){var e=+a;return e!==e||e===0?0:rx(e)}});var Np=f((TV,Bp)=>{"use strict";var ix=wi(),ax=Math.max,sx=Math.min;Bp.exports=function(a,e){var t=ix(a);return t<0?ax(t+e,0):sx(t,e)}});var Vo=f((IV,Fp)=>{"use strict";var nx=wi(),ox=Math.min;Fp.exports=function(a){var e=nx(a);return e>0?ox(e,9007199254740991):0}});var Nr=f((EV,qp)=>{"use strict";var ux=Vo();qp.exports=function(a){return ux(a.length)}});var _o=f((xV,Hp)=>{"use strict";var lx=rr(),cx=Np(),dx=Nr(),Up=function(a){return function(e,t,r){var i=lx(e),s=dx(i);if(s===0)return!a&&-1;var n=cx(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}};Hp.exports={includes:Up(!0),indexOf:Up(!1)}});var ki=f((PV,jp)=>{"use strict";jp.exports=function(){}});var Qp=f(()=>{"use strict";var px=ue(),hx=_o().includes,mx=me(),fx=ki(),bx=mx(function(){return!Array(1).includes()});px({target:"Array",proto:!0,forced:bx},{includes:function(e){return hx(this,e,arguments.length>1?arguments[1]:void 0)}});fx("includes")});var Mt=f((AV,Gp)=>{"use strict";var gx=ht();Gp.exports=gx});var Yp=f((LV,Wp)=>{"use strict";Qp();var vx=Mt();Wp.exports=vx("Array","includes")});var Kp=f((RV,zp)=>{"use strict";var Sx=Yp();zp.exports=Sx});var Fe=f(($V,Xp)=>{"use strict";var yx=Kp();Xp.exports=yx});var Is=f((HV,sh)=>{"use strict";var Ax=Eo(),Lx=xo(),ah=Ax("keys");sh.exports=function(a){return ah[a]||(ah[a]=Lx(a))}});var oh=f((jV,nh)=>{"use strict";var Rx=me();nh.exports=!Rx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Es=f((QV,lh)=>{"use strict";var $x=Ke(),Mx=ie(),Cx=Cr(),Dx=Is(),Vx=oh(),uh=Dx("IE_PROTO"),No=Object,_x=No.prototype;lh.exports=Vx?No.getPrototypeOf:function(a){var e=Cx(a);if($x(e,uh))return e[uh];var t=e.constructor;return Mx(t)&&e instanceof t?t.prototype:e instanceof No?_x:null}});var xs=f((GV,ch)=>{"use strict";ch.exports={}});var hh=f((WV,ph)=>{"use strict";var Ox=le(),Fo=Ke(),Bx=rr(),Nx=_o().indexOf,Fx=xs(),dh=Ox([].push);ph.exports=function(a,e){var t=Bx(a),r=0,i=[],s;for(s in t)!Fo(Fx,s)&&Fo(t,s)&&dh(i,s);for(;e.length>r;)Fo(t,s=e[r++])&&(~Nx(i,s)||dh(i,s));return i}});var qo=f((YV,mh)=>{"use strict";mh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Uo=f((zV,fh)=>{"use strict";var qx=hh(),Ux=qo();fh.exports=Object.keys||function(e){return qx(e,Ux)}});var Ho=f((KV,yh)=>{"use strict";var gh=Ce(),Hx=me(),vh=le(),jx=Es(),Qx=Uo(),Gx=rr(),Wx=co().f,Sh=vh(Wx),Yx=vh([].push),zx=gh&&Hx(function(){var a=Object.create(null);return a[2]=2,!Sh(a,2)}),bh=function(a){return function(e){for(var t=Gx(e),r=Qx(t),i=zx&&jx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!gh||(i?u in t:Sh(t,u)))&&Yx(o,a?[u,t[u]]:t[u]);return o}};yh.exports={entries:bh(!0),values:bh(!1)}});var Th=f(()=>{"use strict";var Kx=ue(),Xx=Ho().entries;Kx({target:"Object",stat:!0},{entries:function(e){return Xx(e)}})});var Eh=f((ZV,Ih)=>{"use strict";Th();var Jx=Mr();Ih.exports=Jx.Object.entries});var Ph=f((e_,xh)=>{"use strict";var Zx=Eh();xh.exports=Zx});var Fr=f((t_,wh)=>{"use strict";var eP=Ph();wh.exports=eP});var sr=f((r_,kh)=>{"use strict";kh.exports={}});var Rh=f((i_,Lh)=>{"use strict";var tP=se(),rP=ie(),Ah=tP.WeakMap;Lh.exports=rP(Ah)&&/native code/.test(String(Ah))});var Wo=f((a_,Ch)=>{"use strict";var iP=Rh(),Mh=se(),aP=Ve(),sP=_r(),jo=Ke(),Qo=Ei(),nP=Is(),oP=xs(),$h="Object already initialized",Go=Mh.TypeError,uP=Mh.WeakMap,Ps,Ai,ws,lP=function(a){return ws(a)?Ai(a):Ps(a,{})},cP=function(a){return function(e){var t;if(!aP(e)||(t=Ai(e)).type!==a)throw new Go("Incompatible receiver, "+a+" required");return t}};iP||Qo.state?(Xe=Qo.state||(Qo.state=new uP),Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,Ps=function(a,e){if(Xe.has(a))throw new Go($h);return e.facade=a,Xe.set(a,e),e},Ai=function(a){return Xe.get(a)||{}},ws=function(a){return Xe.has(a)}):(nr=nP("state"),oP[nr]=!0,Ps=function(a,e){if(jo(a,nr))throw new Go($h);return e.facade=a,sP(a,nr,e),e},Ai=function(a){return jo(a,nr)?a[nr]:{}},ws=function(a){return jo(a,nr)});var Xe,nr;Ch.exports={set:Ps,get:Ai,has:ws,enforce:lP,getterFor:cP}});var Ko=f((s_,Vh)=>{"use strict";var Yo=Ce(),dP=Ke(),Dh=Function.prototype,pP=Yo&&Object.getOwnPropertyDescriptor,zo=dP(Dh,"name"),hP=zo&&function(){}.name==="something",mP=zo&&(!Yo||Yo&&pP(Dh,"name").configurable);Vh.exports={EXISTS:zo,PROPER:hP,CONFIGURABLE:mP}});var Oh=f(_h=>{"use strict";var fP=Ce(),bP=Ro(),gP=ar(),vP=st(),SP=rr(),yP=Uo();_h.f=fP&&!bP?Object.defineProperties:function(e,t){vP(e);for(var r=SP(t),i=yP(t),s=i.length,n=0,o;s>n;)gP.f(e,o=i[n++],r[o]);return e}});var Xo=f((o_,Bh)=>{"use strict";var TP=ht();Bh.exports=TP("document","documentElement")});var tu=f((u_,Qh)=>{"use strict";var IP=st(),EP=Oh(),Nh=qo(),xP=xs(),PP=Xo(),wP=vs(),kP=Is(),Fh=">",qh="<",Zo="prototype",eu="script",Hh=kP("IE_PROTO"),Jo=function(){},jh=function(a){return qh+eu+Fh+a+qh+"/"+eu+Fh},Uh=function(a){a.write(jh("")),a.close();var e=a.parentWindow.Object;return a=null,e},AP=function(){var a=wP("iframe"),e="java"+eu+":",t;return a.style.display="none",PP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(jh("document.F=Object")),t.close(),t.F},ks,As=function(){try{ks=new ActiveXObject("htmlfile")}catch(e){}As=typeof document!="undefined"?document.domain&&ks?Uh(ks):AP():Uh(ks);for(var a=Nh.length;a--;)delete As[Zo][Nh[a]];return As()};xP[Hh]=!0;Qh.exports=Object.create||function(e,t){var r;return e!==null?(Jo[Zo]=IP(e),r=new Jo,Jo[Zo]=null,r[Hh]=e):r=As(),t===void 0?r:EP.f(r,t)}});var qr=f((l_,Gh)=>{"use strict";var LP=_r();Gh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:LP(a,e,t),a}});var su=f((c_,zh)=>{"use strict";var RP=me(),$P=ie(),MP=Ve(),CP=tu(),Wh=Es(),DP=qr(),VP=fe(),_P=ze(),au=VP("iterator"),Yh=!1,mt,ru,iu;[].keys&&(iu=[].keys(),"next"in iu?(ru=Wh(Wh(iu)),ru!==Object.prototype&&(mt=ru)):Yh=!0);var OP=!MP(mt)||RP(function(){var a={};return mt[au].call(a)!==a});OP?mt={}:_P&&(mt=CP(mt));$P(mt[au])||DP(mt,au,function(){return this});zh.exports={IteratorPrototype:mt,BUGGY_SAFARI_ITERATORS:Yh}});var Ls=f((d_,Xh)=>{"use strict";var BP=fe(),NP=BP("toStringTag"),Kh={};Kh[NP]="z";Xh.exports=String(Kh)==="[object z]"});var Li=f((p_,Jh)=>{"use strict";var FP=Ls(),qP=ie(),Rs=tr(),UP=fe(),HP=UP("toStringTag"),jP=Object,QP=Rs(function(){return arguments}())==="Arguments",GP=function(a,e){try{return a[e]}catch(t){}};Jh.exports=FP?Rs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=GP(e=jP(a),HP))=="string"?t:QP?Rs(e):(r=Rs(e))==="Object"&&qP(e.callee)?"Arguments":r}});var em=f((h_,Zh)=>{"use strict";var WP=Ls(),YP=Li();Zh.exports=WP?{}.toString:function(){return"[object "+YP(this)+"]"}});var Ri=f((m_,rm)=>{"use strict";var zP=Ls(),KP=ar().f,XP=_r(),JP=Ke(),ZP=em(),ew=fe(),tm=ew("toStringTag");rm.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(JP(i,tm)||KP(i,tm,{configurable:!0,value:e}),r&&!zP&&XP(i,"toString",ZP))}});var am=f((f_,im)=>{"use strict";var tw=su().IteratorPrototype,rw=tu(),iw=Si(),aw=Ri(),sw=sr(),nw=function(){return this};im.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=rw(tw,{next:iw(+!r,t)}),aw(a,i,!1,!0),sw[i]=nw,a}});var nm=f((b_,sm)=>{"use strict";var ow=le(),uw=at();sm.exports=function(a,e,t){try{return ow(uw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var um=f((g_,om)=>{"use strict";var lw=Ve();om.exports=function(a){return lw(a)||a===null}});var cm=f((v_,lm)=>{"use strict";var cw=um(),dw=String,pw=TypeError;lm.exports=function(a){if(cw(a))return a;throw new pw("Can't set "+dw(a)+" as a prototype")}});var nu=f((S_,dm)=>{"use strict";var hw=nm(),mw=Ve(),fw=$t(),bw=cm();dm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=hw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return fw(i),bw(s),mw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Im=f((y_,Tm)=>{"use strict";var gw=ue(),vw=De(),$s=ze(),Sm=Ko(),Sw=ie(),yw=am(),pm=Es(),hm=nu(),Tw=Ri(),Iw=_r(),ou=qr(),Ew=fe(),mm=sr(),ym=su(),xw=Sm.PROPER,Pw=Sm.CONFIGURABLE,fm=ym.IteratorPrototype,Ms=ym.BUGGY_SAFARI_ITERATORS,$i=Ew("iterator"),bm="keys",Mi="values",gm="entries",vm=function(){return this};Tm.exports=function(a,e,t,r,i,s,n){yw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ms&&v&&v in c)return c[v];switch(v){case bm:return function(){return new t(this,v)};case Mi:return function(){return new t(this,v)};case gm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[$i]||c["@@iterator"]||i&&c[i],p=!Ms&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=pm(h.call(new a)),m!==Object.prototype&&m.next&&(!$s&&pm(m)!==fm&&(hm?hm(m,fm):Sw(m[$i])||ou(m,$i,vm)),Tw(m,u,!0,!0),$s&&(mm[u]=vm))),xw&&i===Mi&&d&&d.name!==Mi&&(!$s&&Pw?Iw(c,"name",Mi):(l=!0,p=function(){return vw(d,this)})),i)if(b={values:o(Mi),keys:s?p:o(bm),entries:o(gm)},n)for(g in b)(Ms||l||!(g in c))&&ou(c,g,b[g]);else gw({target:e,proto:!0,forced:Ms||l},b);return(!$s||n)&&c[$i]!==p&&ou(c,$i,p,{name:i}),mm[e]=p,b}});var xm=f((T_,Em)=>{"use strict";Em.exports=function(a,e){return{value:a,done:e}}});var lu=f((I_,Lm)=>{"use strict";var ww=rr(),uu=ki(),Pm=sr(),km=Wo(),kw=ar().f,Aw=Im(),Cs=xm(),Lw=ze(),Rw=Ce(),Am="Array Iterator",$w=km.set,Mw=km.getterFor(Am);Lm.exports=Aw(Array,"Array",function(a,e){$w(this,{type:Am,target:ww(a),index:0,kind:e})},function(){var a=Mw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Cs(void 0,!0);switch(a.kind){case"keys":return Cs(t,!1);case"values":return Cs(e[t],!1)}return Cs([t,e[t]],!1)},"values");var wm=Pm.Arguments=Pm.Array;uu("keys");uu("values");uu("entries");if(!Lw&&Rw&&wm.name!=="values")try{kw(wm,"name",{value:"values"})}catch(a){}});var $m=f((E_,Rm)=>{"use strict";var Cw=fe(),Dw=sr(),Vw=Cw("iterator"),_w=Array.prototype;Rm.exports=function(a){return a!==void 0&&(Dw.Array===a||_w[Vw]===a)}});var cu=f((x_,Cm)=>{"use strict";var Ow=Li(),Mm=Ii(),Bw=$r(),Nw=sr(),Fw=fe(),qw=Fw("iterator");Cm.exports=function(a){if(!Bw(a))return Mm(a,qw)||Mm(a,"@@iterator")||Nw[Ow(a)]}});var Vm=f((P_,Dm)=>{"use strict";var Uw=De(),Hw=at(),jw=st(),Qw=Ti(),Gw=cu(),Ww=TypeError;Dm.exports=function(a,e){var t=arguments.length<2?Gw(a):e;if(Hw(t))return jw(Uw(t,a));throw new Ww(Qw(a)+" is not iterable")}});var Bm=f((w_,Om)=>{"use strict";var Yw=De(),_m=st(),zw=Ii();Om.exports=function(a,e,t){var r,i;_m(a);try{if(r=zw(a,"return"),!r){if(e==="throw")throw t;return t}r=Yw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return _m(r),t}});var Vs=f((k_,Um)=>{"use strict";var Kw=Vr(),Xw=De(),Jw=st(),Zw=Ti(),ek=$m(),tk=Nr(),Nm=yi(),rk=Vm(),ik=cu(),Fm=Bm(),ak=TypeError,Ds=function(a,e){this.stopped=a,this.result=e},qm=Ds.prototype;Um.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=Kw(e,r),l,c,d,p,h,m,b,g=function(S){return l&&Fm(l,"normal",S),new Ds(!0,S)},v=function(S){return i?(Jw(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=ik(a),!c)throw new ak(Zw(a)+" is not iterable");if(ek(c)){for(d=0,p=tk(a);p>d;d++)if(h=v(a[d]),h&&Nm(qm,h))return h;return new Ds(!1)}l=rk(a,c)}for(m=s?a.next:l.next;!(b=Xw(m,l)).done;){try{h=v(b.value)}catch(S){Fm(l,"throw",S)}if(typeof h=="object"&&h&&Nm(qm,h))return h}return new Ds(!1)}});var jm=f((A_,Hm)=>{"use strict";var sk=Ce(),nk=ar(),ok=Si();Hm.exports=function(a,e,t){sk?nk.f(a,e,ok(0,t)):a[e]=t}});var Qm=f(()=>{"use strict";var uk=ue(),lk=Vs(),ck=jm();uk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return lk(e,function(r,i){ck(t,r,i)},{AS_ENTRIES:!0}),t}})});var Wm=f(($_,Gm)=>{"use strict";lu();Qm();var dk=Mr();Gm.exports=dk.Object.fromEntries});var zm=f((M_,Ym)=>{"use strict";Ym.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 Xm=f(()=>{"use strict";lu();var pk=zm(),hk=se(),mk=Ri(),Km=sr();for(_s in pk)mk(hk[_s],_s),Km[_s]=Km.Array;var _s});var Zm=f((V_,Jm)=>{"use strict";var fk=Wm();Xm();Jm.exports=fk});var du=f((__,ef)=>{"use strict";var bk=Zm();ef.exports=bk});var tf=f(()=>{"use strict"});var pu=f((N_,rf)=>{"use strict";var Ci=se(),gk=ir(),vk=tr(),Os=function(a){return gk.slice(0,a.length)===a};rf.exports=function(){return Os("Bun/")?"BUN":Os("Cloudflare-Workers")?"CLOUDFLARE":Os("Deno/")?"DENO":Os("Node.js/")?"NODE":Ci.Bun&&typeof Bun.version=="string"?"BUN":Ci.Deno&&typeof Deno.version=="object"?"DENO":vk(Ci.process)==="process"?"NODE":Ci.window&&Ci.document?"BROWSER":"REST"}()});var Bs=f((F_,af)=>{"use strict";var Sk=pu();af.exports=Sk==="NODE"});var nf=f((q_,sf)=>{"use strict";var yk=ar();sf.exports=function(a,e,t){return yk.f(a,e,t)}});var lf=f((U_,uf)=>{"use strict";var Tk=ht(),Ik=nf(),Ek=fe(),xk=Ce(),of=Ek("species");uf.exports=function(a){var e=Tk(a);xk&&e&&!e[of]&&Ik(e,of,{configurable:!0,get:function(){return this}})}});var df=f((H_,cf)=>{"use strict";var Pk=yi(),wk=TypeError;cf.exports=function(a,e){if(Pk(e,a))return a;throw new wk("Incorrect invocation")}});var mu=f((j_,pf)=>{"use strict";var kk=le(),Ak=ie(),hu=Ei(),Lk=kk(Function.toString);Ak(hu.inspectSource)||(hu.inspectSource=function(a){return Lk(a)});pf.exports=hu.inspectSource});var bu=f((Q_,gf)=>{"use strict";var Rk=le(),$k=me(),hf=ie(),Mk=Li(),Ck=ht(),Dk=mu(),mf=function(){},ff=Ck("Reflect","construct"),fu=/^\s*(?:class|function)\b/,Vk=Rk(fu.exec),_k=!fu.test(mf),Di=function(e){if(!hf(e))return!1;try{return ff(mf,[],e),!0}catch(t){return!1}},bf=function(e){if(!hf(e))return!1;switch(Mk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return _k||!!Vk(fu,Dk(e))}catch(t){return!0}};bf.sham=!0;gf.exports=!ff||$k(function(){var a;return Di(Di.call)||!Di(Object)||!Di(function(){a=!0})||a})?bf:Di});var Sf=f((G_,vf)=>{"use strict";var Ok=bu(),Bk=Ti(),Nk=TypeError;vf.exports=function(a){if(Ok(a))return a;throw new Nk(Bk(a)+" is not a constructor")}});var gu=f((W_,Tf)=>{"use strict";var yf=st(),Fk=Sf(),qk=$r(),Uk=fe(),Hk=Uk("species");Tf.exports=function(a,e){var t=yf(a).constructor,r;return t===void 0||qk(r=yf(t)[Hk])?e:Fk(r)}});var Ef=f((Y_,If)=>{"use strict";var jk=le();If.exports=jk([].slice)});var Pf=f((z_,xf)=>{"use strict";var Qk=TypeError;xf.exports=function(a,e){if(a<e)throw new Qk("Not enough arguments");return a}});var vu=f((K_,wf)=>{"use strict";var Gk=ir();wf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Gk)});var ku=f((X_,Vf)=>{"use strict";var _e=se(),Wk=no(),Yk=Vr(),kf=ie(),zk=Ke(),Df=me(),Af=Xo(),Kk=Ef(),Lf=vs(),Xk=Pf(),Jk=vu(),Zk=Bs(),xu=_e.setImmediate,Pu=_e.clearImmediate,eA=_e.process,Su=_e.Dispatch,tA=_e.Function,Rf=_e.MessageChannel,rA=_e.String,yu=0,Vi={},$f="onreadystatechange",_i,or,Tu,Iu;Df(function(){_i=_e.location});var wu=function(a){if(zk(Vi,a)){var e=Vi[a];delete Vi[a],e()}},Eu=function(a){return function(){wu(a)}},Mf=function(a){wu(a.data)},Cf=function(a){_e.postMessage(rA(a),_i.protocol+"//"+_i.host)};(!xu||!Pu)&&(xu=function(e){Xk(arguments.length,1);var t=kf(e)?e:tA(e),r=Kk(arguments,1);return Vi[++yu]=function(){Wk(t,void 0,r)},or(yu),yu},Pu=function(e){delete Vi[e]},Zk?or=function(a){eA.nextTick(Eu(a))}:Su&&Su.now?or=function(a){Su.now(Eu(a))}:Rf&&!Jk?(Tu=new Rf,Iu=Tu.port2,Tu.port1.onmessage=Mf,or=Yk(Iu.postMessage,Iu)):_e.addEventListener&&kf(_e.postMessage)&&!_e.importScripts&&_i&&_i.protocol!=="file:"&&!Df(Cf)?(or=Cf,_e.addEventListener("message",Mf,!1)):$f in Lf("script")?or=function(a){Af.appendChild(Lf("script"))[$f]=function(){Af.removeChild(this),wu(a)}}:or=function(a){setTimeout(Eu(a),0)});Vf.exports={set:xu,clear:Pu}});var Bf=f((J_,Of)=>{"use strict";var _f=se(),iA=Ce(),aA=Object.getOwnPropertyDescriptor;Of.exports=function(a){if(!iA)return _f[a];var e=aA(_f,a);return e&&e.value}});var Au=f((Z_,Ff)=>{"use strict";var Nf=function(){this.head=null,this.tail=null};Nf.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}}};Ff.exports=Nf});var Uf=f((eO,qf)=>{"use strict";var sA=ir();qf.exports=/ipad|iphone|ipod/i.test(sA)&&typeof Pebble!="undefined"});var jf=f((tO,Hf)=>{"use strict";var nA=ir();Hf.exports=/web0s(?!.*chrome)/i.test(nA)});var Xf=f((rO,Kf)=>{"use strict";var Hr=se(),oA=Bf(),Qf=Vr(),Lu=ku().set,uA=Au(),lA=vu(),cA=Uf(),dA=jf(),Ru=Bs(),Gf=Hr.MutationObserver||Hr.WebKitMutationObserver,Wf=Hr.document,Yf=Hr.process,Ns=Hr.Promise,Cu=oA("queueMicrotask"),Ur,$u,Mu,Fs,zf;Cu||(Oi=new uA,Bi=function(){var a,e;for(Ru&&(a=Yf.domain)&&a.exit();e=Oi.get();)try{e()}catch(t){throw Oi.head&&Ur(),t}a&&a.enter()},!lA&&!Ru&&!dA&&Gf&&Wf?($u=!0,Mu=Wf.createTextNode(""),new Gf(Bi).observe(Mu,{characterData:!0}),Ur=function(){Mu.data=$u=!$u}):!cA&&Ns&&Ns.resolve?(Fs=Ns.resolve(void 0),Fs.constructor=Ns,zf=Qf(Fs.then,Fs),Ur=function(){zf(Bi)}):Ru?Ur=function(){Yf.nextTick(Bi)}:(Lu=Qf(Lu,Hr),Ur=function(){Lu(Bi)}),Cu=function(a){Oi.head||Ur(),Oi.add(a)});var Oi,Bi;Kf.exports=Cu});var Zf=f((iO,Jf)=>{"use strict";Jf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var qs=f((aO,eb)=>{"use strict";eb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ur=f((sO,tb)=>{"use strict";var pA=se();tb.exports=pA.Promise});var jr=f((nO,sb)=>{"use strict";var hA=se(),Ni=ur(),mA=ie(),fA=Lo(),bA=mu(),gA=fe(),rb=pu(),vA=ze(),Du=bo(),ib=Ni&&Ni.prototype,SA=gA("species"),Vu=!1,ab=mA(hA.PromiseRejectionEvent),yA=fA("Promise",function(){var a=bA(Ni),e=a!==String(Ni);if(!e&&Du===66||vA&&!(ib.catch&&ib.finally))return!0;if(!Du||Du<51||!/native code/.test(a)){var t=new Ni(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[SA]=r,Vu=t.then(function(){})instanceof r,!Vu)return!0}return!e&&(rb==="BROWSER"||rb==="DENO")&&!ab});sb.exports={CONSTRUCTOR:yA,REJECTION_EVENT:ab,SUBCLASSING:Vu}});var Qr=f((oO,ob)=>{"use strict";var nb=at(),TA=TypeError,IA=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new TA("Bad Promise constructor");e=r,t=i}),this.resolve=nb(e),this.reject=nb(t)};ob.exports.f=function(a){return new IA(a)}});var wb=f(()=>{"use strict";var EA=ue(),xA=ze(),Qs=Bs(),Ct=se(),zr=De(),ub=qr(),lb=nu(),PA=Ri(),wA=lf(),kA=at(),js=ie(),AA=Ve(),LA=df(),RA=gu(),mb=ku().set,Fu=Xf(),$A=Zf(),MA=qs(),CA=Au(),fb=Wo(),Gs=ur(),qu=jr(),bb=Qr(),Ws="Promise",gb=qu.CONSTRUCTOR,DA=qu.REJECTION_EVENT,VA=qu.SUBCLASSING,_u=fb.getterFor(Ws),_A=fb.set,Gr=Gs&&Gs.prototype,lr=Gs,Us=Gr,vb=Ct.TypeError,Ou=Ct.document,Uu=Ct.process,Bu=bb.f,OA=Bu,BA=!!(Ou&&Ou.createEvent&&Ct.dispatchEvent),Sb="unhandledrejection",NA="rejectionhandled",cb=0,yb=1,FA=2,Hu=1,Tb=2,Hs,db,qA,pb,Ib=function(a){var e;return AA(a)&&js(e=a.then)?e:!1},Eb=function(a,e){var t=e.value,r=e.state===yb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Tb&&HA(e),e.rejection=Hu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new vb("Promise-chain cycle")):(l=Ib(u))?zr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},xb=function(a,e){a.notified||(a.notified=!0,Fu(function(){for(var t=a.reactions,r;r=t.get();)Eb(r,a);a.notified=!1,e&&!a.rejection&&UA(a)}))},Pb=function(a,e,t){var r,i;BA?(r=Ou.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Ct.dispatchEvent(r)):r={promise:e,reason:t},!DA&&(i=Ct["on"+a])?i(r):a===Sb&&$A("Unhandled promise rejection",t)},UA=function(a){zr(mb,Ct,function(){var e=a.facade,t=a.value,r=hb(a),i;if(r&&(i=MA(function(){Qs?Uu.emit("unhandledRejection",t,e):Pb(Sb,e,t)}),a.rejection=Qs||hb(a)?Tb:Hu,i.error))throw i.value})},hb=function(a){return a.rejection!==Hu&&!a.parent},HA=function(a){zr(mb,Ct,function(){var e=a.facade;Qs?Uu.emit("rejectionHandled",e):Pb(NA,e,a.value)})},Wr=function(a,e,t){return function(r){a(e,r,t)}},Yr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=FA,xb(a,!0))},Nu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new vb("Promise can't be resolved itself");var r=Ib(e);r?Fu(function(){var i={done:!1};try{zr(r,e,Wr(Nu,i,a),Wr(Yr,i,a))}catch(s){Yr(i,s,a)}}):(a.value=e,a.state=yb,xb(a,!1))}catch(i){Yr({done:!1},i,a)}}};if(gb&&(lr=function(e){LA(this,Us),kA(e),zr(Hs,this);var t=_u(this);try{e(Wr(Nu,t),Wr(Yr,t))}catch(r){Yr(t,r)}},Us=lr.prototype,Hs=function(e){_A(this,{type:Ws,done:!1,notified:!1,parent:!1,reactions:new CA,rejection:!1,state:cb,value:void 0})},Hs.prototype=ub(Us,"then",function(e,t){var r=_u(this),i=Bu(RA(this,lr));return r.parent=!0,i.ok=js(e)?e:!0,i.fail=js(t)&&t,i.domain=Qs?Uu.domain:void 0,r.state===cb?r.reactions.add(i):Fu(function(){Eb(i,r)}),i.promise}),db=function(){var a=new Hs,e=_u(a);this.promise=a,this.resolve=Wr(Nu,e),this.reject=Wr(Yr,e)},bb.f=Bu=function(a){return a===lr||a===qA?new db(a):OA(a)},!xA&&js(Gs)&&Gr!==Object.prototype)){pb=Gr.then,VA||ub(Gr,"then",function(e,t){var r=this;return new lr(function(i,s){zr(pb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Gr.constructor}catch(a){}lb&&lb(Gr,Us)}EA({global:!0,constructor:!0,wrap:!0,forced:gb},{Promise:lr});PA(lr,Ws,!1,!0);wA(Ws)});var $b=f((cO,Rb)=>{"use strict";var jA=fe(),Ab=jA("iterator"),Lb=!1;try{kb=0,ju={next:function(){return{done:!!kb++}},return:function(){Lb=!0}},ju[Ab]=function(){return this},Array.from(ju,function(){throw 2})}catch(a){}var kb,ju;Rb.exports=function(a,e){try{if(!e&&!Lb)return!1}catch(i){return!1}var t=!1;try{var r={};r[Ab]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Qu=f((dO,Mb)=>{"use strict";var QA=ur(),GA=$b(),WA=jr().CONSTRUCTOR;Mb.exports=WA||!GA(function(a){QA.all(a).then(void 0,function(){})})});var Cb=f(()=>{"use strict";var YA=ue(),zA=De(),KA=at(),XA=Qr(),JA=qs(),ZA=Vs(),eL=Qu();YA({target:"Promise",stat:!0,forced:eL},{all:function(e){var t=this,r=XA.f(t),i=r.resolve,s=r.reject,n=JA(function(){var o=KA(t.resolve),u=[],l=0,c=1;ZA(e,function(d){var p=l++,h=!1;c++,zA(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Vb=f(()=>{"use strict";var tL=ue(),rL=ze(),iL=jr().CONSTRUCTOR,Wu=ur(),aL=ht(),sL=ie(),nL=qr(),Db=Wu&&Wu.prototype;tL({target:"Promise",proto:!0,forced:iL,real:!0},{catch:function(a){return this.then(void 0,a)}});!rL&&sL(Wu)&&(Gu=aL("Promise").prototype.catch,Db.catch!==Gu&&nL(Db,"catch",Gu,{unsafe:!0}));var Gu});var _b=f(()=>{"use strict";var oL=ue(),uL=De(),lL=at(),cL=Qr(),dL=qs(),pL=Vs(),hL=Qu();oL({target:"Promise",stat:!0,forced:hL},{race:function(e){var t=this,r=cL.f(t),i=r.reject,s=dL(function(){var n=lL(t.resolve);pL(e,function(o){uL(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Ob=f(()=>{"use strict";var mL=ue(),fL=Qr(),bL=jr().CONSTRUCTOR;mL({target:"Promise",stat:!0,forced:bL},{reject:function(e){var t=fL.f(this),r=t.reject;return r(e),t.promise}})});var Yu=f((yO,Bb)=>{"use strict";var gL=st(),vL=Ve(),SL=Qr();Bb.exports=function(a,e){if(gL(a),vL(e)&&e.constructor===a)return e;var t=SL.f(a),r=t.resolve;return r(e),t.promise}});var qb=f(()=>{"use strict";var yL=ue(),TL=ht(),Nb=ze(),IL=ur(),Fb=jr().CONSTRUCTOR,EL=Yu(),xL=TL("Promise"),PL=Nb&&!Fb;yL({target:"Promise",stat:!0,forced:Nb||Fb},{resolve:function(e){return EL(PL&&this===xL?IL:this,e)}})});var Ub=f(()=>{"use strict";wb();Cb();Vb();_b();Ob();qb()});var Gb=f(()=>{"use strict";var wL=ue(),kL=ze(),Ys=ur(),AL=me(),jb=ht(),Qb=ie(),LL=gu(),Hb=Yu(),RL=qr(),Ku=Ys&&Ys.prototype,$L=!!Ys&&AL(function(){Ku.finally.call({then:function(){}},function(){})});wL({target:"Promise",proto:!0,real:!0,forced:$L},{finally:function(a){var e=LL(this,jb("Promise")),t=Qb(a);return this.then(t?function(r){return Hb(e,a()).then(function(){return r})}:a,t?function(r){return Hb(e,a()).then(function(){throw r})}:a)}});!kL&&Qb(Ys)&&(zu=jb("Promise").prototype.finally,Ku.finally!==zu&&RL(Ku,"finally",zu,{unsafe:!0}));var zu});var Yb=f((kO,Wb)=>{"use strict";tf();Ub();Gb();var ML=Mt();Wb.exports=ML("Promise","finally")});var Kb=f((AO,zb)=>{"use strict";var CL=Yb();zb.exports=CL});var zs=f((LO,Xb)=>{"use strict";var DL=Kb();Xb.exports=DL});var cg=f(()=>{"use strict";var YL=ue(),zL=Ho().values;YL({target:"Object",stat:!0},{values:function(e){return zL(e)}})});var pg=f((hB,dg)=>{"use strict";cg();var KL=Mr();dg.exports=KL.Object.values});var mg=f((mB,hg)=>{"use strict";var XL=pg();hg.exports=XL});var Xr=f((fB,fg)=>{"use strict";var JL=mg();fg.exports=JL});var Vg=f(()=>{"use strict";var SR=ue(),yR=Cr(),TR=Nr(),IR=wi(),ER=ki();SR({target:"Array",proto:!0},{at:function(e){var t=yR(this),r=TR(t),i=IR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});ER("at")});var Og=f((wN,_g)=>{"use strict";Vg();var xR=Mt();_g.exports=xR("Array","at")});var Ng=f((kN,Bg)=>{"use strict";var PR=Og();Bg.exports=PR});var Bt=f((AN,Fg)=>{"use strict";var wR=Ng();Fg.exports=wR});var yl=f((bq,Tv)=>{"use strict";var l$=tr();Tv.exports=Array.isArray||function(e){return l$(e)==="Array"}});var Ev=f((gq,Iv)=>{"use strict";var c$=TypeError,d$=9007199254740991;Iv.exports=function(a){if(a>d$)throw c$("Maximum allowed index exceeded");return a}});var wv=f((vq,Pv)=>{"use strict";var p$=yl(),h$=Nr(),m$=Ev(),f$=Vr(),xv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?f$(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&p$(d)?(p=h$(d),u=xv(a,e,d,p,u,s-1)-1):(m$(u+1),a[u]=d),u++),l++;return u};Pv.exports=xv});var Rv=f((Sq,Lv)=>{"use strict";var kv=yl(),b$=bu(),g$=Ve(),v$=fe(),S$=v$("species"),Av=Array;Lv.exports=function(a){var e;return kv(a)&&(e=a.constructor,b$(e)&&(e===Av||kv(e.prototype))?e=void 0:g$(e)&&(e=e[S$],e===null&&(e=void 0))),e===void 0?Av:e}});var Mv=f((yq,$v)=>{"use strict";var y$=Rv();$v.exports=function(a,e){return new(y$(a))(e===0?0:e)}});var Cv=f(()=>{"use strict";var T$=ue(),I$=wv(),E$=at(),x$=Cr(),P$=Nr(),w$=Mv();T$({target:"Array",proto:!0},{flatMap:function(e){var t=x$(this),r=P$(t),i;return E$(e),i=w$(t,0),i.length=I$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Dv=f(()=>{"use strict";var k$=ki();k$("flatMap")});var _v=f((Pq,Vv)=>{"use strict";Cv();Dv();var A$=Mt();Vv.exports=A$("Array","flatMap")});var Bv=f((wq,Ov)=>{"use strict";var L$=_v();Ov.exports=L$});var Tl=f((kq,Nv)=>{"use strict";var R$=Bv();Nv.exports=R$});var ta=f((Aq,Fv)=>{"use strict";var $$=Li(),M$=String;Fv.exports=function(a){if($$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return M$(a)}});var Il=f((Lq,qv)=>{"use strict";qv.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 jv=f((Rq,Hv)=>{"use strict";var C$=le(),D$=$t(),V$=ta(),xl=Il(),Uv=C$("".replace),_$=RegExp("^["+xl+"]+"),O$=RegExp("(^|[^"+xl+"])["+xl+"]+$"),El=function(a){return function(e){var t=V$(D$(e));return a&1&&(t=Uv(t,_$,"")),a&2&&(t=Uv(t,O$,"$1")),t}};Hv.exports={start:El(1),end:El(2),trim:El(3)}});var Yv=f(($q,Wv)=>{"use strict";var B$=Ko().PROPER,N$=me(),Qv=Il(),Gv="\u200B\x85\u180E";Wv.exports=function(a){return N$(function(){return!!Qv[a]()||Gv[a]()!==Gv||B$&&Qv[a].name!==a})}});var Pl=f((Mq,zv)=>{"use strict";var F$=jv().start,q$=Yv();zv.exports=q$("trimStart")?function(){return F$(this)}:"".trimStart});var Xv=f(()=>{"use strict";var U$=ue(),Kv=Pl();U$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Kv},{trimLeft:Kv})});var Zv=f(()=>{"use strict";Xv();var H$=ue(),Jv=Pl();H$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Jv},{trimStart:Jv})});var tS=f((Oq,eS)=>{"use strict";Zv();var j$=Mt();eS.exports=j$("String","trimLeft")});var iS=f((Bq,rS)=>{"use strict";var Q$=tS();rS.exports=Q$});var sS=f((Nq,aS)=>{"use strict";var G$=iS();aS.exports=G$});var TS=f(()=>{"use strict"});var IS=f(()=>{"use strict"});var xS=f((IH,ES)=>{"use strict";var fM=Ve(),bM=tr(),gM=fe(),vM=gM("match");ES.exports=function(a){var e;return fM(a)&&((e=a[vM])!==void 0?!!e:bM(a)==="RegExp")}});var wS=f((EH,PS)=>{"use strict";var SM=st();PS.exports=function(){var a=SM(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 LS=f((xH,AS)=>{"use strict";var yM=De(),TM=Ke(),IM=yi(),EM=wS(),kS=RegExp.prototype;AS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in kS)&&!TM(a,"flags")&&IM(kS,a)?yM(EM,a):e}});var $S=f((PH,RS)=>{"use strict";var Cl=le(),xM=Cr(),PM=Math.floor,$l=Cl("".charAt),wM=Cl("".replace),Ml=Cl("".slice),kM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,AM=/\$([$&'`]|\d{1,2})/g;RS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=AM;return i!==void 0&&(i=xM(i),u=kM),wM(s,u,function(l,c){var d;switch($l(c,0)){case"$":return"$";case"&":return a;case"`":return Ml(e,0,t);case"'":return Ml(e,n);case"<":d=i[Ml(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=PM(p/10);return h===0?l:h<=o?r[h-1]===void 0?$l(c,1):r[h-1]+$l(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var DS=f(()=>{"use strict";var LM=ue(),RM=De(),Vl=le(),MS=$t(),$M=ie(),MM=$r(),CM=xS(),ri=ta(),DM=Ii(),VM=LS(),_M=$S(),OM=fe(),BM=ze(),NM=OM("replace"),FM=TypeError,Dl=Vl("".indexOf),qM=Vl("".replace),CS=Vl("".slice),UM=Math.max;LM({target:"String",proto:!0},{replaceAll:function(e,t){var r=MS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!MM(e)){if(i=CM(e),i&&(s=ri(MS(VM(e))),!~Dl(s,"g")))throw new FM("`.replaceAll` does not allow non-global regexes");if(n=DM(e,NM),n)return RM(n,e,r,t);if(BM&&i)return qM(ri(r),e,t)}for(o=ri(r),u=ri(e),l=$M(t),l||(t=ri(t)),c=u.length,d=UM(1,c),p=Dl(o,u);p!==-1;)h=l?ri(t(u,p,o)):_M(u,o,p,[],void 0,t),b+=CS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Dl(o,u,p+d);return m<o.length&&(b+=CS(o,m)),b}})});var _S=f((AH,VS)=>{"use strict";TS();IS();DS();var HM=Mt();VS.exports=HM("String","replaceAll")});var BS=f((LH,OS)=>{"use strict";var jM=_S();OS.exports=jM});var FS=f((RH,NS)=>{"use strict";var QM=BS();NS.exports=QM});var US=f(($H,qS)=>{"use strict";var GM=wi(),WM=ta(),YM=$t(),zM=RangeError;qS.exports=function(e){var t=WM(YM(this)),r="",i=GM(e);if(i<0||i===1/0)throw new zM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var WS=f((MH,GS)=>{"use strict";var QS=le(),KM=Vo(),HS=ta(),XM=US(),JM=$t(),ZM=QS(XM),eC=QS("".slice),tC=Math.ceil,jS=function(a){return function(e,t,r){var i=HS(JM(e)),s=KM(t),n=i.length,o=r===void 0?" ":HS(r),u,l;return s<=n||o===""?i:(u=s-n,l=ZM(o,tC(u/o.length)),l.length>u&&(l=eC(l,0,u)),a?i+l:l+i)}};GS.exports={start:jS(!1),end:jS(!0)}});var zS=f((CH,YS)=>{"use strict";var rC=ir();YS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(rC)});var KS=f(()=>{"use strict";var iC=ue(),aC=WS().start,sC=zS();iC({target:"String",proto:!0,forced:sC},{padStart:function(e){return aC(this,e,arguments.length>1?arguments[1]:void 0)}})});var JS=f((_H,XS)=>{"use strict";KS();var nC=Mt();XS.exports=nC("String","padStart")});var ey=f((OH,ZS)=>{"use strict";var oC=JS();ZS.exports=oC});var ry=f((BH,ty)=>{"use strict";var uC=ey();ty.exports=uC});var sd="2.0.128-dev.d52ca770.0";var Pe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Pe||{}),pt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(pt||{});var ms=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ms||{}),io=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(io||{});var ao=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ao||{}),fs=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(fs||{});var BT=_(Fe(),1);import{assertNever as ih,assertNonNullable as Tx,isNonNullable as ys,ValueSubject as Oo,Subject as Ix,Subscription as Ex,merge as xx,observableFrom as Px,fromEvent as Zp,map as eh,tap as th,filterChanged as wx,isNullable as Bo,ErrorCategory as rh}from"@vkontakte/videoplayer-shared/es2015";var Jp=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 Ts=class{constructor(e){this.connection$=new Oo(void 0);this.castState$=new Oo("NOT_AVAILABLE");this.errorEvent$=new Ix;this.realCastState$=new Oo("NOT_AVAILABLE");this.subscription=new Ex;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=ys((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||Jp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:rh.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(){ys(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Bo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Bo(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(Zp(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 ih(i.sessionState)}})).add(xx(Zp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(th(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),eh(i=>i.castState)),Px([r.getCastState()])).pipe(wx(),eh(kx),th(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=ys(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Tx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Bo(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"?ys(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:rh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},kx=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 ih(a)}};var fc=_(Fe(),1),ST=_(Fr(),1),yT=_(du(),1);var og=_(zs(),1);import{assertNever as Jb}from"@vkontakte/videoplayer-shared/es2015";var be=(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:Jb(t)}return a},Ks=(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:Jb(e)}};var w=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as VL,Subject as Xs,merge as Zb}from"@vkontakte/videoplayer-shared/es2015";var O=class{constructor(e){this.transitionStarted$=new Xs;this.transitionEnded$=new Xs;this.transitionUpdated$=new Xs;this.forceChanged$=new Xs;this.stateChangeStarted$=Zb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Zb(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||VL(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}};import{assertNever as _L}from"@vkontakte/videoplayer-shared/es2015";var eg=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 _L(a)}};import{assertNever as Kr,assertNonNullable as cr,debounce as tg,ErrorCategory as rg,fromEvent as dr,isNonNullable as ig,map as ag,merge as sg,observableFrom as OL,Subject as BL,Subscription as Xu,timeout as NL,getHighestQuality as FL}from"@vkontakte/videoplayer-shared/es2015";var qL=5,UL=5,HL=500,ng=7e3,Fi=class{constructor(e){this.subscription=new Xu;this.loadMediaTimeoutSubscription=new Xu;this.videoState=new O("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:Kr(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:Kr(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:Kr(e)}break}default:Kr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(eg(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 Xu;this.subscription.add(e),this.subscription.add(sg(this.videoState.stateChangeStarted$.pipe(ag(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(ag(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 BL;e.add(i.pipe(tg(HL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(dr(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)>qL)&&i.next(o),s=o})),e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(dr(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<UL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(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:Kr(n)}}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=sg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,OL(["init"])).pipe(tg(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"),w(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),w(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"),w(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"),w(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"&&w(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];cr(c);let d=FL(Object.keys(c));cr(d);let p=c[d];cr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];cr(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];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];cr(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];cr(c),r=be(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:rg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Kr(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 ig(o)&&(n.metadata.title=o),ig(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(NL(ng).subscribe(()=>s(`timeout(${ng})`)))});(0,og.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:rg.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var vl=_(Fe(),1);import{clearVideoElement as lg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as jL}from"@vkontakte/videoplayer-shared/es2015";var ug=a=>{try{a.pause(),a.playbackRate=0,jL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as QL,Subscription as GL}from"@vkontakte/videoplayer-shared/es2015";var Ju=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)}},Zu=window.WeakMap?new WeakMap:new Ju,el=window.WeakMap?new WeakMap:new Map,WL=(a,e=20)=>{let t=0;return QL(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},we=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?lg(r):(r=document.createElement("video"),a.appendChild(r)),Zu.set(r,i);let s=new GL;return s.add(WL(r,e)),el.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},ke=a=>{let e=el.get(a);e==null||e.unsubscribe(),el.delete(a);let t=Zu.get(a);Zu.delete(a),t?lg(a):ug(a)};var rl=_(Xr(),1);import{assertNonNullable as qi,isNonNullable as ot,isNullable as tR,fromEvent as Jr,merge as bg,observableFrom as gg,filterChanged as vg,map as Ui,Subject as Sg,Subscription as rR,ValueSubject as iR,ErrorCategory as aR}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as tl,isNullable as ZL,Subscription as eR}from"@vkontakte/videoplayer-shared/es2015";var Js=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=ZL(i),l=new eR;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},nt=(a,e,t)=>Js(e,()=>a.loop,r=>{tl(r)&&(a.loop=r)},{onError:t}),Ae=(a,e,t,r)=>Js(e,()=>({muted:a.muted,volume:a.volume}),i=>{tl(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}),qe=(a,e,t,r)=>Js(e,()=>a.playbackRate,i=>{tl(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Dt=Js;var sR=a=>["__",a.language,a.label].join("|"),nR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},il=class a{constructor(e){this.available$=new Sg;this.current$=new iR(void 0);this.error$=new Sg;this.subscription=new rR;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:aR.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(Dt(t.internalTextTracks,()=>(0,rl.default)(this.internalTracks),s=>{ot(s)&&this.setInternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Dt(t.externalTextTracks,()=>(0,rl.default)(this.externalTracks),s=>{ot(s)&&this.setExternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ui(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Dt(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(Dt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qi(this.video);let{textTracks:e}=this.video;this.subscription.add(Jr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(bg(Jr(e,"addtrack"),Jr(e,"removetrack"),gg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),vg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(bg(Jr(e,"change"),gg(["init"])).pipe(Ui(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ui(r=>r&&this.htmlTextTrackToITextTrack(r).id),vg()).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(Jr(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(Jr(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;ot(t.align)&&(i.align=t.align),ot(t.position)&&(i.position=t.position),ot(t.size)&&(i.size=t.size),ot(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){qi(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:sR(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){qi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(tR(e)||!nR(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){qi(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){qi(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)}},Ue=il;var bt=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 yg=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},al=a=>{let e=yg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Tg=a=>{let e=yg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as He,map as Vt,merge as Rg,filterChanged as mR,isNonNullable as $g,Subject as fR,filter as Mg,mapTo as Cg,combine as bR,once as gR,ErrorCategory as vR,ValueSubject as Dg}from"@vkontakte/videoplayer-shared/es2015";var oR=3,Ig=(a,e,t=oR)=>{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 Zs=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 Eg=_(Fe(),1);var Hi=()=>{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 en=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,Eg.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=Hi()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return x(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 tn=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 Je=()=>window.ManagedMediaSource||window.MediaSource,rn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},xg=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Pg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var wg,uR=()=>x(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($(P({},a),{video:$(P({},a.video),{contentType:Ag})})),window.navigator.mediaCapabilities.decodingInfo($(P({},a),{video:$(P({},a.video),{contentType:kg})}))]);wg={DASH_WEBM_AV1:e,DASH_WEBM:t}});uR().catch(a=>{console.error(a)});var lR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',cR='video/mp4; codecs="hev1.1.6.L93.B0"',kg='video/webm; codecs="vp09.00.10.08"',Ag='video/webm; codecs="av01.0.00M.08"',dR='audio/mp4; codecs="mp4a.40.2"',pR='audio/webm; codecs="opus"',an=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 wg}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,p,h,m,b,g,v,S,y,E;this._video=document.createElement("video");try{this._protocols={mms:rn(),mse:xg(),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 I=!!((c=(l=Je())==null?void 0:l.isTypeSupported)!=null&&c.call(l,lR)),L=!!((p=(d=Je())==null?void 0:d.isTypeSupported)!=null&&p.call(d,cR)),M=!!((m=(h=Je())==null?void 0:h.isTypeSupported)!=null&&m.call(h,dR));this._codecs={h264:I,h265:L,vp9:!!((g=(b=Je())==null?void 0:b.isTypeSupported)!=null&&g.call(b,kg)),av1:!!((S=(v=Je())==null?void 0:v.isTypeSupported)!=null&&S.call(v,Ag)),aac:M,opus:!!((E=(y=Je())==null?void 0:y.isTypeSupported)!=null&&E.call(y,pR)),mpeg:(I||L)&&M},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(I){console.error(I)}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 Lg="audio/mpeg",sn=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,Lg))},this._codecs={mp3:!!((i=(r=Je())==null?void 0:r.isTypeSupported)!=null&&i.call(r,Lg))}}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}};import{ValueSubject as hR}from"@vkontakte/videoplayer-shared/es2015";var sl=class{constructor(){this.isInited$=new hR(!1);this._displayChecker=new tn,this._deviceChecker=new en(this._displayChecker),this._browserChecker=new Zs,this._videoChecker=new an(this._deviceChecker,this._browserChecker),this._audioChecker=new sn,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 x(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},N=new sl;var Le=a=>{let e=y=>He(a,y).pipe(Cg(void 0)),r=Rg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>He(a,y))).pipe(Vt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),mR()),i=Rg(He(a,"progress"),He(a,"timeupdate")).pipe(Vt(()=>Ig(a.buffered,a.currentTime))),s=N.browser.isSafari?bR({play:e("play").pipe(gR()),playing:e("playing")}).pipe(Cg(void 0)):e("playing"),n=He(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=He(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=He(a,"error").pipe(Mg(()=>!!(a.error||a.played.length)),Vt(()=>{var E;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:vR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=He(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new fR,d=.3,p;l.subscribe(y=>{a.loop&&$g(p)&&$g(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(Mg(()=>!a.error&&p!==a.duration)),m=He(a,"enterpictureinpicture"),b=He(a,"leavepictureinpicture"),g=new Dg(Tg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Dg(al(a));return He(a,"fullscreenchange").pipe(Vt(()=>al(a))).subscribe(v),{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$:He(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as _t}from"@vkontakte/videoplayer-shared/es2015";var Ot=a=>{switch(a){case"mobile":return _t.Q_144P;case"lowest":return _t.Q_240P;case"low":return _t.Q_360P;case"sd":case"medium":return _t.Q_480P;case"hd":case"high":return _t.Q_720P;case"fullhd":case"full":return _t.Q_1080P;case"quadhd":case"quad":return _t.Q_1440P;case"ultrahd":case"ultra":return _t.Q_2160P}};var Nt=_(Bt(),1),Kg=_(Fe(),1),un=_(Fr(),1);import{isNonNullable as Oe,isNullable as Gg,now as Xg,isHigher as Wg,isHigherOrEqual as ll,isInvariantQuality as Yg,isLowerOrEqual as cl,videoSizeToQuality as LR,assertNotEmptyArray as Jg,assertNonNullable as RR}from"@vkontakte/videoplayer-shared/es2015";var nl=!1,gt={},qg=a=>{nl=a},Ug=()=>{gt={}},Hg=a=>{a(gt)},ji=(a,e)=>{var t;nl&&(gt.meta=(t=gt.meta)!=null?t:{},gt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var r,i;if(!nl)return;gt.series=(r=gt.series)!=null?r:{};let t=(i=gt.series[this.name])!=null?i:[];t.push([Date.now(),e]),gt.series[this.name]=t}};import{isHigher as kR,isHigherOrEqual as DN,isLower as jg,isLowerOrEqual as VN,isNonNullable as nn,isNullable as AR,videoHeightToQuality as on}from"@vkontakte/videoplayer-shared/es2015";function ol({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function ul({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&ol({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Qi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return AR(a)||nn(a.min)&&nn(a.max)&&jg(a.max,a.min)||nn(a.min)&&e&&kR(a.min,e)||nn(a.max)&&t&&jg(a.max,t)}function Qg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Qi({limits:{max:a!=null&&a.max?on(a.max):void 0,min:a!=null&&a.min?on(a.min):void 0},highestAvailableQuality:e?on(e):void 0,lowestAvailableQuality:t?on(t):void 0})}var $R=new Ie("best_bitrate"),Zg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var dl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Gi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Xg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ev='Assertion "ABR Tracks is empty array" failed',ln=(a,e,t,r)=>{var u;let i=[...e].sort(dl(1)),s=[...t].sort(dl(1)),n=s.filter(l=>Oe(l.bitrate)&&Oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,Kg.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},zg=a=>"quality"in a,tv=(a,e,t,r)=>{var n;let i=Oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&Oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Xg()-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=zg(o)?"video":"audio",l=zg(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},MR=(a,e)=>Math.log(e)/Math.log(a),CR=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&N.display.pixelRatio){let i=N.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=MR(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return ul({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}},Ft=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{var Q,R,G,q,J,A;Jg(a,ev);let{containerSizeFactor:b,containerSizeLimit:g}=CR({container:e,tuning:r,limits:i}),v=r.considerPlaybackRate&&Oe(o)?o:1,S=a.filter(T=>!Yg(T.quality)).sort((T,V)=>Wg(T.quality,V.quality)?-1:1),y=(Q=(0,Nt.default)(S,-1))==null?void 0:Q.quality,E=(R=(0,Nt.default)(S,0))==null?void 0:R.quality,I=Qi({limits:i,lowestAvailableQuality:y,highestAvailableQuality:E}),L=v*Zg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),M={},C=S.filter(T=>{let V=!0;if(g)if(T.size)V=T.size.width<=g.width&&T.size.height<=g.height;else{let ye=g&&LR(g);V=ye?cl(T.quality,ye):!0}if(!V)return M[T.quality]="FitsContainer",!1;let Y=h||t,U=Oe(Y)&&isFinite(Y)&&Oe(T.bitrate)?Y-s>=T.bitrate*L:!0,Me=ul({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===T.quality;if(!U&&!Me)return M[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Oe(r.minBufferToSwitchUp)&&u&&!Yg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Wg(T.quality,u.quality))return M[T.quality]="Buffer",!1;if(!!d&&ll(T.quality,d)&&!Me)return M[T.quality]="DroppedFramesLimit",!1;if(!!p&&ll(T.quality,p)&&!Me)return M[T.quality]="StallsLimit",!1;let he=I||(Gg(i==null?void 0:i.max)||cl(T.quality,i.max))&&(Gg(i==null?void 0:i.min)||ll(T.quality,i.min)),Se=Oe(c)&&!c?cl(T.quality,r.backgroundVideoQualityLimit):!0;return!he||!Se?(M[T.quality]="FitsQualityLimits",!1):!0})[0];C&&C.bitrate&&$R.next(C.bitrate);let j=(G=C!=null?C:(0,Nt.default)(S,-1))!=null?G:a[0];return j.quality!==((q=l==null?void 0:l.last)==null?void 0:q.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(
|
|
12
|
+
${a.map(T=>{var V,Y;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${(V=T.size)==null?void 0:V.width}:${(Y=T.size)==null?void 0:Y.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,un.default)(r!=null?r:{}).map(([T,V])=>`${T}: ${V}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${b},
|
|
21
|
-
containerSizeLimit: ${(
|
|
21
|
+
containerSizeLimit: ${(J=g==null?void 0:g.width)!=null?J:0} x ${(A=g==null?void 0:g.height)!=null?A:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${h},
|
|
24
24
|
reserve: ${s},
|
|
25
25
|
playbackRate: ${o},
|
|
26
26
|
playbackRateFactor: ${v},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${L},
|
|
29
29
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
30
30
|
droppedVideoMaxQualityLimit: ${d},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${p},
|
|
32
|
-
limitsAreInvalid: ${
|
|
32
|
+
limitsAreInvalid: ${I},
|
|
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,un.default)(M).map(([T,V])=>`${T}: ${V}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${C==null?void 0:C.quality}
|
|
41
|
+
[selected video track] ${j==null?void 0:j.quality}
|
|
42
|
+
`}),tv(r,m,j,l)},rv=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;Jg(t,ev);let c=i.considerPlaybackRate&&Oe(s)?s:1,d=[...t].sort(dl(-1)),p=a.bitrate;RR(p);let h=c*Zg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,b=ln(a,e,t,i.minVideoAudioRatio),g=l||r;return Oe(g)&&isFinite(g)&&(m=d.find(S=>Oe(S.bitrate)&&Oe(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),m||(m=b),(m==null?void 0:m.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
|
|
43
43
|
[AUDIO TRACKS ABR]
|
|
44
44
|
[available audio tracks]
|
|
45
45
|
${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,un.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
@@ -60,14 +60,14 @@ var fI=Object.create;var lo=Object.defineProperty,bI=Object.defineProperties,gI=
|
|
|
60
60
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
61
61
|
|
|
62
62
|
[selected audio track] ${m==null?void 0:m.id}
|
|
63
|
-
`}),m&&cv(i,u,m,o)};var oe=a=>new URL(a).hostname;import{assertNever as Iv,assertNonNullable as Ev,combine as vR,debounce as SR,ErrorCategory as xv,filter as Pv,filterChanged as yR,isNonNullable as El,map as dn,merge as wv,observableFrom as TR,once as IR,Subscription as ER,ValueSubject as xl,videoQualityToHeight as Av,videoSizeToQuality as xR}from"@vkontakte/videoplayer-shared/es2015";var vv=O(Ft(),1);var hv=O(Xe(),1);var pv=a=>{if(a instanceof DOMException&&(0,hv.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"))},Ae=(a,e)=>P(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!pv(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return pv(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as un,isNullable as eR,assertNonNullable as Ji}from"@vkontakte/videoplayer-shared/es2015";var fv=O(Jr(),1);import{isNonNullable as mv,assertNonNullable as on,now as J$}from"@vkontakte/videoplayer-shared/es2015";function ue(){return J$()}function Sl(a){return ue()-a}function yl(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 bv(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ei(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;on(c);let L=Sl(c),j;if(L<b){j=b-L,setTimeout(g,j);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,R()},v=L=>(s=L,U),S=L=>(d=L,U),T=()=>(h="json",U),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=L=>(p=L,U),R=()=>{c=ue(),n=new i,n.open("get",a);let L=0,j,_=0,z=()=>(on(c),Math.max(c,Math.max(j||0,_||0)));if(s&&n.addEventListener("progress",k=>{let y=ue();s.updateChunk&&k.loaded>L&&(s.updateChunk(z(),k.loaded-L),L=k.loaded,j=y)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;on(n);let k=n.status;if(k>=200&&k<300){let{response:y,responseType:C}=n,Q=y==null?void 0:y.byteLength;if(typeof Q=="number"&&s){let N=Q-L;N&&s.updateChunk&&s.updateChunk(z(),N)}C==="json"&&(!y||!(0,fv.default)(y).length)?I():(d&&d(),e(y))}else I()}),n.addEventListener("error",()=>{I()}),p){let k=()=>{on(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(_=ue(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),U},U={withBitrateReporting:v,withParallel:E,withJSONResponse:T,withRetryCount:L=>(l=L,U),withRetryInterval:(L,j)=>(mv(L)&&(b=L),mv(j)&&(m=j),U),withTimeout:L=>(o=L,U),withFinally:S,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return U}var Ki=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var gv=O(Jr(),1);var Xi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ue(),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=ue()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ei(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ue()}_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=ue();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,gv.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}};import{Subject as tR}from"@vkontakte/videoplayer-shared/es2015";var ln=1e4,Tl=3;var rR=6e4,iR=10,aR=1,sR=500,Zi=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 tR,this.chunkRateEstimator=new Ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=yl(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=yl(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||{};!ev({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,vv.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||un(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=()=>{bv(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Xi(Tl,ln,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 I=s&&(!c||c===this.rep);return I||t("Not running!"),I},p=(I,E,R)=>{u&&u.abort(),u=ei(this.urlResolver.resolve(I,!1),E,R,()=>this._retryCallback()).withTimeout(ln).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Tl).withFinally(()=>{u=null}).send()},h=(I,E,R)=>{Ji(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let R=ue()-1e4,D=0;for(let M=0;M<this.bufferStates.length;M++){let q=this.bufferStates[M];I=Math.min(I,q.buf),q.ts<R&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${I} drop=${D} jitter=${this.sourceJitter}`);let Z=I-aR;this.sourceJitter>=0?Z-=this.sourceJitter/2:this.sourceJitter-=1,Z>3?m(1.15):Z>1?m(1.1):Z>.3?m(1.05):m(1)}},v=I=>{let E,R=()=>E&&E.start?E.start.length:0,D=k=>E.start[k]/1e3,Z=k=>E.dur[k]/1e3,M=k=>E.fragIndex+k,q=(k,y)=>({chunkIdx:M(k),startTS:D(k),dur:Z(k),discontinuity:y}),U=()=>{let k=0;if(E&&E.dur){let y=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,C=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=y;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let N=E.dur.length-1;for(;N>=0&&(Q-=E.dur[N],!(Q<=0));--N);k=Math.min(N,E.dur.length-1-C),k=Math.max(k,0)}return q(k,!0)},L=k=>{let y=R();if(!(y<=0)){if(un(k)){for(let C=0;C<y;C++)if(D(C)>k)return q(C)}return U()}},j=k=>{let y=R(),C=k?k.chunkIdx+1:0,Q=C-E.fragIndex;if(!(y<=0)){if(!k||Q<0||Q-y>iR)return t(`Resync: offset=${Q} bChunks=${y} chunk=`+JSON.stringify(k)),U();if(!(Q>=y))return q(C-E.fragIndex,!1)}},_=(k,y,C)=>{l&&l.abort(),l=ei(this.urlResolver.resolve(k,!0,this.lowLatency),y,C,()=>this._retryCallback()).withTimeout(ln).withRetryCount(Tl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,y)=>{_(I,C=>{if(!d())return;E=C;let Q=!!E.lowLatency;Q!==this.lowLatency&&b(Q);let N=0;for(let Re=0;Re<E.dur.length;++Re)N+=E.dur[Re];N>0&&(Ji(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(N/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,k(L(y))},()=>this._handleNetworkError())},nextChunk:j}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ji(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:R}=this.params,D=v(e.jidxUrl),Z,M,q,U,L=0,j,_,z,k=()=>{j&&(clearTimeout(j),j=void 0);let G=Math.max(sR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=L+G,be=ue(),ge=Math.min(1e4,ce-be);L=be;let xt=()=>{l||d()&&D.seek(()=>{d()&&(L=ue(),y(),k())})};ge>0?j=window.setTimeout(()=>{this.paused?k():xt()},ge):xt()},y=()=>{let G;for(;G=D.nextChunk(U);)U=G,hi(G);let ce=D.nextChunk(q);if(ce){if(q&&ce.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}Re(ce)}else k()},C=(G,ce)=>{if(!d()||!this.sourceBuffer)return;let be,ge,xt,xr=Pt=>{window.setTimeout(()=>{d()&&C(G,ce)},Pt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),xr(100);else{let Pt=ue(),Kt=E.currentTime;!this.paused&&E.buffered.length>1&&_===Kt&&Pt-z>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),_!==Kt&&(_=Kt,z=Pt);let Pr=this._getBufferSizeSec();if(Pr>30)R(`Buffered ${Pr} seconds; delaying appendBuffer`),xr(2e3);else try{this.sourceBuffer.appendBuffer(G),this.videoPlayStarted?(this.bufferStates.push({ts:Pt,buf:Pr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(mi){if(mi.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),xt=this.sourceBuffer.buffered.length,xt!==0&&(be=this.sourceBuffer.buffered.start(0),ge=Kt,ge-be>4&&this.sourceBuffer.remove(be,ge-3)),xr(1e3);else throw mi}}},Q=()=>{M&&Z&&(R([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(q)]),C(M,function(){M=null,y()}))},N=G=>e.fragUrlTemplate.replace("%%id%%",G.chunkIdx),Re=G=>{d()&&h(N(G),(ce,be)=>{if(d()){if(be/=1e3,M=ce,q=G,n=G.startTS,be){let ge=Math.min(10,G.dur/be);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ge:ge}Q()}},()=>this._handleNetworkError())},hi=G=>{d()&&(Ji(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(N(G),!1)))},Er=G=>{d()&&(e.cachedHeader=G,C(G,()=>{Z=!0,Q()}))};s=!0,D.seek(G=>{if(d()){if(L=ue(),!G){k();return}U=G,!eR(I)||G.startTS>I?Re(G):(q=G,y())}},I),e.cachedHeader?Er(e.cachedHeader):p(e.headerUrl,Er,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),un(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,Ji(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return un(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=ue();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!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&&Sl(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=ue();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ei(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ln).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;Ae(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))},rR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Tv=O(qr(),1);import{debounce as nR,filter as Sv,fromEvent as oR,interval as uR,isHigher as lR,isInvariantQuality as cR,isLower as dR,merge as pR,Subject as yv,Subscription as hR}from"@vkontakte/videoplayer-shared/es2015";var Il=class{constructor(){this.onDroopedVideoFramesLimit$=new yv;this.subscription=new hR;this.playing=!1;this.tracks=[];this.forceChecker$=new yv;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&&!cR(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&&lR(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(oR(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=uR(this.droppedFramesChecker.checkTime).pipe(Sv(()=>this.playing),Sv(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(nR(this.droppedFramesChecker.checkTime)),r=pR(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,Tv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>dR(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}},cn=Il;import{map as mR,Observable as fR}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as bR}from"@vkontakte/videoplayer-shared/es2015";var ea=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var gR=(a,e)=>new fR(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||ea()))},x(x({},r),e));i.observe(a);let s=bR(document,"visibilitychange").pipe(mR(n=>!document.hidden||ea())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),He=gR;var PR=["paused","playing","ready"],wR=["paused","playing","ready"],ta=class{constructor(e){this.subscription=new ER;this.videoState=new V("stopped");this.representations$=new xl([]);this.droppedFramesManager=new cn;this.maxSeekBackTime$=new xl(1/0);this.zeroTime$=new xl(void 0);this.liveOffset=new mr;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:xv.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=Nt(u.name))!=null?r:xR(u.video),d=u.bitrate/1e3,p=x({},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),El(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,Pl.default)(wR,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Pl.default)(PR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(he(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(he(this.params.source.url,u))}return;default:return Iv(e)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:xv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};wv(this.videoState.stateChangeStarted$.pipe(dn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(dn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Ee(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(oe(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=we(this.video);this.subscription.add(this.representations$.pipe(dn(i=>i.map(({track:s})=>s)),Pv(i=>!!i.length),IR()).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(yR(),dn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(vR({zeroTime:this.zeroTime$.pipe(Pv(El)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Fe(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(He(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&Av(i),min:s&&Av(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 Iv(i.to)}},t)).add(wv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,TR(["init"])).pipe(SR(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),xe(this.video)}createLiveDashPlayer(){let e=new Zi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&El(t)?t:Ut(e.map(({track:b})=>b),{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 b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;Ev(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;Ev(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(he(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var kv=ta;var hT=O(Xe(),1);var ut=(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)};import{assertNever as hC,assertNonNullable as mC,debounce as fC,ErrorCategory as lT,filter as cT,filterChanged as Ha,fromEvent as bC,isNonNullable as dT,map as hc,merge as qn,observableFrom as mc,once as pT,Subscription as gC}from"@vkontakte/videoplayer-shared/es2015";var pn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ti=class extends pn{constructor(){super(),this.listeners||pn.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)}},ra=class{constructor(){Object.defineProperty(this,"signal",{value:new ti,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ra.prototype[Symbol.toStringTag]="AbortController",ti.prototype[Symbol.toStringTag]="AbortSignal");function hn(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 wl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!hn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ia=hn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Lv=ia?wl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ia?Lv.fetch:window.fetch,tq=ia?Lv.Request:window.Request,me=ia?ra:window.AbortController,rq=ia?ti:window.AbortSignal;var lc=O(kl(),1);var In=O(Ft(),1);var gt=()=>window.ManagedMediaSource||window.MediaSource,mn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},zv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Kv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as xn,clientChecker as En}from"@vkontakte/videoplayer-shared/es2015";var je=document.createElement("video"),XR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',JR='video/mp4; codecs="hev1.1.6.L93.B0"',oS='video/webm; codecs="vp09.00.10.08"',uS='video/webm; codecs="av01.0.00M.08"',ZR='audio/mp4; codecs="mp4a.40.2"',eM='audio/webm; codecs="opus"',Xv,Jv,aa={mms:mn(),mse:zv(),hls:!!((Xv=je.canPlayType)!=null&&Xv.call(je,"application/x-mpegurl")||(Jv=je.canPlayType)!=null&&Jv.call(je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Zv,eS,ke={mp4:!!((Zv=je.canPlayType)!=null&&Zv.call(je,"video/mp4")),webm:!!((eS=je.canPlayType)!=null&&eS.call(je,"video/webm")),cmaf:!0},bn,tS,gn,rS,vn,iS,Sn,aS,yn,sS,Tn,nS,Le={h264:!!((tS=(bn=gt())==null?void 0:bn.isTypeSupported)!=null&&tS.call(bn,XR)),h265:!!((rS=(gn=gt())==null?void 0:gn.isTypeSupported)!=null&&rS.call(gn,JR)),vp9:!!((iS=(vn=gt())==null?void 0:vn.isTypeSupported)!=null&&iS.call(vn,oS)),av1:!!((aS=(Sn=gt())==null?void 0:Sn.isTypeSupported)!=null&&aS.call(Sn,uS)),aac:!!((sS=(yn=gt())==null?void 0:yn.isTypeSupported)!=null&&sS.call(yn,ZR)),opus:!!((nS=(Tn=gt())==null?void 0:Tn.isTypeSupported)!=null&&nS.call(Tn,eM))},ri=(Le.h264||Le.h265)&&Le.aac,fr,tM=()=>P(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($(x({},a),{video:$(x({},a.video),{contentType:uS})})),window.navigator.mediaCapabilities.decodingInfo($(x({},a),{video:$(x({},a.video),{contentType:oS})}))]);fr={DASH_WEBM_AV1:e,DASH_WEBM:t}});tM().catch(a=>{console.error(a)});var ii=aa.hls&&ke.mp4,lS=()=>Object.keys(Le).filter(a=>Le[a]),cS=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=aa.mse&&(!r||!!window.MediaStreamTrack)||aa.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&ke.mp4&&ri;case"DASH_WEBM":return i&&ke.webm&&Le.vp9&&Le.opus;case"DASH_WEBM_AV1":return i&&ke.webm&&Le.av1&&Le.opus;case"DASH_STREAMS":return i&&(ke.mp4&&ri||ke.webm&&(Le.vp9||Le.av1)&&(Le.opus||Le.aac));case"DASH_LIVE":return i&&ke.mp4&&ri;case"DASH_LIVE_CMAF":return i&&ke.mp4&&ri&&ke.cmaf;case"DASH_ONDEMAND":return i&&ke.mp4&&ri;case"HLS":case"HLS_ONDEMAND":return ii||e&&i&&ke.mp4&&ri;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ii;case"MPEG":return ke.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return aa.webrtc&&aa.ws&&Le.h264&&(ke.mp4||ke.webm);default:return xn(s)}})},fn=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 fr?fr[t].smooth?[t,e]:fr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return fr?fr[t].powerEfficient?[t,e]:fr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:xn(a)}return[e,t]},dS=({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(En.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:xn(e)}return ii?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},pS=({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=En.isMac&&En.isSafari;if(En.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:xn(a)}else ii&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Ll=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],hS=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,In.default)(t.value.split("."),0)}for(let t of a){let r=(0,In.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,In.default)(e.value.split("."),0)};var CS=O(DS(),1);import{ErrorCategory as na}from"@vkontakte/videoplayer-shared/es2015";var VS=a=>{if(!a)return{id:"EmptyResponse",category:na.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:na.NETWORK,message:`UV Error ${a}`};let e=(0,CS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:na.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:na.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:na.PARSER,message:"Response is valid XML, but parser failed"}};var Ht=(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};import{abortable as nc,assertNonNullable as li,clientChecker as zD,combine as ci,ErrorCategory as ct,filter as Dn,filterChanged as Cn,flattenObject as qa,fromEvent as Tt,getTraceSubscriptionMethod as KD,interval as oc,isNonNullable as tT,isNullable as rT,map as Ua,merge as Tr,now as uc,Subject as Vn,Subscription as iT,tap as XD,throttle as JD,ValueSubject as ee}from"@vkontakte/videoplayer-shared/es2015";var wn=O(Xe(),1),oi=O(Ft(),1),An=O(kl(),1);var vM=(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)},SM=a=>window.clearTimeout(a),BS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),OS=!BS(window.requestIdleCallback)||!BS(window.cancelIdleCallback),Cl=OS?vM:window.requestIdleCallback,oa=OS?SM:window.cancelIdleCallback;var Gy=O(Js(),1);import{assertNever as yM,ErrorCategory as _S,clientChecker as Vl,Subject as NS}from"@vkontakte/videoplayer-shared/es2015";var TM=18,FS=!1;try{FS=Vl.isSafari&&!!Vl.macVersion&&Vl.macVersion<=TM}catch(a){console.error(a)}var Bl=class{constructor(e){this.bufferFull$=new NS;this.error$=new NS;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:_S.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return P(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 P(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 P(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};FS&&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:_S.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:yM(t)}}},qS=Bl;var Ol=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Qt,assertNonNullable as $e,clientChecker as OD,ErrorCategory as yt,fromEvent as ec,getExponentialDelay as tc,isNonNullable as ni,isNullable as fe,now as Pn,once as _D,Subject as ND,Subscription as FD,ValueSubject as vr}from"@vkontakte/videoplayer-shared/es2015";var F=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 ai=class extends F{};var ua=class extends F{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 la=class extends F{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 ca=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends F{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var da=class extends J{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 pa=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var br=class extends J{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 ma=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends J{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 ga=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var va=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Sa=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends J{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 Ta=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var xa=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends J{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 wa=class extends J{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 Aa=class extends J{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 ka=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var La=class extends J{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 $a=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var EM={ftyp:la,moov:ca,mvhd:da,moof:pa,mdat:ha,sidx:br,trak:ma,mdia:Sa,mfhd:Ea,tkhd:ya,traf:xa,tfhd:Pa,tfdt:wa,trun:Aa,minf:Ta,sv3d:fa,st3d:ba,prhd:ga,proj:Ia,equi:va,uuid:ua,stbl:ka,stsd:La,avc1:$a,unknown:ai},vt=class a{constructor(e={}){this.options=x({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=EM[e];return r?new r(t,new a):new ai(t,new a)}};var jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var PM=new TextDecoder("ascii"),wM=a=>PM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",AM=a=>{let e=new br(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})},kM=(a,e)=>{let r=new vt().parse(a),i=new jt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},LM=a=>{let t=new vt().parse(a),r=new jt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},$M=a=>{var i;let t=new vt().parse(a);return(i=new jt(t).find("sidx"))==null?void 0:i.timescale},RM=(a,e)=>{let r=new vt().parse(a),s=new jt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},MM=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 jt(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},US={validateData:wM,parseInit:MM,getIndexRange:()=>{},parseSegments:AM,parseFeedableSegmentChunk:kM,getChunkEndTime:RM,getServerLatencyTimestamps:LM,getTimescaleFromIndex:$M};var Ma=O(Xe(),1);import{assertNonNullable as Nl,isNonNullable as GS,isNullable as CM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as DM}from"@vkontakte/videoplayer-shared/es2015";var HS={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"}},jS=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=Ra(a,t),i=r in HS,s=i?HS[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=Ra(u),d=l*it(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}},Ra=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(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},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Ra(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:DM(e)}},gr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=jS(r);if(!e(i))return;i.type==="master"&&gr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},QS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=jS(a);return gr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(r=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var WS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],VM=[231,22612,22743,167,171,163,160,175],BM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return gr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=Ze(m,h);l=Ra(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ze(m,h):p===17545?i=Ze(m,h):p===21420&&l===475249515?u=Ze(m,h):p===374648427?gr(m,({tag:g,type:v,value:S})=>g===30321?(c=Ze(S,v)===1,!1):!0):s&&n&&(0,Ma.default)(WS,p)&&(o=!0),!o}),Nl(e,"Failed to parse webm Segment start"),Nl(t,"Failed to parse webm Segment end"),Nl(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}}}},OM=a=>{if(CM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},_M=(a,e)=>{let t=!1,r=!1,i=o=>GS(o.time)&&GS(o.position),s=[],n;return gr(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=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,Ma.default)(WS,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}}})},NM=a=>{let e=0,t=!1;try{gr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Ma.default)(VM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Ma.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},YS={validateData:QS,parseInit:BM,getIndexRange:OM,parseSegments:_M,parseFeedableSegmentChunk:NM};var Da=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return YS;case"mp4":return US}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Xl=O(my(),1),Fy=O(qr(),1),qy=O($y(),1),Uy=O(Ft(),1),Jl=O(Jr(),1);var Ry=O(Xe(),1),Ql=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,Ry.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as BD,isNullable as _y}from"@vkontakte/videoplayer-shared/es2015";var My=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Dy=a=>{var e;try{let t=CD(),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 CD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
63
|
+
`}),m&&tv(i,u,m,o)};var ce=a=>new URL(a).hostname;import{assertNever as hv,assertNonNullable as mv,combine as e$,debounce as t$,ErrorCategory as fv,filter as bv,filterChanged as r$,isNonNullable as bl,map as mn,merge as gv,observableFrom as i$,once as a$,Subscription as s$,ValueSubject as gl,videoQualityToHeight as vv,videoSizeToQuality as n$}from"@vkontakte/videoplayer-shared/es2015";var lv=_(Bt(),1);var av=_(Fe(),1);var iv=a=>{if(a instanceof DOMException&&(0,av.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"))},Re=(a,e)=>x(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!iv(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return iv(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as dn,isNullable as _R,assertNonNullable as zi}from"@vkontakte/videoplayer-shared/es2015";var nv=_(Xr(),1);import{isNonNullable as sv,assertNonNullable as cn,now as DR}from"@vkontakte/videoplayer-shared/es2015";function de(){return DR()}function pl(a){return de()-a}function hl(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 ov(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Zr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;cn(c);let R=pl(c),G;if(R<b){G=b-R,setTimeout(g,G);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,L()},v=R=>(s=R,Q),S=R=>(d=R,Q),y=()=>(h="json",Q),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=R=>(p=R,Q),L=()=>{c=de(),n=new i,n.open("get",a);let R=0,G,q=0,J=()=>(cn(c),Math.max(c,Math.max(G||0,q||0)));if(s&&n.addEventListener("progress",A=>{let T=de();s.updateChunk&&A.loaded>R&&(s.updateChunk(J(),A.loaded-R),R=A.loaded,G=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;cn(n);let A=n.status;if(A>=200&&A<300){let{response:T,responseType:V}=n,Y=T==null?void 0:T.byteLength;if(typeof Y=="number"&&s){let U=Y-R;U&&s.updateChunk&&s.updateChunk(J(),U)}V==="json"&&(!T||!(0,nv.default)(T).length)?E():(d&&d(),e(T))}else E()}),n.addEventListener("error",()=>{E()}),p){let A=()=>{cn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=de(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=h,n.send(),Q},Q={withBitrateReporting:v,withParallel:I,withJSONResponse:y,withRetryCount:R=>(l=R,Q),withRetryInterval:(R,G)=>(sv(R)&&(b=R),sv(G)&&(m=G),Q),withTimeout:R=>(o=R,Q),withFinally:S,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return Q}var Wi=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 uv=_(Xr(),1);var Yi=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=de(),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=de()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Zr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=de()}_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=de();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,uv.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}};import{Subject as OR}from"@vkontakte/videoplayer-shared/es2015";var pn=1e4,ml=3;var BR=6e4,NR=10,FR=1,qR=500,Ki=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 OR,this.chunkRateEstimator=new Wi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=hl(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=hl(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*(N.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||{};!Qg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,lv.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||dn(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=()=>{ov(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 Yi(ml,pn,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 E=s&&(!c||c===this.rep);return E||t("Not running!"),E},p=(E,I,L)=>{u&&u.abort(),u=Zr(this.urlResolver.resolve(E,!1),I,L,()=>this._retryCallback()).withTimeout(pn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ml).withFinally(()=>{u=null}).send()},h=(E,I,L)=>{zi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let I=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),r.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let L=de()-1e4,M=0;for(let C=0;C<this.bufferStates.length;C++){let j=this.bufferStates[C];E=Math.min(E,j.buf),j.ts<L&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${E} drop=${M} jitter=${this.sourceJitter}`);let re=E-FR;this.sourceJitter>=0?re-=this.sourceJitter/2:this.sourceJitter-=1,re>3?m(1.15):re>1?m(1.1):re>.3?m(1.05):m(1)}},v=E=>{let I,L=()=>I&&I.start?I.start.length:0,M=A=>I.start[A]/1e3,re=A=>I.dur[A]/1e3,C=A=>I.fragIndex+A,j=(A,T)=>({chunkIdx:C(A),startTS:M(A),dur:re(A),discontinuity:T}),Q=()=>{let A=0;if(I&&I.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,V=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=T;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let U=I.dur.length-1;for(;U>=0&&(Y-=I.dur[U],!(Y<=0));--U);A=Math.min(U,I.dur.length-1-V),A=Math.max(A,0)}return j(A,!0)},R=A=>{let T=L();if(!(T<=0)){if(dn(A)){for(let V=0;V<T;V++)if(M(V)>A)return j(V)}return Q()}},G=A=>{let T=L(),V=A?A.chunkIdx+1:0,Y=V-I.fragIndex;if(!(T<=0)){if(!A||Y<0||Y-T>NR)return t(`Resync: offset=${Y} bChunks=${T} chunk=`+JSON.stringify(A)),Q();if(!(Y>=T))return j(V-I.fragIndex,!1)}},q=(A,T,V)=>{l&&l.abort(),l=Zr(this.urlResolver.resolve(A,!0,this.lowLatency),T,V,()=>this._retryCallback()).withTimeout(pn).withRetryCount(ml).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,T)=>{q(E,V=>{if(!d())return;I=V;let Y=!!I.lowLatency;Y!==this.lowLatency&&b(Y);let U=0;for(let Me=0;Me<I.dur.length;++Me)U+=I.dur[Me];U>0&&(zi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(U/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,A(R(T))},()=>this._handleNetworkError())},nextChunk:G}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),zi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:I,logger:L}=this.params,M=v(e.jidxUrl),re,C,j,Q,R=0,G,q,J,A=()=>{G&&(clearTimeout(G),G=void 0);let z=Math.max(qR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=R+z,Se=de(),ye=Math.min(1e4,he-Se);R=Se;let Et=()=>{l||d()&&M.seek(()=>{d()&&(R=de(),T(),A())})};ye>0?G=window.setTimeout(()=>{this.paused?A():Et()},ye):Et()},T=()=>{let z;for(;z=M.nextChunk(Q);)Q=z,li(z);let he=M.nextChunk(j);if(he){if(j&&he.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?A():(S(),this._initPlayerWith(e));return}Me(he)}else A()},V=(z,he)=>{if(!d()||!this.sourceBuffer)return;let Se,ye,Et,Er=xt=>{window.setTimeout(()=>{d()&&V(z,he)},xt)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Er(100);else{let xt=de(),Yt=I.currentTime;!this.paused&&I.buffered.length>1&&q===Yt&&xt-J>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),q!==Yt&&(q=Yt,J=xt);let xr=this._getBufferSizeSec();if(xr>30)L(`Buffered ${xr} seconds; delaying appendBuffer`),Er(2e3);else try{this.sourceBuffer.appendBuffer(z),this.videoPlayStarted?(this.bufferStates.push({ts:xt,buf:xr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch(ci){if(ci.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(Se=this.sourceBuffer.buffered.start(0),ye=Yt,ye-Se>4&&this.sourceBuffer.remove(Se,ye-3)),Er(1e3);else throw ci}}},Y=()=>{C&&re&&(L([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(j)]),V(C,function(){C=null,T()}))},U=z=>e.fragUrlTemplate.replace("%%id%%",z.chunkIdx),Me=z=>{d()&&h(U(z),(he,Se)=>{if(d()){if(Se/=1e3,C=he,j=z,n=z.startTS,Se){let ye=Math.min(10,z.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ye:ye}Y()}},()=>this._handleNetworkError())},li=z=>{d()&&(zi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(U(z),!1)))},Ir=z=>{d()&&(e.cachedHeader=z,V(z,()=>{re=!0,Y()}))};s=!0,M.seek(z=>{if(d()){if(R=de(),!z){A();return}Q=z,!_R(E)||z.startTS>E?Me(z):(j=z,T())}},E),e.cachedHeader?Ir(e.cachedHeader):p(e.headerUrl,Ir,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),dn(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,zi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return dn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=de();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!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&&pl(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=de();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Zr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(pn).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;Re(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))},BR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var pv=_(Fr(),1);import{debounce as UR,filter as cv,fromEvent as HR,interval as jR,isHigher as QR,isInvariantQuality as GR,isLower as WR,merge as YR,Subject as dv,Subscription as zR}from"@vkontakte/videoplayer-shared/es2015";var fl=class{constructor(){this.onDroopedVideoFramesLimit$=new dv;this.subscription=new zR;this.playing=!1;this.tracks=[];this.forceChecker$=new dv;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&&!GR(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&&QR(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(HR(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=jR(this.droppedFramesChecker.checkTime).pipe(cv(()=>this.playing),cv(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(UR(this.droppedFramesChecker.checkTime)),r=YR(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,pv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>WR(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}},hn=fl;import{map as KR,Observable as XR}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as JR}from"@vkontakte/videoplayer-shared/es2015";var Xi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var ZR=(a,e)=>new XR(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Xi()))},P(P({},r),e));i.observe(a);let s=JR(document,"visibilitychange").pipe(KR(n=>!document.hidden||Xi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),je=ZR;var o$=["paused","playing","ready"],u$=["paused","playing","ready"],Ji=class{constructor(e){this.subscription=new s$;this.videoState=new O("stopped");this.representations$=new gl([]);this.droppedFramesManager=new hn;this.maxSeekBackTime$=new gl(1/0);this.zeroTime$=new gl(void 0);this.liveOffset=new bt;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:fv.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=Ot(u.name))!=null?r:n$(u.video),d=u.bitrate/1e3,p=P({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),bl(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,vl.default)(u$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,vl.default)(o$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(be(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(be(this.params.source.url,u))}return;default:return hv(e)}};this.textTracksManager=new Ue(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:fv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};gv(this.videoState.stateChangeStarted$.pipe(mn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(mn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=we(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(ce(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=Le(this.video);this.subscription.add(this.representations$.pipe(mn(i=>i.map(({track:s})=>s)),bv(i=>!!i.length),a$()).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(r$(),mn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(e$({zeroTime:this.zeroTime$.pipe(bv(bl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(Ae(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(qe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&vv(i),min:s&&vv(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 hv(i.to)}},t)).add(gv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,i$(["init"])).pipe(t$(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),ke(this.video)}createLiveDashPlayer(){let e=new Ki({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&bl(t)?t:Ft(e.map(({track:b})=>b),{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 b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;mv(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;mv(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(be(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Sv=Ji;var Hy=_(Fe(),1);var ut=(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)};import{assertNever as HC,assertNonNullable as jC,debounce as QC,ErrorCategory as Ny,filter as Fy,filterChanged as Fa,fromEvent as GC,isNonNullable as qy,map as ac,merge as Dn,observableFrom as sc,once as Uy,Subscription as WC}from"@vkontakte/videoplayer-shared/es2015";var fn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ei=class extends fn{constructor(){super(),this.listeners||fn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Zi=class{constructor(){Object.defineProperty(this,"signal",{value:new ei,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Zi.prototype[Symbol.toStringTag]="AbortController",ei.prototype[Symbol.toStringTag]="AbortSignal");function bn(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 Sl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!bn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ea=bn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),yv=ea?Sl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ea?yv.fetch:window.fetch,hq=ea?yv.Request:window.Request,ge=ea?Zi:window.AbortController,mq=ea?ei:window.AbortSignal;var ec=_(Tl(),1);var nS=_(sS(),1);import{ErrorCategory as ra}from"@vkontakte/videoplayer-shared/es2015";var oS=a=>{if(!a)return{id:"EmptyResponse",category:ra.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ra.NETWORK,message:`UV Error ${a}`};let e=(0,nS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ra.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:ra.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ra.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(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};import{abortable as Xl,assertNonNullable as gr,combine as vr,ErrorCategory as ct,filter as Oa,filterChanged as Jl,flattenObject as Ba,fromEvent as Sr,getTraceSubscriptionMethod as xC,interval as Zl,isNonNullable as $y,isNullable as My,map as ni,merge as yr,now as PC,Subject as An,Subscription as Cy,tap as wC,throttle as kC,ValueSubject as ne}from"@vkontakte/videoplayer-shared/es2015";var vn=_(Fe(),1),ai=_(Bt(),1),Sn=_(Tl(),1);var W$=(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)},Y$=a=>window.clearTimeout(a),uS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),lS=!uS(window.requestIdleCallback)||!uS(window.cancelIdleCallback),wl=lS?W$:window.requestIdleCallback,ia=lS?Y$:window.cancelIdleCallback;var vy=_(zs(),1);import{assertNever as z$,ErrorCategory as cS,Subject as dS}from"@vkontakte/videoplayer-shared/es2015";var K$=18,pS=!1;try{pS=N.browser.isSafari&&!!N.browser.safariVersion&&N.browser.safariVersion<=K$}catch(a){console.error(a)}var kl=class{constructor(e){this.bufferFull$=new dS;this.error$=new dS;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:cS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return x(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 x(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 x(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};pS&&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:cS.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:z$(t)}}},hS=kl;var Al=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Ht,assertNonNullable as $e,ErrorCategory as yt,fromEvent as Ql,getExponentialDelay as Gl,isNonNullable as ii,isNullable as ve,now as gn,once as pC,Subject as hC,Subscription as mC,ValueSubject as mr}from"@vkontakte/videoplayer-shared/es2015";var H=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 ti=class extends H{};var aa=class extends H{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 H{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 H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var te=class extends H{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var oa=class extends te{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 H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var la=class extends H{constructor(e,t){super(e,t),this.data=this.content}};var pr=class extends te{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 H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends te{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 te{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ma=class extends te{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 H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends te{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 H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends te{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ya=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends te{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 te{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 te{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 H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends te{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 H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var J$={ftyp:sa,moov:na,mvhd:oa,moof:ua,mdat:la,sidx:pr,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:ti},vt=class a{constructor(e={}){this.options=P({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=J$[e];return r?new r(t,new a):new ti(t,new a)}};var Ut=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 eM=new TextDecoder("ascii"),tM=a=>eM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",rM=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})},iM=(a,e)=>{let r=new vt().parse(a),i=new Ut(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)},aM=a=>{let t=new vt().parse(a),r=new Ut(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},sM=a=>{var i;let t=new vt().parse(a);return(i=new Ut(t).find("sidx"))==null?void 0:i.timescale},nM=(a,e)=>{let r=new vt().parse(a),s=new Ut(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},oM=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 Ut(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},mS={validateData:tM,parseInit:oM,getIndexRange:()=>{},parseSegments:rM,parseFeedableSegmentChunk:iM,getChunkEndTime:nM,getServerLatencyTimestamps:aM,getTimescaleFromIndex:sM};var Aa=_(Fe(),1);import{assertNonNullable as Rl,isNonNullable as vS,isNullable as lM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as uM}from"@vkontakte/videoplayer-shared/es2015";var fS={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"}},bS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=ka(a,t),i=r in fS,s=i?fS[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ka(u),d=l*it(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}},ka=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(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},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ka(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:uM(e)}},hr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=bS(r);if(!e(i))return;i.type==="master"&&hr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},gS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=bS(a);return hr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(r=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var SS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],cM=[231,22612,22743,167,171,163,160,175],dM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return hr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=Ze(m,h);l=ka(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ze(m,h):p===17545?i=Ze(m,h):p===21420&&l===475249515?u=Ze(m,h):p===374648427?hr(m,({tag:g,type:v,value:S})=>g===30321?(c=Ze(S,v)===1,!1):!0):s&&n&&(0,Aa.default)(SS,p)&&(o=!0),!o}),Rl(e,"Failed to parse webm Segment start"),Rl(t,"Failed to parse webm Segment end"),Rl(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}}}},pM=a=>{if(lM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hM=(a,e)=>{let t=!1,r=!1,i=o=>vS(o.time)&&vS(o.position),s=[],n;return hr(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=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,Aa.default)(SS,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}}})},mM=a=>{let e=0,t=!1;try{hr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Aa.default)(cM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Aa.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},yS={validateData:gS,parseInit:dM,getIndexRange:pM,parseSegments:hM,parseFeedableSegmentChunk:mM};var La=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return yS;case"mp4":return mS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ul=_(FS(),1),py=_(Fr(),1),hy=_(ry(),1),my=_(Bt(),1),Hl=_(Xr(),1);var iy=_(Fe(),1),_l=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,iy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as dC,isNullable as cy}from"@vkontakte/videoplayer-shared/es2015";var ay=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var sy=a=>{var e;try{let t=lC(),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 lC(){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 Wl=O(Ft(),1);import{videoSizeToQuality as VD}from"@vkontakte/videoplayer-shared/es2015";var Cy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Nt(s):void 0)!=null?u:VD({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},Vy=({id:a,bitrate:e})=>({id:a,bitrate:e}),By=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Oy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Yl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Wl.default)(r.split("."),0),isDefault:i}),zl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Wl.default)(i.split("."),0)}),Kl=a=>"url"in a,ye=a=>a.type==="template",Ca=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Ny=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},St=(a,e)=>{let t=a;t=(0,Xl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Fy.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Xl.default)(t,n,(o,u)=>_y(s)?o:_y(u)?s:(0,qy.default)(s,parseInt(u,10),"0"))}return t},Hy=(a,e)=>{var M,q,U,L,j,_,z,k,y,C,Q,N,Re,hi,Er,G,ce,be,ge,xt,xr,Pt,Kt,Pr,mi,Cc,Vc,Bc,Oc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,rd,id,ad,sd,nd,od,ud,ld,cd,dd,pd,hd,md,fd;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(Qe=>{var X,Xt;return(Xt=(X=Qe.textContent)==null?void 0:X.trim())!=null?Xt:""}),o=(M=(0,Uy.default)(n,0))!=null?M:"",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,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={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:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),T=[...s.getElementsByTagName("Period")],I=T.reduce((Qe,X)=>$(x({},Qe),{[X.id]:X.children}),{}),E=T.reduce((Qe,X)=>$(x({},Qe),{[X.id]:X.getAttribute("duration")}),{});S?v=Ny(S):(0,Jl.default)(E).filter(Qe=>Qe).length&&!u?v=(0,Jl.default)(E).reduce((Qe,X)=>{var Xt;return Qe+((Xt=Ny(X))!=null?Xt:0)},0):b&&(v=parseInt(b,10));let R=0,D=(U=(q=s.getAttribute("profiles"))==null?void 0:q.split(","))!=null?U:[];for(let Qe of T.map(X=>X.id))for(let X of I[Qe]){let Xt=(L=X.getAttribute("id"))!=null?L:"id"+(R++).toString(10),fi=(j=X.getAttribute("mimeType"))!=null?j:"",ao=(_=X.getAttribute("codecs"))!=null?_:"",so=(z=X.getAttribute("contentType"))!=null?z:fi==null?void 0:fi.split("/")[0],uI=(y=(k=X.getAttribute("profiles"))==null?void 0:k.split(","))!=null?y:[],bd=(Q=Dy((C=X.getAttribute("lang"))!=null?C:""))!=null?Q:{},rs=(hi=(Re=(N=X.querySelector("Label"))==null?void 0:N.textContent)==null?void 0:Re.trim())!=null?hi:void 0,lI=X.querySelectorAll("Representation"),cI=X.querySelector("SegmentTemplate"),dI=(G=(Er=X.querySelector("Role"))==null?void 0:Er.getAttribute("value"))!=null?G:void 0,wr=so,re={id:Xt,language:bd.language,isDefault:dI==="main",label:rs,codecs:ao,hdr:wr==="video"&&Ql(ao),mime:fi,representations:[]};for(let K of lI){let wt=(ce=K.getAttribute("lang"))!=null?ce:void 0,bi=(ge=(be=rs!=null?rs:X.getAttribute("label"))!=null?be:K.getAttribute("label"))!=null?ge:void 0,is=(Pt=(xr=(xt=K.querySelector("BaseURL"))==null?void 0:xt.textContent)==null?void 0:xr.trim())!=null?Pt:"",Jt=new URL(is||o,e).toString(),At=(Kt=K.getAttribute("mimeType"))!=null?Kt:fi,as=(mi=(Pr=K.getAttribute("codecs"))!=null?Pr:ao)!=null?mi:"",ss;if(so==="text"){let kt=K.getAttribute("id")||"",ns=((Cc=bd.privateuse)==null?void 0:Cc.includes("x-auto"))||kt.includes("_auto"),Zt=K.querySelector("SegmentTemplate");if(Zt){let gi={representationId:(Vc=K.getAttribute("id"))!=null?Vc:void 0,bandwidth:(Bc=K.getAttribute("bandwidth"))!=null?Bc:void 0},os=parseInt((Oc=K.getAttribute("bandwidth"))!=null?Oc:"",10)/1e3,us=(Nc=parseInt((_c=Zt.getAttribute("startNumber"))!=null?_c:"",10))!=null?Nc:1,Ar=parseInt((Fc=Zt.getAttribute("timescale"))!=null?Fc:"",10),no=(qc=Zt.querySelectorAll("SegmentTimeline S"))!=null?qc:[],kr=Zt.getAttribute("media");if(!kr)continue;let ls=[],cs=0,ds="",Lr=0,vi=us,ve=0;for(let Ge of no){let er=parseInt((Uc=Ge.getAttribute("d"))!=null?Uc:"",10),Ne=parseInt((Hc=Ge.getAttribute("r"))!=null?Hc:"",10)||0,Lt=parseInt((jc=Ge.getAttribute("t"))!=null?jc:"",10);ve=Number.isFinite(Lt)?Lt:ve;let tr=er/Ar*1e3,$t=ve/Ar*1e3;for(let tt=0;tt<Ne+1;tt++){let Rt=St(kr,$(x({},gi),{segmentNumber:vi.toString(10),segmentTime:(ve+tt*er).toString(10)})),$r=($t!=null?$t:0)+tt*tr,yi=$r+tr;vi++,ls.push({time:{from:$r,to:yi},url:Rt})}ve+=(Ne+1)*er,cs+=(Ne+1)*tr}Lr=ve/Ar*1e3,ds=St(kr,$(x({},gi),{segmentNumber:vi.toString(10),segmentTime:ve.toString(10)}));let Si={time:{from:Lr,to:1/0},url:ds},pt={type:"template",baseUrl:Jt,segmentTemplateUrl:kr,initUrl:"",totalSegmentsDurationMs:cs,segments:ls,nextSegmentBeyondManifest:Si,timescale:Ar};ss={id:kt,kind:"text",segmentReference:pt,profiles:[],duration:v,bitrate:os,mime:"",codecs:"",width:0,height:0,isAuto:ns}}else ss={id:kt,isAuto:ns,kind:"text",url:Jt}}else{let kt=(Gc=(Qc=K.getAttribute("contentType"))!=null?Qc:At==null?void 0:At.split("/")[0])!=null?Gc:so,ns=(Yc=(Wc=X.getAttribute("profiles"))==null?void 0:Wc.split(","))!=null?Yc:[],Zt=parseInt((zc=K.getAttribute("width"))!=null?zc:"",10),gi=parseInt((Kc=K.getAttribute("height"))!=null?Kc:"",10),os=parseInt((Xc=K.getAttribute("bandwidth"))!=null?Xc:"",10)/1e3,us=(Jc=K.getAttribute("frameRate"))!=null?Jc:"",Ar=(Zc=K.getAttribute("quality"))!=null?Zc:void 0,no=us?My(us):void 0,kr=(ed=K.getAttribute("id"))!=null?ed:"id"+(R++).toString(10),ls=kt==="video"?`${gi}p`:kt==="audio"?`${os}Kbps`:as,cs=`${kr}@${ls}`,ds=[...D,...uI,...ns],Lr,vi=K.querySelector("SegmentBase"),ve=(td=K.querySelector("SegmentTemplate"))!=null?td:cI;if(vi){let pt=(id=(rd=K.querySelector("SegmentBase Initialization"))==null?void 0:rd.getAttribute("range"))!=null?id:"",[Ge,er]=pt.split("-").map(Rt=>parseInt(Rt,10)),Ne={from:Ge,to:er},Lt=(ad=K.querySelector("SegmentBase"))==null?void 0:ad.getAttribute("indexRange"),[tr,$t]=Lt?Lt.split("-").map(Rt=>parseInt(Rt,10)):[],tt=Lt?{from:tr,to:$t}:void 0;Lr={type:"byteRange",url:Jt,initRange:Ne,indexRange:tt}}else if(ve){let pt={representationId:(sd=K.getAttribute("id"))!=null?sd:void 0,bandwidth:(nd=K.getAttribute("bandwidth"))!=null?nd:void 0},Ge=parseInt((od=ve.getAttribute("timescale"))!=null?od:"",10),er=(ud=ve.getAttribute("initialization"))!=null?ud:"",Ne=ve.getAttribute("media"),Lt=(cd=parseInt((ld=ve.getAttribute("startNumber"))!=null?ld:"",10))!=null?cd:1,tr=St(er,pt);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let $t=(dd=ve.querySelectorAll("SegmentTimeline S"))!=null?dd:[],tt=[],Rt=0,$r="",yi=0;if($t.length){let ps=Lt,We=0;for(let Rr of $t){let rt=parseInt((pd=Rr.getAttribute("d"))!=null?pd:"",10),rr=parseInt((hd=Rr.getAttribute("r"))!=null?hd:"",10)||0,hs=parseInt((md=Rr.getAttribute("t"))!=null?md:"",10);We=Number.isFinite(hs)?hs:We;let oo=rt/Ge*1e3,uo=We/Ge*1e3;for(let ms=0;ms<rr+1;ms++){let hI=St(Ne,$(x({},pt),{segmentNumber:ps.toString(10),segmentTime:(We+ms*rt).toString(10)})),gd=(uo!=null?uo:0)+ms*oo,mI=gd+oo;ps++,tt.push({time:{from:gd,to:mI},url:hI})}We+=(rr+1)*rt,Rt+=(rr+1)*oo}yi=We/Ge*1e3,$r=St(Ne,$(x({},pt),{segmentNumber:ps.toString(10),segmentTime:We.toString(10)}))}else if(BD(v)){let We=parseInt((fd=ve.getAttribute("duration"))!=null?fd:"",10)/Ge*1e3,Rr=Math.ceil(v/We),rt=0;for(let rr=1;rr<Rr;rr++){let hs=St(Ne,$(x({},pt),{segmentNumber:rr.toString(10),segmentTime:rt.toString(10)}));tt.push({time:{from:rt,to:rt+We},url:hs}),rt+=We}yi=rt,$r=St(Ne,$(x({},pt),{segmentNumber:Rr.toString(10),segmentTime:rt.toString(10)}))}let pI={time:{from:yi,to:1/0},url:$r};Lr={type:"template",baseUrl:Jt,segmentTemplateUrl:Ne,initUrl:tr,totalSegmentsDurationMs:Rt,segments:tt,nextSegmentBeyondManifest:pI,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!kt||!At)continue;let Si={video:"video",audio:"audio",text:"text"}[kt];if(!Si)continue;wr||(wr=Si),ss={id:cs,kind:Si,segmentReference:Lr,profiles:ds,duration:v,bitrate:os,mime:At,codecs:as,width:Zt,height:gi,fps:no,quality:Ar}}re.language||(re.language=wt),re.label||(re.label=bi),re.mime||(re.mime=At),re.codecs||(re.codecs=as),re.hdr||(re.hdr=wr==="video"&&Ql(as)),re.representations.push(ss)}if(wr){let K=i[wr].find(wt=>wt.id===re.id);if(K&&re.representations.every(wt=>ye(wt.segmentReference)))for(let wt of K.representations){let bi=re.representations.find(At=>At.id===wt.id),is=bi==null?void 0:bi.segmentReference,Jt=wt.segmentReference;Jt.segments.push(...is.segments),Jt.nextSegmentBeyondManifest=is.nextSegmentBeyondManifest}else i[wr].push(re)}}return{duration:v,streams:i,baseUrls:n,live:g}};var Qy=O(Xe(),1);import{isNonNullable as jy}from"@vkontakte/videoplayer-shared/es2015";var Te=(a,e)=>jy(a)&&jy(e)&&a.readyState==="open"&&(0,Qy.default)([...a.activeSourceBuffers],e);var Va=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new vr(0);this.currentLowLatencySegmentLength$=new vr(0);this.currentSegmentLength$=new vr(0);this.onLastSegment$=new vr(!1);this.fullyBuffered$=new vr(!1);this.playingRepresentation$=new vr(void 0);this.playingRepresentationInit$=new vr(void 0);this.error$=new ND;this.gaps=[];this.subscription=new FD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new me;this.switchAbortController=new me;this.destroyAbortController=new me;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=Qt(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){let t=this.representations.get(e);$e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new qS(this.sourceBuffer),this.subscription.add(ec(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:yt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:yt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(ec(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:yt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Te(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ol(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ut(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);$e(r,"No init buffer for starting representation"),$e(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=Qt(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Te(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();ni(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new bs(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Qt(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Te(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();ni(n)&&(this.isLive||(this.bufferLimit=1/0,yield new bs(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Qt(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){var u,l;let t=(u=(0,An.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!ye(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);$e(i);let s=this.segments.get(r);$e(s,"No segments for starting representation");let n=this.initData.get(r);if($e(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 me,Qt(this.switchAbortController.signal,function(r,i=!1){return ae(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);$e(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(fe(o)||fe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),$e(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Te(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();ni(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(){!fe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return P(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new me,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(fe(e)||fe(this.downloadingRepresentationId)||fe(this.playingRepresentationId)||fe(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||ni(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if($e(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);ni(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=ut(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)&&Ol(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ut(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,wn.default)(o,i))l="high";else{let c=(0,oi.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&ut(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,oi.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;ni(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,An.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,An.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!ye(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>$(x({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,oi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;$e(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(!ye(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=St(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&&oa&&oa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&oa&&oa(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&Te(this.mediaSource,this.sourceBuffer)&&!(Ht(this.sourceBuffer.buffered,p)&&Ht(this.sourceBuffer.buffered,h)))&&g&&S});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 P(this,null,function*(){ye(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return P(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 Qt(o,function(){return ae(this,null,function*(){let c=tc(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=Pn(),!c)return;let d=new DataView(c),p=Da(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ca(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())ye(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return P(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 Qt(n,function(){return ae(this,null,function*(){let u=tc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),ec(window,"online").pipe(_D()).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=Pn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ca(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ye(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,oi.default)(e,0).byte.from,to:(0,oi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>P(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=Pn(),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:yt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ye(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=Pn();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:yt.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,wn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return P(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=Da(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 P(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,m=d<i,b=p<=i;if(!m)continue;let g=Da(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,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 v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(fe(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer))){!this.isLive&&OD.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ht(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ht(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:yt.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",Kl(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=Cl(()=>(0,Gy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return P(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Qt(this.destroyAbortController.signal,function(){return ae(this,null,function*(){let o=tc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Da(e.mime),i)).then(o=>P(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&&ye(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:yt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return P(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 P(this,null,function*(){if(!this.sourceBuffer||!Te(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||fe(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(x({},u.time)),i=n(i);let l=Kl(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,wn.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 P(this,null,function*(){if(!this.sourceBuffer||!Te(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||!Te(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||!Te(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||fe(e)?0:ut(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Te(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||!Te(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=Cl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:yt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(fe(this.sourceBuffer)||!Te(this.mediaSource,this.sourceBuffer)||fe(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:yt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ba=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Wy=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}};import{abortable as Oa,assertNever as zy,fromEvent as Ky,merge as qD,now as _a,Subscription as UD,Subject as Xy,ValueSubject as rc,flattenObject as ui,ErrorCategory as Na}from"@vkontakte/videoplayer-shared/es2015";var Yy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Ln=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new rc(void 0);this.lastConnectionReused$=new rc(void 0);this.lastRequestFirstBytes$=new rc(void 0);this.recoverableError$=new Xy;this.error$=new Xy;this.abortAllController=new me;this.subscription=new UD;this.fetchManifest=Oa(this.abortAllController.signal,function(e){return ae(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ba(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Yy(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(kn);return i?(t.log("success",ui({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ui({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Oa(this.abortAllController.signal,function(l){return ae(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 L,j;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 _=new URL(c,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),c=_.toString();break}default:zy(t)}this.requestQuic&&(c=Ba(c));let h=this.abortAllController.signal,m;if(n){let _=new me;if(m=qD(Ky(this.abortAllController.signal,"abort"),Ky(n,"abort")).subscribe(()=>{try{_.abort()}catch(z){kn(z)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(z){kn(z)}h=_.signal}let b=_a();p.log("startRequest",ui({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:h}),v=_a();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:_}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){m==null||m.unsubscribe();let _=_a(),z={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",ui(z)),p.end(),g.arrayBuffer()}let[S,T]=g.body.tee(),I=S.getReader();o&&((j=this.throughputEstimator)==null||j.trackStream(T,u));let E=0,R=new Uint8Array(0),D=!1,Z=_=>{m==null||m.unsubscribe(),D=!0,kn(_)},M=Oa(h,function(k){return ae(this,arguments,function*({done:_,value:z}){if(E===0&&this.lastRequestFirstBytes$.next(_a()-b),h.aborted){m==null||m.unsubscribe();return}if(!_&&z){let y=new Uint8Array(R.length+z.length);y.set(R),y.set(z,R.length),R=y,E+=z.byteLength,i==null||i(new DataView(R.buffer),E),yield I==null?void 0:I.read().then(M,Z)}})}.bind(this));yield I==null?void 0:I.read().then(M,Z),m==null||m.unsubscribe();let q=_a(),U={failed:D,requestStartedAt:b,requestEndedAt:q,duration:q-b};return D?(p.error("endRequest",ui(U)),p.end(),null):(p.log("endRequest",ui(U)),p.end(),R.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Oa(this.abortAllController.signal,function(e,t,r){return ae(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Oa(this.abortAllController.signal,function(e,t){return ae(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=>$(x({},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}=Wy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return P(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:zy(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return P(this,null,function*(){let r=yield lt(e,t),i=yield r.text(),s=parseInt(i);if(r.ok||isNaN(s))return r;switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Na.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Na.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Na.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Na.FATAL});break;default:console.log(JSON.stringify(r)),console.log(s),this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Na.FATAL})}})}},kn=a=>{if(!Ca(a))throw a};var Sr=(a,e,t)=>t*e+(1-t)*a,ic=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Jy=(a,e,t,r)=>{let i=0,s=t,n=ic(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};import{isNullable as HD,ValueSubject as Zy}from"@vkontakte/videoplayer-shared/es2015";var Gt=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 Zy(e.initial),this.debounced$=new Zy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Se(`raw_${t}`),this.smoothedSeries$=new Se(`smoothed_${t}`),this.reportedSeries$=new Se(`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+=it(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)&&(HD(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 $n=class extends Gt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Sr(this.slow,e,this.params.emaAlphaSlow),this.fast=Sr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Rn=class extends Gt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ic(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Sr(this.emaSmoothed,e,this.params.emaAlpha);let r=Jy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Mn=class extends Gt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Sr(this.smoothed,t,this.params.emaAlpha):t}};var yr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new $n({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Rn({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 Mn(x({initial:e,label:"liveEdgeDelay"},t))}};var ac=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as jD,ValueSubject as QD}from"@vkontakte/videoplayer-shared/es2015";var Fa=class a{constructor(e,t){this.currentRepresentation$=new QD(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(!jD(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($(x({},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&&ye(t.segmentReference))}};var ZD=["timeupdate","progress","play","seeked","stalled","waiting"],eC=["timeupdate","progress","loadeddata","playing","seeked"];var Bn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new iT;this.representationSubscription=new iT;this.state$=new V("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Vn;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new Vn;this.fetcherError$=new Vn;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Vn;this.gapWatchdogActive=!1;this.destroyController=new me;this.initManifest=nc(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=he(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:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=nc(this.destroyController.signal,function(){return ae(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:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Hy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=VS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=gt())==null?void 0:h.isTypeSupported)!=null&&m.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:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=hS(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);zD.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=$(x({},t),{streams:i});return this.tracer.log("updateManifestEnd",qa(s)),s})}.bind(this));this.initRepresentations=nc(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",qa({initialVideo:e,initialAudio:t,sourceHls:r})),li(this.manifest),li(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Tt(p,"error").pipe(Dn(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Kv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&mn())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 Va("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],tT(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Va("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Fa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Fa(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(Tr(...eC.map(p=>Tt(this.element,p))).pipe(Ua(p=>this.element?ut(this.element.buffered,this.element.currentTime*1e3):0),Cn(),XD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Tr(Tt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Cn()).subscribe(h=>this.liveStreamEndTimestamp=uc())),this.subscription.add(Tt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=oc(1e3).subscribe(h=>{let m=Zs(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()})})).add(Tt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(ci({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ua(({isActiveLive:h,isLowLatency:m})=>h&&m),Cn()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||ac(this.element,1)})),this.representationSubscription.add(ci({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Dn(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!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 m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(ci({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Dn(({isLive:h})=>h),Cn((h,m)=>m.bufferLength<h.bufferLength),Ua(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let g=Zs(this.manifestUrlString,2);return(h/2+m+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ci({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-g;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(T)>v&&(I=1+Math.sign(T)*S),ac(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let m=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;m=Math.min(...this.bufferManagers.map(T=>{var I,E;return(E=(I=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(ci({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(JD(1e3)).subscribe(b=>P(this,[b],function*({liveLoadBufferLength:h,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=Zs(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,R=isFinite(h)?h:m,D=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),Z=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(Z);let M="none";if(D?M="active_low_latency":this.isLowLatency$.getValue()&&Z?(this.bufferManagers.forEach(q=>q.proceedLowLatencyLive()),M="active_low_latency"):v!==0&&R<T?M="live_forward_buffering":R<T+E&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let q=p-(T+I),U=this.normolizeLiveOffset(Math.trunc(v+q/g)),L=Math.abs(U-v),j=0;!h||L<=this.tuning.dashCmafLive.offsetCalculationError?j=v:U>0&&L>this.tuning.dashCmafLive.offsetCalculationError&&(j=U),this.manifestUrlString=he(this.manifestUrlString,j,2)}(M==="live_with_target_offset"||M==="live_forward_buffering")&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Tr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ua(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Tr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ua(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(Tr(this.forceEnded$,ci({allBuffersFull:l,someBufferEnded:c}).pipe(Dn(({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:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Tr(...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,lc.default)((0,lc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),ye(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&tT(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=oc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:ct.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 Ln({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=yr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return P(this,null,function*(){var i,s,n;li(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?uc()-this.liveStreamEndTimestamp:0,r=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(r===0),this.manifestUrlString=he(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(){li(this.element),this.state$.setState("running"),this.subscription.add(Tr(...ZD.map(e=>Tt(this.element,e)),Tt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Tt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Tt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ht(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,S,T,I,E,R;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=uc(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(I=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?I: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 D=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(D).catch(Z=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:Z})}),i.liveLastOffset=D}else{let D=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(D),(R=this.audioBufferManager)==null||R.maintain(D),i.position=D}this.tracer.log("stallIntervalCallback",qa(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=oc(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return P(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 P(this,null,function*(){var i,s,n,o,u;li(this.element),li(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),Ht(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(rT(this.element)||rT(this.videoBufferManager))&&(this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",qa({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=KD(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 P(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=$(x({},r),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",qa(r)))}}};var On=class{constructor(e,t){this.fov=e,this.orientation=t}};var _n=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/it(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=x({},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*it(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 aT=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Bl=_(Bt(),1);import{videoSizeToQuality as cC}from"@vkontakte/videoplayer-shared/es2015";var ny=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ot(s):void 0)!=null?u:cC({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},oy=({id:a,bitrate:e})=>({id:a,bitrate:e}),uy=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ly=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Nl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Bl.default)(r.split("."),0),isDefault:i}),Fl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Bl.default)(i.split("."),0)}),ql=a=>"url"in a,Ee=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var dy=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},St=(a,e)=>{let t=a;t=(0,Ul.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,py.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ul.default)(t,n,(o,u)=>cy(s)?o:cy(u)?s:(0,hy.default)(s,parseInt(u,10),"0"))}return t},fy=(a,e)=>{var I,L,M,re,C,j,Q,R,G,q,J,A,T,V,Y,U,Me,li,Ir,z,he,Se,ye,Et,Er,xt,Yt,xr,ci,Ic,Ec,xc,Pc,wc,kc,Ac,Lc,Rc,$c,Mc,Cc,Dc,Vc,_c,Oc,Bc,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc;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(Qe=>{var ee,zt;return(zt=(ee=Qe.textContent)==null?void 0:ee.trim())!=null?zt:""}),o=(I=(0,my.default)(n,0))!=null?I:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],m=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((Qe,ee)=>$(P({},Qe),{[ee.id]:ee.children}),{}),v=b.reduce((Qe,ee)=>$(P({},Qe),{[ee.id]:ee.getAttribute("duration")}),{});p?d=dy(p):(0,Hl.default)(v).filter(Qe=>Qe).length&&!u?d=(0,Hl.default)(v).reduce((Qe,ee)=>{var zt;return Qe+((zt=dy(ee))!=null?zt:0)},0):m&&(d=parseInt(m,10));let S=0,y=(M=(L=s.getAttribute("profiles"))==null?void 0:L.split(","))!=null?M:[];for(let Qe of b.map(ee=>ee.id))for(let ee of g[Qe]){let zt=(re=ee.getAttribute("id"))!=null?re:"id"+(S++).toString(10),di=(C=ee.getAttribute("mimeType"))!=null?C:"",Kn=(j=ee.getAttribute("codecs"))!=null?j:"",Xn=(Q=ee.getAttribute("contentType"))!=null?Q:di==null?void 0:di.split("/")[0],NT=(G=(R=ee.getAttribute("profiles"))==null?void 0:R.split(","))!=null?G:[],ed=(J=sy((q=ee.getAttribute("lang"))!=null?q:""))!=null?J:{},Za=(V=(T=(A=ee.querySelector("Label"))==null?void 0:A.textContent)==null?void 0:T.trim())!=null?V:void 0,FT=ee.querySelectorAll("Representation"),qT=ee.querySelector("SegmentTemplate"),UT=(U=(Y=ee.querySelector("Role"))==null?void 0:Y.getAttribute("value"))!=null?U:void 0,Pr=Xn,ae={id:zt,language:ed.language,isDefault:UT==="main",label:Za,codecs:Kn,hdr:Pr==="video"&&_l(Kn),mime:di,representations:[]};for(let Z of FT){let Pt=(Me=Z.getAttribute("lang"))!=null?Me:void 0,pi=(Ir=(li=Za!=null?Za:ee.getAttribute("label"))!=null?li:Z.getAttribute("label"))!=null?Ir:void 0,es=(Se=(he=(z=Z.querySelector("BaseURL"))==null?void 0:z.textContent)==null?void 0:he.trim())!=null?Se:"",Kt=new URL(es||o,e).toString(),wt=(ye=Z.getAttribute("mimeType"))!=null?ye:di,ts=(Er=(Et=Z.getAttribute("codecs"))!=null?Et:Kn)!=null?Er:"",rs;if(Xn==="text"){let kt=Z.getAttribute("id")||"",is=((xt=ed.privateuse)==null?void 0:xt.includes("x-auto"))||kt.includes("_auto"),Xt=Z.querySelector("SegmentTemplate");if(Xt){let hi={representationId:(Yt=Z.getAttribute("id"))!=null?Yt:void 0,bandwidth:(xr=Z.getAttribute("bandwidth"))!=null?xr:void 0},as=parseInt((ci=Z.getAttribute("bandwidth"))!=null?ci:"",10)/1e3,ss=(Ec=parseInt((Ic=Xt.getAttribute("startNumber"))!=null?Ic:"",10))!=null?Ec:1,wr=parseInt((xc=Xt.getAttribute("timescale"))!=null?xc:"",10),Jn=(Pc=Xt.querySelectorAll("SegmentTimeline S"))!=null?Pc:[],kr=Xt.getAttribute("media");if(!kr)continue;let ns=[],os=0,us="",Ar=0,mi=ss,Te=0;for(let Ge of Jn){let Jt=parseInt((wc=Ge.getAttribute("d"))!=null?wc:"",10),Ne=parseInt((kc=Ge.getAttribute("r"))!=null?kc:"",10)||0,At=parseInt((Ac=Ge.getAttribute("t"))!=null?Ac:"",10);Te=Number.isFinite(At)?At:Te;let Zt=Jt/wr*1e3,Lt=Te/wr*1e3;for(let tt=0;tt<Ne+1;tt++){let Rt=St(kr,$(P({},hi),{segmentNumber:mi.toString(10),segmentTime:(Te+tt*Jt).toString(10)})),Lr=(Lt!=null?Lt:0)+tt*Zt,bi=Lr+Zt;mi++,ns.push({time:{from:Lr,to:bi},url:Rt})}Te+=(Ne+1)*Jt,os+=(Ne+1)*Zt}Ar=Te/wr*1e3,us=St(kr,$(P({},hi),{segmentNumber:mi.toString(10),segmentTime:Te.toString(10)}));let fi={time:{from:Ar,to:1/0},url:us},dt={type:"template",baseUrl:Kt,segmentTemplateUrl:kr,initUrl:"",totalSegmentsDurationMs:os,segments:ns,nextSegmentBeyondManifest:fi,timescale:wr};rs={id:kt,kind:"text",segmentReference:dt,profiles:[],duration:d,bitrate:as,mime:"",codecs:"",width:0,height:0,isAuto:is}}else rs={id:kt,isAuto:is,kind:"text",url:Kt}}else{let kt=(Rc=(Lc=Z.getAttribute("contentType"))!=null?Lc:wt==null?void 0:wt.split("/")[0])!=null?Rc:Xn,is=(Mc=($c=ee.getAttribute("profiles"))==null?void 0:$c.split(","))!=null?Mc:[],Xt=parseInt((Cc=Z.getAttribute("width"))!=null?Cc:"",10),hi=parseInt((Dc=Z.getAttribute("height"))!=null?Dc:"",10),as=parseInt((Vc=Z.getAttribute("bandwidth"))!=null?Vc:"",10)/1e3,ss=(_c=Z.getAttribute("frameRate"))!=null?_c:"",wr=(Oc=Z.getAttribute("quality"))!=null?Oc:void 0,Jn=ss?ay(ss):void 0,kr=(Bc=Z.getAttribute("id"))!=null?Bc:"id"+(S++).toString(10),ns=kt==="video"?`${hi}p`:kt==="audio"?`${as}Kbps`:ts,os=`${kr}@${ns}`,us=[...y,...NT,...is],Ar,mi=Z.querySelector("SegmentBase"),Te=(Nc=Z.querySelector("SegmentTemplate"))!=null?Nc:qT;if(mi){let dt=(qc=(Fc=Z.querySelector("SegmentBase Initialization"))==null?void 0:Fc.getAttribute("range"))!=null?qc:"",[Ge,Jt]=dt.split("-").map(Rt=>parseInt(Rt,10)),Ne={from:Ge,to:Jt},At=(Uc=Z.querySelector("SegmentBase"))==null?void 0:Uc.getAttribute("indexRange"),[Zt,Lt]=At?At.split("-").map(Rt=>parseInt(Rt,10)):[],tt=At?{from:Zt,to:Lt}:void 0;Ar={type:"byteRange",url:Kt,initRange:Ne,indexRange:tt}}else if(Te){let dt={representationId:(Hc=Z.getAttribute("id"))!=null?Hc:void 0,bandwidth:(jc=Z.getAttribute("bandwidth"))!=null?jc:void 0},Ge=parseInt((Qc=Te.getAttribute("timescale"))!=null?Qc:"",10),Jt=(Gc=Te.getAttribute("initialization"))!=null?Gc:"",Ne=Te.getAttribute("media"),At=(Yc=parseInt((Wc=Te.getAttribute("startNumber"))!=null?Wc:"",10))!=null?Yc:1,Zt=St(Jt,dt);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Lt=(zc=Te.querySelectorAll("SegmentTimeline S"))!=null?zc:[],tt=[],Rt=0,Lr="",bi=0;if(Lt.length){let ls=At,We=0;for(let Rr of Lt){let rt=parseInt((Kc=Rr.getAttribute("d"))!=null?Kc:"",10),er=parseInt((Xc=Rr.getAttribute("r"))!=null?Xc:"",10)||0,cs=parseInt((Jc=Rr.getAttribute("t"))!=null?Jc:"",10);We=Number.isFinite(cs)?cs:We;let Zn=rt/Ge*1e3,eo=We/Ge*1e3;for(let ds=0;ds<er+1;ds++){let jT=St(Ne,$(P({},dt),{segmentNumber:ls.toString(10),segmentTime:(We+ds*rt).toString(10)})),td=(eo!=null?eo:0)+ds*Zn,QT=td+Zn;ls++,tt.push({time:{from:td,to:QT},url:jT})}We+=(er+1)*rt,Rt+=(er+1)*Zn}bi=We/Ge*1e3,Lr=St(Ne,$(P({},dt),{segmentNumber:ls.toString(10),segmentTime:We.toString(10)}))}else if(dC(d)){let We=parseInt((Zc=Te.getAttribute("duration"))!=null?Zc:"",10)/Ge*1e3,Rr=Math.ceil(d/We),rt=0;for(let er=1;er<Rr;er++){let cs=St(Ne,$(P({},dt),{segmentNumber:er.toString(10),segmentTime:rt.toString(10)}));tt.push({time:{from:rt,to:rt+We},url:cs}),rt+=We}bi=rt,Lr=St(Ne,$(P({},dt),{segmentNumber:Rr.toString(10),segmentTime:rt.toString(10)}))}let HT={time:{from:bi,to:1/0},url:Lr};Ar={type:"template",baseUrl:Kt,segmentTemplateUrl:Ne,initUrl:Zt,totalSegmentsDurationMs:Rt,segments:tt,nextSegmentBeyondManifest:HT,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!kt||!wt)continue;let fi={video:"video",audio:"audio",text:"text"}[kt];if(!fi)continue;Pr||(Pr=fi),rs={id:os,kind:fi,segmentReference:Ar,profiles:us,duration:d,bitrate:as,mime:wt,codecs:ts,width:Xt,height:hi,fps:Jn,quality:wr}}ae.language||(ae.language=Pt),ae.label||(ae.label=pi),ae.mime||(ae.mime=wt),ae.codecs||(ae.codecs=ts),ae.hdr||(ae.hdr=Pr==="video"&&_l(ts)),ae.representations.push(rs)}if(Pr){let Z=i[Pr].find(Pt=>Pt.id===ae.id);if(Z&&ae.representations.every(Pt=>Ee(Pt.segmentReference)))for(let Pt of Z.representations){let pi=ae.representations.find(wt=>wt.id===Pt.id),es=pi==null?void 0:pi.segmentReference,Kt=Pt.segmentReference;Kt.segments.push(...es.segments),Kt.nextSegmentBeyondManifest=es.nextSegmentBeyondManifest}else i[Pr].push(ae)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var gy=_(Fe(),1);import{isNonNullable as by}from"@vkontakte/videoplayer-shared/es2015";var xe=(a,e)=>by(a)&&by(e)&&a.readyState==="open"&&(0,gy.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 mr(0);this.currentLowLatencySegmentLength$=new mr(0);this.currentSegmentLength$=new mr(0);this.onLastSegment$=new mr(!1);this.fullyBuffered$=new mr(!1);this.playingRepresentation$=new mr(void 0);this.playingRepresentationInit$=new mr(void 0);this.error$=new hC;this.gaps=[];this.subscription=new mC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ge;this.switchAbortController=new ge;this.destroyAbortController=new ge;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=Ht(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);$e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new hS(this.sourceBuffer),this.subscription.add(Ql(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:yt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:yt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Ql(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:yt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!xe(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Al(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ut(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);$e(r,"No init buffer for starting representation"),$e(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=Ht(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!xe(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();ii(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=Ht(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(ve(s)||ve(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!xe(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();ii(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=Ht(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var u,l;let t=(u=(0,Sn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Ee(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);$e(i);let s=this.segments.get(r);$e(s,"No segments for starting representation");let n=this.initData.get(r);if($e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ge,Ht(this.switchAbortController.signal,function(r,i=!1){return oe(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);$e(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(ve(o)||ve(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),$e(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!xe(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();ii(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(){!ve(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return x(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ge,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!xe(this.mediaSource,this.sourceBuffer)||ii(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if($e(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);ii(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=ut(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)&&Al(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ut(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,vn.default)(o,i))l="high";else{let c=(0,ai.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&&ut(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ai.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;ii(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,Sn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,Sn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ee(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>$(P({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ai.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;$e(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(!Ee(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=St(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:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&xe(this.mediaSource,this.sourceBuffer)&&!(qt(this.sourceBuffer.buffered,p)&&qt(this.sourceBuffer.buffered,h)))&&g&&S});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 x(this,null,function*(){Ee(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return x(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 Ht(o,function(){return oe(this,null,function*(){let c=Gl(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=gn(),!c)return;let d=new DataView(c),p=La(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),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())Ee(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return x(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 Ht(n,function(){return oe(this,null,function*(){let u=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ql(window,"online").pipe(pC()).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=gn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Ee(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ai.default)(e,0).byte.from,to:(0,ai.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>x(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=gn(),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:yt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!Ee(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=gn();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:yt.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,vn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return x(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=La(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 x(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,m=d<i,b=p<=i;if(!m)continue;let g=La(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,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 v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(ve(this.sourceBuffer)||!xe(this.mediaSource,this.sourceBuffer))){!this.isLive&&N.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:yt.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",ql(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=wl(()=>(0,vy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return x(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ht(this.destroyAbortController.signal,function(){return oe(this,null,function*(){let o=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,La(e.mime),i)).then(o=>x(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&&Ee(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:yt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return x(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 x(this,null,function*(){if(!this.sourceBuffer||!xe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ve(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(P({},u.time)),i=n(i);let l=ql(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,vn.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 x(this,null,function*(){if(!this.sourceBuffer||!xe(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||!xe(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||!xe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ve(e)?0:ut(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!xe(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||!xe(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=wl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:yt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ve(this.sourceBuffer)||!xe(this.mediaSource,this.sourceBuffer)||ve(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:yt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ma=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Sy=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}};import{abortable as Ca,assertNever as Ty,fromEvent as Iy,merge as fC,now as Da,Subscription as bC,Subject as Ey,ValueSubject as Wl,flattenObject as si,ErrorCategory as Va}from"@vkontakte/videoplayer-shared/es2015";var yy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Tn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Wl(void 0);this.lastConnectionReused$=new Wl(void 0);this.lastRequestFirstBytes$=new Wl(void 0);this.recoverableError$=new Ey;this.error$=new Ey;this.abortAllController=new ge;this.subscription=new bC;this.fetchManifest=Ca(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ma(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=yy(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(yn);return i?(t.log("success",si({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",si({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Ca(this.abortAllController.signal,function(l){return oe(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 R,G;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 q=new URL(c,location.href);q.searchParams.append("bytes",`${r.from}-${r.to}`),c=q.toString();break}default:Ty(t)}this.requestQuic&&(c=Ma(c));let h=this.abortAllController.signal,m;if(n){let q=new ge;if(m=fC(Iy(this.abortAllController.signal,"abort"),Iy(n,"abort")).subscribe(()=>{try{q.abort()}catch(J){yn(J)}}),this.abortAllController.signal.aborted||n.aborted)try{q.abort()}catch(J){yn(J)}h=q.signal}let b=Da();p.log("startRequest",si({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:h}),v=Da();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let q=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:q}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){m==null||m.unsubscribe();let q=Da(),J={requestStartedAt:b,requestEndedAt:q,duration:q-b};return p.log("endRequest",si(J)),p.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),E=S.getReader();o&&((G=this.throughputEstimator)==null||G.trackStream(y,u));let I=0,L=new Uint8Array(0),M=!1,re=q=>{m==null||m.unsubscribe(),M=!0,yn(q)},C=Ca(h,function(A){return oe(this,arguments,function*({done:q,value:J}){if(I===0&&this.lastRequestFirstBytes$.next(Da()-b),h.aborted){m==null||m.unsubscribe();return}if(!q&&J){let T=new Uint8Array(L.length+J.length);T.set(L),T.set(J,L.length),L=T,I+=J.byteLength,i==null||i(new DataView(L.buffer),I),yield E==null?void 0:E.read().then(C,re)}})}.bind(this));yield E==null?void 0:E.read().then(C,re),m==null||m.unsubscribe();let j=Da(),Q={failed:M,requestStartedAt:b,requestEndedAt:j,duration:j-b};return M?(p.error("endRequest",si(Q)),p.end(),null):(p.log("endRequest",si(Q)),p.end(),L.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Ca(this.abortAllController.signal,function(e,t,r){return oe(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ca(this.abortAllController.signal,function(e,t){return oe(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=>$(P({},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}=Sy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return x(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:Ty(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return x(this,null,function*(){let r=yield lt(e,t);if(r.ok)return r;let i=yield r.text(),s=parseInt(i);switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Va.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Va.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Va.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Va.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Va.FATAL})}})}},yn=a=>{if(!Ra(a))throw a};var fr=(a,e,t)=>t*e+(1-t)*a,Yl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,xy=(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};import{isNullable as gC,ValueSubject as Py}from"@vkontakte/videoplayer-shared/es2015";var jt=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 Py(e.initial),this.debounced$=new Py(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`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+=it(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)&&(gC(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 In=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=fr(this.slow,e,this.params.emaAlphaSlow),this.fast=fr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var En=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Yl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=fr(this.emaSmoothed,e,this.params.emaAlpha);let r=xy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var xn=class extends jt{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?fr(this.smoothed,t,this.params.emaAlpha):t}};var br=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new In({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new En({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 xn(P({initial:e,label:"liveEdgeDelay"},t))}};var zl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as vC,ValueSubject as SC}from"@vkontakte/videoplayer-shared/es2015";var _a=class a{constructor(e,t){this.currentRepresentation$=new SC(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(!vC(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($(P({},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&&Ee(t.segmentReference))}};var wn=_(Bt(),1);import{assertNever as kn}from"@vkontakte/videoplayer-shared/es2015";var wy=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let{containers:i,protocols:s,codecs:n,nativeHlsSupported:o}=N.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 kn(c)}})},Pn=a=>{let{webmDecodingInfo:e}=N.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:kn(a)}return[t,r]},ky=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Pn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(N.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",...Pn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Pn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Pn(a),...i,"HLS","HLS_ONDEMAND"];default:kn(e)}return N.video.nativeHlsSupported?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Ay=({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=N.device.isMac&&N.browser.isSafari;if(N.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:kn(a)}else N.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"]},Kl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ly=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,wn.default)(t.value.split("."),0)}for(let t of a){let r=(0,wn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,wn.default)(e.value.split("."),0)};var AC=["timeupdate","progress","play","seeked","stalled","waiting"],LC=["timeupdate","progress","loadeddata","playing","seeked"];var Ln=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Cy;this.representationSubscription=new Cy;this.state$=new O("none");this.currentVideoRepresentation$=new ne(void 0);this.currentVideoRepresentationInit$=new ne(void 0);this.currentAudioRepresentation$=new ne(void 0);this.currentVideoSegmentLength$=new ne(0);this.currentAudioSegmentLength$=new ne(0);this.error$=new An;this.lastConnectionType$=new ne(void 0);this.lastConnectionReused$=new ne(void 0);this.lastRequestFirstBytes$=new ne(void 0);this.currentLiveTextRepresentation$=new ne(null);this.isLive$=new ne(!1);this.isActiveLive$=new ne(!1);this.isLowLatency$=new ne(!1);this.liveDuration$=new ne(0);this.liveAvailabilityStartTime$=new ne(void 0);this.bufferLength$=new ne(0);this.liveLatency$=new ne(void 0);this.liveLoadBufferLength$=new ne(0);this.livePositionFromPlayer$=new ne(0);this.currentStallDuration$=new ne(0);this.videoLastDataObtainedTimestamp$=new ne(0);this.fetcherRecoverableError$=new An;this.fetcherError$=new An;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new An;this.gapWatchdogActive=!1;this.destroyController=new ge;this.initManifest=Xl(this.destroyController.signal,function(e,t,r){return oe(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=be(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:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Xl(this.destroyController.signal,function(){return oe(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:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=fy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=Je())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=Ly(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);N.display.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=$(P({},t),{streams:i});return this.tracer.log("updateManifestEnd",Ba(s)),s})}.bind(this));this.initRepresentations=Xl(this.destroyController.signal,function(e,t,r){return oe(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",Ba({initialVideo:e,initialAudio:t,sourceHls:r})),gr(this.manifest),gr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Sr(p,"error").pipe(Oa(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Pg():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&rn())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],$y(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new $a("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}_a.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new _a(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Zl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Ks(this.manifestUrlString,2);this.manifestUrlString=be(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(yr(...LC.map(p=>Sr(this.element,p))).pipe(ni(p=>this.element?ut(this.element.buffered,this.element.currentTime*1e3):0),Jl(),wC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(yr(Sr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(vr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ni(({isActiveLive:h,isLowLatency:m})=>h&&m),Jl()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||zl(this.element,1)})),this.representationSubscription.add(vr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Oa(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(vr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$,currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Oa(({isActiveLive:h,isLowLatency:m,currentLowLatencySegmentLength:b})=>h&&m&&!!b)).subscribe(({currentLowLatencySegmentLength:h})=>{let m=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(vr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Oa(({isLive:h})=>h),ni(h=>P({},h)),Jl((h,m)=>m.bufferLength<h.bufferLength),ni(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let g=Ks(this.manifestUrlString,2);return(h/2+m+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(vr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=h-g;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(y)>v&&(E=1+Math.sign(y)*S),zl(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let m=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var E,I;return(I=(E=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?I:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(vr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(kC(1e3)).subscribe(b=>x(this,[b],function*({liveLoadBufferLength:h,bufferLength:m}){if(gr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Ks(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,L=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),re=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLive$.next(re);let C="none";if(M?C="active_low_latency":this.isLowLatency$.getValue()&&re?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),C="active_low_latency"):v!==0&&L<y?C="live_forward_buffering":L<y+I&&(C="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),C==="live_forward_buffering"||C==="live_with_target_offset"){let j=p-(y+E),Q=this.normolizeLiveOffset(Math.trunc(v+j/g)),R=Math.abs(Q-v),G;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?G=v:Q>0&&R>this.tuning.dashCmafLive.offsetCalculationError?G=Q:G=0,this.manifestUrlString=be(this.manifestUrlString,G,2)}C!=="none"&&C!=="active_low_latency"&&(p=0,yield this.updateLive())}),h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=yr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ni(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=yr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ni(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(yr(this.forceEnded$,vr({allBuffersFull:l,someBufferEnded:c}).pipe(Oa(({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:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(yr(...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,ec.default)((0,ec.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ee(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&$y(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=Zl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:ct.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 Tn({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=br.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,P({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return x(this,null,function*(){var r,i,s;gr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLive$.next(t===0),this.liveLastSeekOffset=t,this.manifestUrlString=be(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){gr(this.element),this.state$.setState("running"),this.subscription.add(yr(...AC.map(e=>Sr(this.element,e)),Sr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Sr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Sr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,S,y,E,I,L;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=PC(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(E=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?E:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset).catch(M=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:M})}),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let M=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(M),(L=this.audioBufferManager)==null||L.maintain(M),i.position=M}this.tracer.log("stallIntervalCallback",Ba(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Zl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return x(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 x(this,null,function*(){var i,s,n,o,u;gr(this.element),gr(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),qt(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(My(this.element)||My(this.videoBufferManager))&&(this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Ba({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=xC(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 x(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=$(P({},r),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Ba(r)))}}};var Rn=class{constructor(e,t){this.fov=e,this.orientation=t}};var $n=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/it(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=P({},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*it(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 Dy=`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 Vy=`#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 Nn=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 On(this.params.fov,this.params.orientation),this.cameraRotationManager=new _n(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(aT,this.gl.VERTEX_SHADER),r=this.createShader(sT,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}};import{isNullable as iC,now as nT,Subscription as aC,filter as sC,combine as oT,ValueSubject as cc,isNonNullable as nC}from"@vkontakte/videoplayer-shared/es2015";var dc=class{constructor(){this.isSeeked$=new cc(!1);this.isBuffering$=new cc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new aC;this.severeStallOccurred$=new cc(!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(oT({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(sC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(oT({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(iC(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=nT(),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,nC(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=nT(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},uT=dc;import{combine as oC,map as uC,observeElementSize as lC,Subscription as cC,ValueSubject as pc,noop as dC}from"@vkontakte/videoplayer-shared/es2015";var Fn=class{constructor(){this.subscription=new cC;this.pipSize$=new pc(void 0);this.videoSize$=new pc(void 0);this.elementSize$=new pc(void 0);this.pictureInPictureWindowRemoveEventListener=dC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(lC(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(oC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(uC(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ir=class{constructor(e){this.subscription=new gC;this.videoState=new V("stopped");this.droppedFramesManager=new cn;this.stallsManager=new uT;this.elementSizeManager=new Fn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new 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"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return hC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Nn(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 qe(e.source.url),this.params=e,this.video=Ee(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(oe(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 Bn({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=we(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:lT.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(cT(l=>!!l.length),pT()).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(hc(l=>l.to.state!=="none"),Ha());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ha()),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(cT(dT),pT()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(hc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Fe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(mC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Yl(h));let m=[];for(let b of h.representations){let g=Vy(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(zl(p));let h=[];for(let m of p.representations){let b=Cy($(x({},m),{streamId:p.id}));b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=By(p,h);this.textTracksMap.set(m,{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(qn(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$,bC(this.video,"progress")).subscribe(()=>P(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,hT.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,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===p.id});dT(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.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 g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,g)}}),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(Ha()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.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(zl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ha()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.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(Yl(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(hc(({to:l})=>l==="ready"),Ha());this.subscription.add(qn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,mc(["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(qn(o,this.player.state$.stateChangeEnded$,mc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=qn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,mc(["init"])).pipe(fC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var D,Z,M,q,U,L,j,_,z,k,y,C,Q;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(D=e.videoTrack.getState())==null?void 0:D.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===i),o=t.currentVideoTrack$.getValue(),u=((q=(M=e.videoStream.getState())!=null?M:n&&((Z=this.videoTracksMap.get(n))==null?void 0:Z.stream))!=null?q:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ut(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,m=Math.min(d/Math.min(p,h||1/0),1),b=(U=e.audioStream.getState())!=null?U:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(L=[...this.audioStreamsMap.keys()].find(({id:N})=>N===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let N=nn(n,c,(j=this.audioStreamsMap.get(g))!=null?j:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(_=N==null?void 0:N.bitrate)!=null?_:-1/0)}if(o){let N=nn(o,c,(z=this.audioStreamsMap.get(g))!=null?z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=N==null?void 0:N.bitrate)!=null?k:-1/0)}}let S=Ut(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),T=r?S!=null?S:n:n!=null?n:S,I=g&&dv(T,c,(y=this.audioStreamsMap.get(g))!=null?y:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(C=this.videoTracksMap.get(T))==null?void 0:C.representation,R=I&&((Q=this.audioTracksMap.get(I))==null?void 0:Q.representation);if(E&&R)return[E,R];if(E&&!R&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lT.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),xe(this.video),this.tracer.end()}};var ja=class extends Ir{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Un,merge as mT,filter as vC,filterChanged as SC,isNullable as fc,map as fT,ValueSubject as bc}from"@vkontakte/videoplayer-shared/es2015";var Qa=class extends Ir{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 bc(1);s(r.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe(fT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Un({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(fT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(Un({position:t.position$,liveStreamStatus:this.player.liveStreamStatus$}).subscribe(({position:o,liveStreamStatus:u})=>t.isLiveEnded$.next(u!=="active"&&o===0))).add(Un({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:mT(r.playbackRateState$,new bc(1))}).pipe(vC(({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||fc(l)||(e=o-l)})).add(Un({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:mT(r.playbackRateState$,new bc(1))}).pipe(SC((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||fc(o)||fc(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=Oy(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 gT=O(Js(),1);import{assertNever as Ga,assertNonNullable as bT,debounce as yC,ErrorCategory as Hn,filter as TC,isNonNullable as IC,isNullable as EC,map as jn,merge as xC,Observable as PC,observableFrom as wC,Subscription as AC,videoSizeToQuality as kC}from"@vkontakte/videoplayer-shared/es2015";var et={};var di=(a,e)=>new PC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Wa=class{constructor(e){this.subscription=new AC;this.videoState=new V("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:Ga(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ga(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ga(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ga(e)}break;default:Ga(t)}};this.textTracksManager=new qe(e.source.url),this.video=Ee(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(oe(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),xe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Hn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,gT.default)(import("hls.js").then(i=>{e||(et.Hls=i.default,et.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){bT(et.Hls,"hls.js not loaded"),this.hls=new et.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){bT(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Hn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=we(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(nt(this.video,e.isLooped,r)),this.subscription.add(Pe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Fe(this.video,e.playbackRate,i.playbackRateState$,r)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(jn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(di(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Hn.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"),w(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(di(this.hls,et.Events.MANIFEST_PARSED).pipe(jn(({levels:l})=>l.reduce((c,d)=>{var S,T;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(T=Nt((S=d.attrs.QUALITY)!=null?S:""))!=null?T:kC({width:h,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(di(this.hls,et.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(di(this.hls,et.Events.LEVEL_LOADING).pipe(jn(({url:l})=>oe(l))),t.hostname$),s(di(this.hls,et.Events.FRAG_CHANGED),l=>{var p,h,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Bt(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=di(this.hls,et.Events.LEVEL_SWITCHED).pipe(jn(({level:l})=>n(this.hls.levels[l])));o.pipe(TC(IC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Bt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(EC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=xC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,wC(["init"])).pipe(yC(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 P(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hn.DOM,thrown:t})))||(this.videoState.setState("paused"),w(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"),w(this.params.desiredState.playbackState,"stopped",!0)}};var vT="X-Playback-Duration",gc=a=>P(void 0,null,function*(){var i;let e=yield lt(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(vT)?parseInt(e.headers.get(vT),10):void 0});import{assertNever as NC,combine as FC,debounce as qC,ErrorCategory as Wn,filter as UC,filterChanged as HC,isNonNullable as TT,isNullable as Yn,map as IT,merge as jC,observableFrom as QC,Subscription as GC,ValueSubject as yc,VideoQuality as WC}from"@vkontakte/videoplayer-shared/es2015";var Sc=O(Su(),1);import{videoSizeToQuality as LC,getExponentialDelay as $C}from"@vkontakte/videoplayer-shared/es2015";var RC=a=>{let e=null;if(a.QUALITY&&(e=Nt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=LC({width:t,height:r})}return e!=null?e:null},MC=(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(CC(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([$(x({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return P(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;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 P(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:_C.WTF,thrown:t,message:e})}};var Ya=class{constructor(e){this.subscription=new GC;this.videoState=new V("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new yc([]);this.liveOffset=new mr;this.manifestStartTime$=new yc(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"),w(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"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(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"&&w(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"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return NC(t)}};var r;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:WC.INVARIANT,url:this.params.source.url};let t=(i,s)=>Qn(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 Gn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new qe(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:Wn.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:Wn.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(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new yc((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:Wn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=we(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(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(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"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(HC(),IT(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&&TT(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(oe(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(FC({startTime:this.manifestStartTime$.pipe(UC(TT)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(IT(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=jC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,QC(["init"])).pipe(qC(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),xe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Yn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=he(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),gc(n).then(c=>{var d;if(!Yn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Yn(p)||!isFinite(p))&<(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();gc(g).then(v=>{Yn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wn.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=he(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}};import{assertNever as YC,debounce as zC,ErrorCategory as Tc,fromEvent as Ic,isNonNullable as KC,isNullable as XC,map as ET,merge as xT,observableFrom as PT,Subscription as JC,ValueSubject as ZC,VideoQuality as e0,clientChecker as t0}from"@vkontakte/videoplayer-shared/es2015";var za=class{constructor(e){this.subscription=new JC;this.videoState=new V("stopped");this.manifests$=new ZC([]);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"),w(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"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return YC(t)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:e0.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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Qn(he(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:Tc.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:Tc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=we(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(ET(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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&&KC(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(oe(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(ET(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)),!t0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(xT(Ic(o,"addtrack"),Ic(o,"removetrack"),Ic(o,"change"),PT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=xT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,PT(["init"])).pipe(zC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(XC(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(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var kT=O(qr(),1),Ec=O(Jr(),1),LT=O(Ft(),1);import{assertNever as r0,assertNonNullable as wT,debounce as i0,ErrorCategory as AT,isHigherOrEqual as a0,isLowerOrEqual as s0,isNonNullable as n0,merge as o0,observableFrom as u0,Subscription as l0,map as c0}from"@vkontakte/videoplayer-shared/es2015";var Ka=class{constructor(e){this.subscription=new l0;this.videoState=new V("stopped");this.trackUrls={};this.textTracksManager=new qe;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"),w(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"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return r0(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,kT.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,Ec.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:AT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=we(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(c0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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&&n0(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=o0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,u0(["init"])).pipe(i0(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),xe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;wT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];wT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ba(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:AT.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=Ut(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,Ec.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Yi({limits:e,lowestAvailableQuality:(c=(0,LT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?s0(i,e.max):!0,u=e.min?a0(i,e.min):!0;o&&u||r(e)}};import{assertNever as RT,debounce as m0,merge as MT,observableFrom as f0,Subscription as b0,map as DT,ValueSubject as g0,ErrorCategory as Pc,VideoQuality as v0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as d0}from"@vkontakte/videoplayer-shared/es2015";var $T=["stun:videostun.mycdn.me:80"],p0=1e3,h0=3,xc=()=>null,zn=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=xc;this.externalStopCallback=xc;this.externalErrorCallback=xc;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 P(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 P(this,null,function*(){try{let e={iceServers:[{urls:$T}]};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 P(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return P(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:d0.WTF,message:e.message})}onPeerConnectionStream(e){return P(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 P(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),p0)}normalizeOptions(e={}){let t={stunServerList:$T,maxRetryNumber:h0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Xa=class{constructor(e){this.videoState=new V("stopped");this.maxSeekBackTime$=new g0(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"),w(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"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return RT(e)}};this.subscription=new b0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new zn(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),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Pc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};MT(this.videoState.stateChangeStarted$.pipe(DT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(DT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=we(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(He(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(Pe(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 RT(n.to)}},r)).add(MT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,f0(["init"])).pipe(m0(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(oe(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:v0.INVARIANT}),this.video.srcObject=e,w(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:Pc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pc.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}};import{assertNever as es,assertNonNullable as Wt,ErrorCategory as Kn,filter as NT,isNonNullable as FT,isNullable as w0,map as A0,merge as k0,once as L0,Subject as le,Subscription as qT,ValueSubject as B,flattenObject as UT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as S0,map as CT,Subscription as y0,Subject as T0}from"@vkontakte/videoplayer-shared/es2015";var VT=a=>new S0(e=>{let t=new y0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(CT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(CT(({type:l})=>l!==void 0)),n=new T0,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()}});import{ErrorCategory as I0,Subscription as E0,combine as x0,filter as OT,once as _T}from"@vkontakte/videoplayer-shared/es2015";function BT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as P0}from"@vkontakte/videoplayer-shared/es2015";var Za=class Za{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new me;this.subscriptions=new E0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(OT(s=>!!s.type),_T()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){P0.isSafari&&e!=="MPEG"||this.subscriptions.add(x0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(OT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),_T()).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 P(this,null,function*(){let{volumeMultiplier:t}=this,r=BT();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:Za.errorId,category:I0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Za.errorId} exception`,thrown:e})}};Za.errorId="VolumeMultiplierManager";var pi=Za;var $0={chunkDuration:5e3,maxParallelRequests:5},ts=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new le;this.noAvailableProvidersError$=new le;this.volumeMultiplierError$=new le;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new le,fetcherError$:new le,fetcherRecoverableError$:new le,warning$:new le,willSeekEvent$:new le,soundProhibitedEvent$:new le,seekedEvent$:new le,loopedEvent$:new le,endedEvent$:new le,firstBytesEvent$:new le,loadedMetadataEvent$:new le,firstFrameEvent$:new le,canplay$:new le,isLive$:new B(void 0),isLiveEnded$:new B(null),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),severeStallOccurred$:new le,availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B(""),getCurrentTime$:new B(null)};this.subscription=new qT;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=cS([...pS(this.params.tuning),...dS(this.params.tuning)],this.params.tuning).filter(l=>FT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,wc.default)(i,l)),...t.filter(l=>(0,wc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",UT(s)),this.screenFormatsIterator=new Ja(s);let n=[...Ll(!0),...Ll(!1)];this.chromecastFormatsIterator=new Ja(n.filter(l=>FT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&pi.isSupported()&&(this.volumeMultiplierManager=new pi(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(w0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Kn.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 es(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 Wt(o),new ja($(x({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Qa($(x({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Wt(o),ii||!this.params.tuning.useHlsJs?new za($(x({},n),{source:o})):new Wa($(x({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Ya($(x({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Ka($(x({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new kv($(x({},n),{source:o,config:$(x({},$0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Xa({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 es(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 Wt(o),new ji({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 es(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return es(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 es(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 $(x({},e),{url:r(e.url)})}return(0,jT.default)((0,HT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new qT,t=!1,r=0;return e.add(k0(this.providerOutput.error$.pipe(NT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),VT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(A0(i=>({id:`ProviderHangup:${i}`,category:Kn.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(NT(({to:s})=>s==="playing"),L0()).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===Kn.NETWORK,u=i.category===Kn.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=$(x({},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",UT(n))})),e}};import{fromEvent as Xn,once as R0,combine as M0,Subscription as QT,ValueSubject as Ac,map as D0,filter as C0,isNonNullable as Jn,now as _e,safeStorage as kc}from"@vkontakte/videoplayer-shared/es2015";var V0=5e3,GT="one_video_throughput",WT="one_video_rtt",It=window.navigator.connection,YT=()=>{let a=It==null?void 0:It.downlink;if(Jn(a)&&a!==10)return a*1e3},zT=()=>{let a=It==null?void 0:It.rtt;if(Jn(a)&&a!==3e3)return a},KT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Lc=class a{constructor(e){this.subscription=new QT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(GT)||(e.useBrowserEstimation?YT():void 0)||V0,r=(s=(i=a.load(WT))!=null?i:e.useBrowserEstimation?zT():void 0)!=null?s:0;if(this.throughput$=new Ac(t),this.rtt$=new Ac(r),this.rttAdjustedThroughput$=new Ac(KT(t,r,e.rttPenaltyRequestSize)),this.throughput=yr.getSmoothedValue(t,-1,e),this.rtt=yr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=YT();u&&this.throughput.next(u);let l=zT();Jn(l)&&this.rtt.next(l)};It&&"onchange"in It&&this.subscription.add(Xn(It,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{kc.set(GT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{kc.set(WT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(M0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(D0(({throughput:n,rtt:o})=>KT(n,o,e.rttPenaltyRequestSize)),C0(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=_e(),i=new QT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Xn(e,"progress").pipe(R0()).subscribe(s=>{t=s.loaded,r=_e()}));break;case 1:case 0:i.add(Xn(e,"loadstart").subscribe(()=>{t=0,r=_e()}));break}i.add(Xn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=_e(),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=_e(),n=0,o=_e(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>P(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,_e()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=_e();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=_e()}else n+=d.byteLength;o=_e()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&_e()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,_e()-o,this.concurrentDownloads.size),n=0,o=_e());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=kc.get(e);if(Jn(t))return(r=parseInt(t,10))!=null?r:void 0}},XT=Lc;import{fillWithDefault as B0,VideoQuality as Zn}from"@vkontakte/videoplayer-shared/es2015";var JT={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:Zn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Zn.Q_720P,trafficSavingLimit:Zn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Zn.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:!0,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},ZT=a=>{var e;return $(x({},B0(a,JT)),{configName:[...(e=a.configName)!=null?e:[],...JT.configName]})};import{assertNonNullable as eo,combine as Et,ErrorCategory as to,filter as Ie,filterChanged as W,fromEvent as Rc,isNonNullable as H0,isNullable as j0,Logger as Q0,map as H,mapTo as iI,merge as Yt,now as ro,once as dt,Subject as Y,Subscription as aI,tap as Mc,ValueSubject as A,isHigher as G0,isInvariantQuality as sI,flattenObject as zt,throttle as Dc,getTraceSubscriptionMethod as nI,Tracer as W0,InternalsExposure as Y0}from"@vkontakte/videoplayer-shared/es2015";import{merge as O0,map as _0,filter as eI,isNonNullable as N0}from"@vkontakte/videoplayer-shared/es2015";var $c=({seekState:a,position$:e})=>O0(a.stateChangeEnded$.pipe(_0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),eI(N0)),e.pipe(eI(()=>a.getState().state==="none")));import{assertNonNullable as F0}from"@vkontakte/videoplayer-shared/es2015";var tI=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return F0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as q0,once as U0}from"@vkontakte/videoplayer-shared/es2015";var rI=(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(q0(i=>i.length>0),U0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var io=class{constructor(e={configName:[]},t=W0.createRootTracer(!1)){this.subscription=new aI;this.logger=new Q0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new V("stopped"),seekState:new V({state:"none"}),volume:new V({volume:1,muted:!1}),videoTrack:new V(void 0),videoStream:new V(void 0),audioStream:new V(void 0),autoVideoTrackSwitching:new V(!0),autoVideoTrackLimits:new V({}),isLooped:new V(!1),isLowLatency:new V(!1),playbackRate:new V(1),externalTextTracks:new V([]),internalTextTracks:new V([]),currentTextTrack:new V(void 0),textTrackCuesSettings:new V({}),cameraOrientation:new V({x:0,y:0})};this.info={playbackState$:new A("stopped"),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),predefinedQualityLimitType$:new A("unknown"),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),isLiveEnded$:new A(null),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,fetcherRecoverableError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,autoplaySoundProhibited$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y,fetcherError$:new Y,severeStallOccured$:new Y};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Jg,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=ZT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new xs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new XT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new Y0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return(0,oI.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:to.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=yd(i,["container"]);return this.tracer.log("initVideo",zt(r)),this.domContainer=tI(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new ts({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&&!ea()?(this.tracer.log("request play from hidden tab"),Rc(document,"visibilitychange").pipe(dt()).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){eo(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(Ie(r=>r.length>0),dt()).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",zt(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;eo(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",zt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>x({type:"external"},t))),this}selectTextTrack(e){var t;return rI(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",x({},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(j0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return H0(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(Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ml({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Ie(({from:e})=>e==="stopped"),dt()).subscribe(()=>{this.initedAt=ro(),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",zt(n)),n.state==="requested"?this.desiredState.seekState.setState($(x({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:to.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(dt()).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",zt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(H(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(H(n=>n.destination),W()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Et({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(H(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>sI(u)?1:sI(l)?-1:G0(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(W()).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(W((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(W((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(W()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(W()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(W()).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(H(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(Mc(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(Et({hasLiveOffsetByPaused:Yt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(n=>n.to),W(),H(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(Et({atLiveEdge:Et({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:$c({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(H(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),W(),Mc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(H(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Et({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(H(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),W(),Mc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(H(n=>n.muted),W()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(H(n=>n.volume),W()).subscribe(this.info.volume$)).add($c({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Yt(e.providerOutput.endedEvent$.pipe(iI(!0)),e.providerOutput.seekedEvent$.pipe(iI(!1))).pipe(W()).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(H(n=>({id:n?`No${n}`:"NoProviders",category:to.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(dt(),H(n=>n!=null?n:ro()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(dt(),H(()=>ro()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(dt(),H(()=>ro()-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 A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new A(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Ie(({to:n})=>n==="playing"),dt()).subscribe(()=>r.next(!1)));let i=0,s=Yt(e.providerOutput.isBuffering$,t,r).pipe(H(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),W());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(Yt(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(Yt(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(H(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 aI;this.subscription.add(t),this.subscription.add(e.current$.pipe(W((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Ie(r=>r.length>0),dt()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Ut(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(Yt(this.desiredState.videoTrack.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(H(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;eo(this.providerContainer),eo(e),Xg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Kg(r)),this.providerContainer.current$.subscribe(({type:r})=>Wi("provider",r)),e.duration$.subscribe(r=>Wi("duration",r)),e.availableVideoTracks$.pipe(Ie(r=>!!r.length),dt()).subscribe(r=>Wi("tracks",r)),this.events.fatalError$.subscribe(new Se("fatalError")),this.events.managedError$.subscribe(new Se("managedError")),e.position$.subscribe(new Se("position")),e.currentVideoTrack$.pipe(H(r=>r==null?void 0:r.quality)).subscribe(new Se("quality")),this.info.currentBuffer$.subscribe(new Se("buffer")),e.isBuffering$.subscribe(new Se("isBuffering"))].forEach(r=>this.subscription.add(r)),Wi("codecs",lS())}initTracerSubscription(){let e=nI(this.tracer.log.bind(this.tracer)),t=nI(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(W()).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(Et({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Ie(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),W((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Ie(r=>r>0),W()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Ie(r=>r>0),W()).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(Et({currentBuffer:this.info.currentBuffer$.pipe(Ie(r=>r.end>0),W((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(W())}).pipe(Dc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(W()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(W()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(W()).subscribe(e("canChangePlaybackSpeed"))).add(Et({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Ie(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Dc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(W(),Ie(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(W(),Ie(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(W()).subscribe(e("muted"))).add(this.info.volume$.pipe(W()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(W(),Ie(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Et({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Ie(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Dc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(W(),Ie(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=()=>P(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:to.DOM,message:String(i)})})});this.subscription.add(Yt(Rc(document,"visibilitychange"),Rc(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",zt({quality:t,availableTracks:zt(e),track:zt(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}};import{Subscription as x8,Observable as P8,Subject as w8,ValueSubject as A8,VideoQuality as k8}from"@vkontakte/videoplayer-shared/es2015";var L8=`@vkontakte/videoplayer-core@${Td}`;export{gs as ChromecastState,po as HttpConnectionType,P8 as Observable,Me as PlaybackState,io as Player,vs as PredefinedQualityLimits,L8 as SDK_VERSION,w8 as Subject,x8 as Subscription,ho as Surface,Td as VERSION,A8 as ValueSubject,Mt as VideoFormat,k8 as VideoQuality};
|
|
124
|
+
`;var Mn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new Rn(this.params.fov,this.params.orientation),this.cameraRotationManager=new $n(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(Dy,this.gl.VERTEX_SHADER),r=this.createShader(Vy,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}};import{isNullable as MC,now as _y,Subscription as CC,filter as DC,combine as Oy,ValueSubject as tc,isNonNullable as VC}from"@vkontakte/videoplayer-shared/es2015";var rc=class{constructor(){this.isSeeked$=new tc(!1);this.isBuffering$=new tc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new CC;this.severeStallOccurred$=new tc(!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(Oy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(DC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Oy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(MC(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=_y(),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,VC(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=_y(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},By=rc;import{combine as _C,map as OC,observeElementSize as BC,Subscription as NC,ValueSubject as ic,noop as FC}from"@vkontakte/videoplayer-shared/es2015";var Cn=class{constructor(){this.subscription=new NC;this.pipSize$=new ic(void 0);this.videoSize$=new ic(void 0);this.elementSize$=new ic(void 0);this.pictureInPictureWindowRemoveEventListener=FC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(BC(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(_C({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(OC(({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 Tr=class{constructor(e){this.subscription=new WC;this.videoState=new O("stopped");this.droppedFramesManager=new hn;this.stallsManager=new By;this.elementSizeManager=new Cn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Gi;this.audioTrackSwitchHistory=new Gi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),w(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"),w(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&w(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return HC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Mn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ue(e.source.url),this.params=e,this.video=we(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(ce(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 Ln({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=Le(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Ny.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(Fy(l=>!!l.length),Uy()).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(ac(l=>l.to.state!=="none"),Fa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Fa()),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(Fy(qy),Uy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(ac(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(Ae(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(jC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Nl(h));let m=[];for(let b of h.representations){let g=oy(b);m.push(g),this.audioTracksMap.set(g,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Fl(p));let h=[];for(let m of p.representations){let b=ny($(P({},m),{streamId:p.id}));b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=uy(p,h);this.textTracksMap.set(m,{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(Dn(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$,GC(this.video,"progress")).subscribe(()=>x(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Hy.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,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===p.id});qy(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.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 g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",h.id,g)}}),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(Fa()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.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(Fl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Fa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.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(Nl(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(ac(({to:l})=>l==="ready"),Fa());this.subscription.add(Dn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,sc(["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(Dn(o,this.player.state$.stateChangeEnded$,sc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Dn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,sc(["init"])).pipe(QC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var M,re,C,j,Q,R,G,q,J,A,T,V,Y;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(M=e.videoTrack.getState())==null?void 0:M.id,n=[...this.videoTracksMap.keys()].find(({id:U})=>U===i),o=t.currentVideoTrack$.getValue(),u=((j=(C=e.videoStream.getState())!=null?C:n&&((re=this.videoTracksMap.get(n))==null?void 0:re.stream))!=null?j:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:U})=>U===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ut(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,m=Math.min(d/Math.min(p,h||1/0),1),b=(Q=e.audioStream.getState())!=null?Q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(R=[...this.audioStreamsMap.keys()].find(({id:U})=>U===(b==null?void 0:b.id)))!=null?R:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let U=ln(n,c,(G=this.audioStreamsMap.get(g))!=null?G:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(q=U==null?void 0:U.bitrate)!=null?q:-1/0)}if(o){let U=ln(o,c,(J=this.audioStreamsMap.get(g))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(A=U==null?void 0:U.bitrate)!=null?A:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=r?S!=null?S:n:n!=null?n:S,E=g&&rv(y,c,(T=this.audioStreamsMap.get(g))!=null?T:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(V=this.videoTracksMap.get(y))==null?void 0:V.representation,L=E&&((Y=this.audioTracksMap.get(E))==null?void 0:Y.representation);if(I&&L)return[I,L];if(I&&!L&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ny.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),ke(this.video),this.tracer.end()}};var qa=class extends Tr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as jy,interval as YC,map as Qy}from"@vkontakte/videoplayer-shared/es2015";var Ua=class extends Tr{constructor(e){super(e),this.liveOffset=new bt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(Qy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(jy({interval:YC(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(jy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Qy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=ly(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Wy=_(zs(),1);import{assertNever as Ha,assertNonNullable as Gy,debounce as zC,ErrorCategory as Vn,filter as KC,isNonNullable as XC,isNullable as JC,map as _n,merge as ZC,Observable as eD,observableFrom as tD,Subscription as rD,videoSizeToQuality as iD}from"@vkontakte/videoplayer-shared/es2015";var et={};var oi=(a,e)=>new eD(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),ja=class{constructor(e){this.subscription=new rD;this.videoState=new O("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:Ha(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ha(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ha(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ha(e)}break;default:Ha(t)}};this.textTracksManager=new Ue(e.source.url),this.video=we(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(ce(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),ke(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Vn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Wy.default)(import("hls.js").then(i=>{e||(et.Hls=i.default,et.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Gy(et.Hls,"hls.js not loaded"),this.hls=new et.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Gy(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Vn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Le(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(nt(this.video,e.isLooped,r)),this.subscription.add(Ae(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,i.playbackRateState$,r)),s(je(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(_n(l=>l.to)),this.params.output.playbackState$),this.subscription.add(oi(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Vn.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"),w(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(oi(this.hls,et.Events.MANIFEST_PARSED).pipe(_n(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(y=Ot((S=d.attrs.QUALITY)!=null?S:""))!=null?y:iD({width:h,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(oi(this.hls,et.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(oi(this.hls,et.Events.LEVEL_LOADING).pipe(_n(({url:l})=>ce(l))),t.hostname$),s(oi(this.hls,et.Events.FRAG_CHANGED),l=>{var p,h,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Dt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=oi(this.hls,et.Events.LEVEL_SWITCHED).pipe(_n(({level:l})=>n(this.hls.levels[l])));o.pipe(KC(XC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Dt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(JC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=ZC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,tD(["init"])).pipe(zC(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 x(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vn.DOM,thrown:t})))||(this.videoState.setState("paused"),w(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"),w(this.params.desiredState.playbackState,"stopped",!0)}};var Yy="X-Playback-Duration",nc=a=>x(void 0,null,function*(){var i;let e=yield lt(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(Yy)?parseInt(e.headers.get(Yy),10):void 0});import{assertNever as mD,combine as fD,debounce as bD,ErrorCategory as Nn,filter as gD,filterChanged as vD,isNonNullable as Xy,isNullable as Fn,map as Jy,merge as SD,observableFrom as yD,Subscription as TD,ValueSubject as lc,VideoQuality as ID}from"@vkontakte/videoplayer-shared/es2015";var uc=_(du(),1);import{videoSizeToQuality as aD,getExponentialDelay as sD}from"@vkontakte/videoplayer-shared/es2015";var nD=a=>{let e=null;if(a.QUALITY&&(e=Ot(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=aD({width:t,height:r})}return e!=null?e:null},oD=(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,uc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=nD(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[S,y]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,uc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},uD=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),oc=0,zy=(i,...s)=>x(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield lt(a,r)).text();oc+=1;try{let{qualityManifests:u,textTracks:l}=oD(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(oc<=t.manifestRetryMaxCount)return yield uD(sD(oc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),zy(a,e,t)}return{qualityManifests:[],textTracks:[]}}),On=zy;import{isNonNullable as lD,Subscription as cD,throttle as dD,ValueSubject as Ky,Subject as pD,ErrorCategory as hD}from"@vkontakte/videoplayer-shared/es2015";var Bn=class{constructor(e,t,r,i,s){this.subscription=new cD;this.abortControllers={destroy:new ge,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Ky(null);this.getCurrentTime$=new Ky(null);this.error$=new pD;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(dD(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 x(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 x(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 x(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield lt(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
|
|
126
|
+
`),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(lD(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([$(P({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return x(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ge;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 x(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:hD.WTF,thrown:t,message:e})}};var Qa=class{constructor(e){this.subscription=new TD;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new lc([]);this.liveOffset=new bt;this.manifestStartTime$=new lc(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"),w(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"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),w(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"&&w(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"&&(w(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return mD(t)}};var r;this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ID.INVARIANT,url:this.params.source.url};let t=(i,s)=>On(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 Bn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ue(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:Nn.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:Nn.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(ce(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new lc((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:Nn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Le(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(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(je(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"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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(vD(),Jy(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&&Xy(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(ce(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(fD({startTime:this.manifestStartTime$.pipe(gD(Xy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Jy(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=SD(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,yD(["init"])).pipe(bD(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),ke(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Fn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=be(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),nc(n).then(c=>{var d;if(!Fn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Fn(p)||!isFinite(p))&<(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();nc(g).then(v=>{Fn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nn.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=be(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}};import{assertNever as ED,debounce as xD,ErrorCategory as cc,fromEvent as dc,isNonNullable as PD,isNullable as wD,map as Zy,merge as eT,observableFrom as tT,Subscription as kD,ValueSubject as AD,VideoQuality as LD}from"@vkontakte/videoplayer-shared/es2015";var Ga=class{constructor(e){this.subscription=new kD;this.videoState=new O("stopped");this.manifests$=new AD([]);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"),w(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"?w(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return ED(t)}};this.textTracksManager=new Ue(e.source.url),this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:LD.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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),On(be(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:cc.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:cc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Le(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(Zy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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&&PD(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(ce(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Zy(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)),!N.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(eT(dc(o,"addtrack"),dc(o,"removetrack"),dc(o,"change"),tT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=eT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,tT(["init"])).pipe(xD(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var s,n;let e=this.selectManifest();if(wD(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(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var aT=_(Fr(),1),pc=_(Xr(),1),sT=_(Bt(),1);import{assertNever as RD,assertNonNullable as rT,debounce as $D,ErrorCategory as iT,isHigherOrEqual as MD,isLowerOrEqual as CD,isNonNullable as DD,merge as VD,observableFrom as _D,Subscription as OD,map as BD}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new OD;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Ue;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"),w(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"?w(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return RD(e)}};this.params=e,this.video=we(e.container,e.tuning),this.params.output.element$.next(this.video),(0,aT.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,pc.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:iT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Le(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(BD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(Ae(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,r)),s(je(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),w(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),w(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&&DD(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=VD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,_D(["init"])).pipe($D(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),ke(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;rT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];rT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ma(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ce(t))}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:iT.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=Ft(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,pc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Qi({limits:e,lowestAvailableQuality:(c=(0,sT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?CD(i,e.max):!0,u=e.min?MD(i,e.min):!0;o&&u||r(e)}};import{assertNever as oT,debounce as UD,merge as uT,observableFrom as HD,Subscription as jD,map as lT,ValueSubject as QD,ErrorCategory as mc,VideoQuality as GD}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as ND}from"@vkontakte/videoplayer-shared/es2015";var nT=["stun:videostun.mycdn.me:80"],FD=1e3,qD=3,hc=()=>null,qn=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=hc;this.externalStopCallback=hc;this.externalErrorCallback=hc;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 x(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 x(this,null,function*(){try{let e={iceServers:[{urls:nT}]};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 x(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return x(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:ND.WTF,message:e.message})}onPeerConnectionStream(e){return x(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 x(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),FD)}normalizeOptions(e={}){let t={stunServerList:nT,maxRetryNumber:qD,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 O("stopped");this.maxSeekBackTime$=new QD(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"),w(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"),w(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"&&w(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&w(this.params.desiredState.playbackState,"paused");return;default:return oT(e)}};this.subscription=new jD,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=we(e.container,e.tuning),this.liveStreamClient=new qn(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),ke(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:mc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};uT(this.videoState.stateChangeStarted$.pipe(lT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(lT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Le(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(je(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ae(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 oT(n.to)}},r)).add(uT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,HD(["init"])).pipe(UD(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(ce(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:GD.INVARIANT}),this.video.srcObject=e,w(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:mc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Re(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),w(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mc.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}};import{assertNever as Xa,assertNonNullable as Qt,ErrorCategory as Un,filter as fT,isNonNullable as bT,isNullable as ZD,map as e0,merge as t0,once as r0,Subject as pe,Subscription as gT,ValueSubject as B,flattenObject as vT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as WD,map as cT,Subscription as YD,Subject as zD}from"@vkontakte/videoplayer-shared/es2015";var dT=a=>new WD(e=>{let t=new YD,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(cT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(cT(({type:l})=>l!==void 0)),n=new zD,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()}});import{ErrorCategory as KD,Subscription as XD,combine as JD,filter as hT,once as mT}from"@vkontakte/videoplayer-shared/es2015";function pT(){return new(window.AudioContext||window.webkitAudioContext)}var Ka=class Ka{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ge;this.subscriptions=new XD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(hT(s=>!!s.type),mT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){N.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(JD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(hT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),mT()).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 x(this,null,function*(){let{volumeMultiplier:t}=this,r=pT();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:KD.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ka.errorId} exception`,thrown:e})}};Ka.errorId="VolumeMultiplierManager";var ui=Ka;var i0={chunkDuration:5e3,maxParallelRequests:5},Ja=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new pe;this.noAvailableProvidersError$=new pe;this.volumeMultiplierError$=new pe;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new pe,fetcherError$:new pe,fetcherRecoverableError$:new pe,warning$:new pe,willSeekEvent$:new pe,soundProhibitedEvent$:new pe,seekedEvent$:new pe,loopedEvent$:new pe,endedEvent$:new pe,firstBytesEvent$:new pe,loadedMetadataEvent$:new pe,firstFrameEvent$:new pe,canplay$:new pe,isLive$:new B(void 0),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),severeStallOccurred$:new pe,availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B(""),getCurrentTime$:new B(null)};this.subscription=new gT;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=wy([...Ay(this.params.tuning),...ky(this.params.tuning)],this.params.tuning).filter(l=>bT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,fc.default)(i,l)),...t.filter(l=>(0,fc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",vT(s)),this.screenFormatsIterator=new za(s);let n=[...Kl(!0),...Kl(!1)];this.chromecastFormatsIterator=new za(n.filter(l=>bT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ui.isSupported()&&(this.volumeMultiplierManager=new ui(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(ZD(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Un.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 Xa(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 Qt(o),new qa($(P({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ua($(P({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Qt(o),N.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Ga($(P({},n),{source:o})):new ja($(P({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Qa($(P({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Wa($(P({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Sv($(P({},n),{source:o,config:$(P({},i0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(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 Xa(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 Qt(o),new Fi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Xa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Xa(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 Xa(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 $(P({},e),{url:r(e.url)})}return(0,yT.default)((0,ST.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new gT,t=!1,r=0;return e.add(t0(this.providerOutput.error$.pipe(fT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),dT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(e0(i=>({id:`ProviderHangup:${i}`,category:Un.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(fT(({to:s})=>s==="playing"),r0()).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===Un.NETWORK,u=i.category===Un.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=$(P({},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",vT(n))})),e}};import{fromEvent as Hn,once as a0,combine as s0,Subscription as TT,ValueSubject as bc,map as n0,filter as o0,isNonNullable as jn,now as Be,safeStorage as gc}from"@vkontakte/videoplayer-shared/es2015";var u0=5e3,IT="one_video_throughput",ET="one_video_rtt",Tt=window.navigator.connection,xT=()=>{let a=Tt==null?void 0:Tt.downlink;if(jn(a)&&a!==10)return a*1e3},PT=()=>{let a=Tt==null?void 0:Tt.rtt;if(jn(a)&&a!==3e3)return a},wT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},vc=class a{constructor(e){this.subscription=new TT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(IT)||(e.useBrowserEstimation?xT():void 0)||u0,r=(s=(i=a.load(ET))!=null?i:e.useBrowserEstimation?PT():void 0)!=null?s:0;if(this.throughput$=new bc(t),this.rtt$=new bc(r),this.rttAdjustedThroughput$=new bc(wT(t,r,e.rttPenaltyRequestSize)),this.throughput=br.getSmoothedValue(t,-1,e),this.rtt=br.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=xT();u&&this.throughput.next(u);let l=PT();jn(l)&&this.rtt.next(l)};Tt&&"onchange"in Tt&&this.subscription.add(Hn(Tt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{gc.set(IT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{gc.set(ET,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(s0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(n0(({throughput:n,rtt:o})=>wT(n,o,e.rttPenaltyRequestSize)),o0(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=Be(),i=new TT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Hn(e,"progress").pipe(a0()).subscribe(s=>{t=s.loaded,r=Be()}));break;case 1:case 0:i.add(Hn(e,"loadstart").subscribe(()=>{t=0,r=Be()}));break}i.add(Hn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Be(),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=Be(),n=0,o=Be(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>x(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Be()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Be();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Be()}else n+=d.byteLength;o=Be()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Be()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Be()-o,this.concurrentDownloads.size),n=0,o=Be());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=gc.get(e);if(jn(t))return(r=parseInt(t,10))!=null?r:void 0}},kT=vc;import{fillWithDefault as l0,VideoQuality as Qn}from"@vkontakte/videoplayer-shared/es2015";var AT={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:Qn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Qn.Q_720P,trafficSavingLimit:Qn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Qn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!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},LT=a=>{var e;return $(P({},l0(a,AT)),{configName:[...(e=a.configName)!=null?e:[],...AT.configName]})};import{assertNonNullable as Gn,combine as It,ErrorCategory as Wn,filter as D,filterChanged as K,fromEvent as yc,isNonNullable as b0,isNullable as g0,Logger as v0,map as W,mapTo as CT,merge as Gt,now as Yn,once as F,Subject as X,Subscription as DT,tap as VT,ValueSubject as k,isHigher as S0,isInvariantQuality as _T,flattenObject as Wt,throttle as Tc,getTraceSubscriptionMethod as OT,Tracer as y0,InternalsExposure as T0}from"@vkontakte/videoplayer-shared/es2015";import{merge as c0,map as d0,filter as RT,isNonNullable as p0}from"@vkontakte/videoplayer-shared/es2015";var Sc=({seekState:a,position$:e})=>c0(a.stateChangeEnded$.pipe(d0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),RT(p0)),e.pipe(RT(()=>a.getState().state==="none")));import{assertNonNullable as h0}from"@vkontakte/videoplayer-shared/es2015";var $T=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return h0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as m0,once as f0}from"@vkontakte/videoplayer-shared/es2015";var MT=(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(m0(i=>i.length>0),f0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var zn=class{constructor(e={configName:[]},t=y0.createRootTracer(!1)){this.subscription=new DT;this.logger=new v0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new k(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInited=new k(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new k("stopped"),position$:new k(0),duration$:new k(1/0),muted$:new k(!1),volume$:new k(1),availableVideoStreams$:new k([]),currentVideoStream$:new k(void 0),availableQualities$:new k([]),availableQualitiesFps$:new k({}),currentQuality$:new k(void 0),isAutoQualityEnabled$:new k(!0),autoQualityLimitingAvailable$:new k(!1),autoQualityLimits$:new k({}),predefinedQualityLimitType$:new k("unknown"),availableAudioStreams$:new k([]),currentAudioStream$:new k(void 0),availableAudioTracks$:new k([]),isAudioAvailable$:new k(!0),currentPlaybackRate$:new k(1),currentBuffer$:new k({start:0,end:0}),isBuffering$:new k(!0),isStalled$:new k(!1),isEnded$:new k(!1),isLooped$:new k(!1),isLive$:new k(void 0),canChangePlaybackSpeed$:new k(void 0),atLiveEdge$:new k(void 0),atLiveDurationEdge$:new k(void 0),liveTime$:new k(void 0),liveBufferTime$:new k(void 0),liveLatency$:new k(void 0),currentFormat$:new k(void 0),availableTextTracks$:new k([]),currentTextTrack$:new k(void 0),throughputEstimation$:new k(void 0),rttEstimation$:new k(void 0),videoBitrate$:new k(void 0),hostname$:new k(void 0),httpConnectionType$:new k(void 0),httpConnectionReused$:new k(void 0),surface$:new k("none"),chromecastState$:new k("NOT_AVAILABLE"),chromecastDeviceName$:new k(void 0),intrinsicVideoSize$:new k(void 0),availableSources$:new k(void 0),is3DVideo$:new k(!1),currentVideoSegmentLength$:new k(0),currentAudioSegmentLength$:new k(0)};this.events={inited$:new X,ready$:new X,started$:new X,playing$:new X,paused$:new X,stopped$:new X,willStart$:new X,willResume$:new X,willPause$:new X,willStop$:new X,willDestruct$:new X,watchCoverageRecord$:new X,watchCoverageLive$:new X,managedError$:new X,fatalError$:new X,fetcherRecoverableError$:new X,ended$:new X,looped$:new X,seeked$:new X,willSeek$:new X,autoplaySoundProhibited$:new X,firstBytes$:new X,loadedMetadata$:new X,firstFrame$:new X,canplay$:new X,log$:new X,fetcherError$:new X,severeStallOccured$:new X};this.experimental={element$:new k(void 0),tuningConfigName$:new k([]),enableDebugTelemetry$:new k(!1),dumpTelemetry:Hg,getCurrentTime$:new k(null)};if(this.initLogs(),this.tuning=LT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ts({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new kT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new T0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return(0,BT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Wn.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=ad(o,["container"]);this.tracer.log("initVideo",Wt(n)),this.domContainer=$T(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ja({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?N.isInited$.pipe(D(s=>!!s),F()).subscribe(()=>{console.log("Core SDK async start"),t()}):t()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),yc(document,"visibilitychange").pipe(F()).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(D(e=>!!e),F()).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(D(e=>!!e),F()).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(D(e=>!!e),F()).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(D(e=>!!e),F()).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(D(r=>!!r),F()).subscribe(()=>{let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;e>=r&&!i&&(s=r-.2),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.playerInited.pipe(D(t=>!!t),F()).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(D(r=>!!r),F()).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(D(t=>!!t),F()).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(D(t=>!!t),F()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{Gn(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(D(r=>r.length>0),F()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Wt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.playerInited.pipe(D(t=>!!t),F()).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(D(t=>!!t),F()).subscribe(()=>{var r;Gn(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(D(t=>!!t),F()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>P({type:"external"},t)))}),this}selectTextTrack(e){return this.playerInited.pipe(D(t=>!!t),F()).subscribe(()=>{var t;MT(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(D(t=>!!t),F()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",P({},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(D(t=>!!t),F()).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(D(r=>!!r),F()).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(D(t=>!!t),F()).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(D(r=>!!r),F()).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(D(e=>e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.playerInited.pipe(D(e=>!!e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(g0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return b0(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(Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(ol({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(D(({from:e})=>e==="stopped"),F()).subscribe(()=>{this.initedAt=Yn(),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",Wt(n)),n.state==="requested"?this.desiredState.seekState.setState($(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Wn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(F()).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",Wt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(W(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(W(n=>n.destination),K()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(It({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(W(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>_T(u)?1:_T(l)?-1:S0(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(K()).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(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(K()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(K()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(K()).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(W(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(It({hasLiveOffsetByPaused:Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(n=>n.to),K(),W(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(It({atLiveEdge:It({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(W(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),K(),VT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(W(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(It({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(W(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),K(),VT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(W(n=>n.muted),K()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(W(n=>n.volume),K()).subscribe(this.info.volume$)).add(Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Gt(e.providerOutput.endedEvent$.pipe(CT(!0)),e.providerOutput.seekedEvent$.pipe(CT(!1))).pipe(K()).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(W(n=>({id:n?`No${n}`:"NoProviders",category:Wn.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(F(),W(n=>n!=null?n:Yn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(F(),W(()=>Yn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(F(),W(()=>Yn()-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 k(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new k(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(D(({to:n})=>n==="playing"),F()).subscribe(()=>r.next(!1)));let i=0,s=Gt(e.providerOutput.isBuffering$,t,r).pipe(W(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),K());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(Gt(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(Gt(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(W(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 DT;this.subscription.add(t),this.subscription.add(e.current$.pipe(K((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(D(r=>r.length>0),F()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Ft(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(Gt(this.desiredState.videoTrack.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(W(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;Gn(this.providerContainer),Gn(e),Ug(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>qg(r)),this.providerContainer.current$.subscribe(({type:r})=>ji("provider",r)),e.duration$.subscribe(r=>ji("duration",r)),e.availableVideoTracks$.pipe(D(r=>!!r.length),F()).subscribe(r=>ji("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(W(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),ji("codecs",N.video.supportedCodecs)}initTracerSubscription(){let e=OT(this.tracer.log.bind(this.tracer)),t=OT(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(K()).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(It({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(D(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),K((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(D(r=>r>0),K()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(D(r=>r>0),K()).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(It({currentBuffer:this.info.currentBuffer$.pipe(D(r=>r.end>0),K((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(K())}).pipe(Tc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(K()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(K()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(K()).subscribe(e("canChangePlaybackSpeed"))).add(It({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(D(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Tc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(K(),D(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(K(),D(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(K()).subscribe(e("muted"))).add(this.info.volume$.pipe(K()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(K(),D(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(It({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(D(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Tc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(K(),D(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=()=>x(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:Wn.DOM,message:String(i)})})});this.subscription.add(Gt(yc(document,"visibilitychange"),yc(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",Wt({quality:t,availableTracks:Wt(e),track:Wt(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&&!Xi()}};import{Subscription as NK,Observable as FK,Subject as qK,ValueSubject as UK,VideoQuality as HK}from"@vkontakte/videoplayer-shared/es2015";var jK=`@vkontakte/videoplayer-core@${sd}`;export{ms as ChromecastState,io as HttpConnectionType,FK as Observable,Pe as PlaybackState,zn as Player,fs as PredefinedQualityLimits,jK as SDK_VERSION,qK as Subject,NK as Subscription,ao as Surface,sd as VERSION,UK as ValueSubject,pt as VideoFormat,HK as VideoQuality,N as clientChecker,Hi as isMobile};
|