@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/es2018.esm.js
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
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 aI=Object.create;var ld=Object.defineProperty;var sI=Object.getOwnPropertyDescriptor;var nI=Object.getOwnPropertyNames;var oI=Object.getPrototypeOf,uI=Object.prototype.hasOwnProperty;var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var lI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of nI(e))!uI.call(a,i)&&i!==t&&ld(a,i,{get:()=>e[i],enumerable:!(r=sI(e,i))||r.enumerable});return a};var C=(a,e,t)=>(t=a!=null?aI(oI(a)):{},lI(e||!a||!a.__esModule?ld(t,"default",{value:a,enumerable:!0}):t,a));var Z=f((ao,dd)=>{"use strict";var bi=function(a){return a&&a.Math===Math&&a};dd.exports=bi(typeof globalThis=="object"&&globalThis)||bi(typeof window=="object"&&window)||bi(typeof self=="object"&&self)||bi(typeof global=="object"&&global)||bi(typeof ao=="object"&&ao)||function(){return this}()||Function("return this")()});var oe=f((N0,pd)=>{"use strict";pd.exports=function(a){try{return!!a()}catch(e){return!0}}});var gi=f((F0,hd)=>{"use strict";var cI=oe();hd.exports=!cI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var so=f((q0,gd)=>{"use strict";var dI=gi(),bd=Function.prototype,md=bd.apply,fd=bd.call;gd.exports=typeof Reflect=="object"&&Reflect.apply||(dI?fd.bind(md):function(){return fd.apply(md,arguments)})});var re=f((U0,yd)=>{"use strict";var vd=gi(),Sd=Function.prototype,no=Sd.call,pI=vd&&Sd.bind.bind(no,no);yd.exports=vd?pI:function(a){return function(){return no.apply(a,arguments)}}});var Jt=f((H0,Id)=>{"use strict";var Td=re(),hI=Td({}.toString),mI=Td("".slice);Id.exports=function(a){return mI(hI(a),8,-1)}});var oo=f((j0,Ed)=>{"use strict";var fI=Jt(),bI=re();Ed.exports=function(a){if(fI(a)==="Function")return bI(a)}});var X=f((Q0,xd)=>{"use strict";var uo=typeof document=="object"&&document.all;xd.exports=typeof uo=="undefined"&&uo!==void 0?function(a){return typeof a=="function"||a===uo}:function(a){return typeof a=="function"}});var Le=f((G0,Pd)=>{"use strict";var gI=oe();Pd.exports=!gI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var $e=f((W0,wd)=>{"use strict";var vI=gi(),ps=Function.prototype.call;wd.exports=vI?ps.bind(ps):function(){return ps.apply(ps,arguments)}});var lo=f(Ld=>{"use strict";var Ad={}.propertyIsEnumerable,kd=Object.getOwnPropertyDescriptor,SI=kd&&!Ad.call({1:2},1);Ld.f=SI?function(e){var t=kd(this,e);return!!t&&t.enumerable}:Ad});var vi=f((z0,$d)=>{"use strict";$d.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Md=f((K0,Rd)=>{"use strict";var yI=re(),TI=oe(),II=Jt(),co=Object,EI=yI("".split);Rd.exports=TI(function(){return!co("z").propertyIsEnumerable(0)})?function(a){return II(a)==="String"?EI(a,""):co(a)}:co});var Ar=f((X0,Dd)=>{"use strict";Dd.exports=function(a){return a==null}});var kt=f((J0,Cd)=>{"use strict";var xI=Ar(),PI=TypeError;Cd.exports=function(a){if(xI(a))throw new PI("Can't call method on "+a);return a}});var Zt=f((Z0,Vd)=>{"use strict";var wI=Md(),AI=kt();Vd.exports=function(a){return wI(AI(a))}});var Re=f((eV,Bd)=>{"use strict";var kI=X();Bd.exports=function(a){return typeof a=="object"?a!==null:kI(a)}});var kr=f((tV,Od)=>{"use strict";Od.exports={}});var ut=f((rV,Nd)=>{"use strict";var po=kr(),ho=Z(),LI=X(),_d=function(a){return LI(a)?a:void 0};Nd.exports=function(a,e){return arguments.length<2?_d(po[a])||_d(ho[a]):po[a]&&po[a][e]||ho[a]&&ho[a][e]}});var Si=f((iV,Fd)=>{"use strict";var $I=re();Fd.exports=$I({}.isPrototypeOf)});var er=f((aV,Hd)=>{"use strict";var RI=Z(),qd=RI.navigator,Ud=qd&&qd.userAgent;Hd.exports=Ud?String(Ud):""});var fo=f((sV,zd)=>{"use strict";var Yd=Z(),mo=er(),jd=Yd.process,Qd=Yd.Deno,Gd=jd&&jd.versions||Qd&&Qd.version,Wd=Gd&&Gd.v8,je,hs;Wd&&(je=Wd.split("."),hs=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!hs&&mo&&(je=mo.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=mo.match(/Chrome\/(\d+)/),je&&(hs=+je[1])));zd.exports=hs});var bo=f((nV,Xd)=>{"use strict";var Kd=fo(),MI=oe(),DI=Z(),CI=DI.String;Xd.exports=!!Object.getOwnPropertySymbols&&!MI(function(){var a=Symbol("symbol detection");return!CI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Kd&&Kd<41})});var go=f((oV,Jd)=>{"use strict";var VI=bo();Jd.exports=VI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var vo=f((uV,Zd)=>{"use strict";var BI=ut(),OI=X(),_I=Si(),NI=go(),FI=Object;Zd.exports=NI?function(a){return typeof a=="symbol"}:function(a){var e=BI("Symbol");return OI(e)&&_I(e.prototype,FI(a))}});var yi=f((lV,ep)=>{"use strict";var qI=String;ep.exports=function(a){try{return qI(a)}catch(e){return"Object"}}});var Ze=f((cV,tp)=>{"use strict";var UI=X(),HI=yi(),jI=TypeError;tp.exports=function(a){if(UI(a))return a;throw new jI(HI(a)+" is not a function")}});var Ti=f((dV,rp)=>{"use strict";var QI=Ze(),GI=Ar();rp.exports=function(a,e){var t=a[e];return GI(t)?void 0:QI(t)}});var ap=f((pV,ip)=>{"use strict";var So=$e(),yo=X(),To=Re(),WI=TypeError;ip.exports=function(a,e){var t,r;if(e==="string"&&yo(t=a.toString)&&!To(r=So(t,a))||yo(t=a.valueOf)&&!To(r=So(t,a))||e!=="string"&&yo(t=a.toString)&&!To(r=So(t,a)))return r;throw new WI("Can't convert object to primitive value")}});var Qe=f((hV,sp)=>{"use strict";sp.exports=!0});var up=f((mV,op)=>{"use strict";var np=Z(),YI=Object.defineProperty;op.exports=function(a,e){try{YI(np,a,{value:e,configurable:!0,writable:!0})}catch(t){np[a]=e}return e}});var Ii=f((fV,dp)=>{"use strict";var zI=Qe(),KI=Z(),XI=up(),lp="__core-js_shared__",cp=dp.exports=KI[lp]||XI(lp,{});(cp.versions||(cp.versions=[])).push({version:"3.38.0",mode:zI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Io=f((bV,hp)=>{"use strict";var pp=Ii();hp.exports=function(a,e){return pp[a]||(pp[a]=e||{})}});var Lr=f((gV,mp)=>{"use strict";var JI=kt(),ZI=Object;mp.exports=function(a){return ZI(JI(a))}});var Ge=f((vV,fp)=>{"use strict";var eE=re(),tE=Lr(),rE=eE({}.hasOwnProperty);fp.exports=Object.hasOwn||function(e,t){return rE(tE(e),t)}});var Eo=f((SV,bp)=>{"use strict";var iE=re(),aE=0,sE=Math.random(),nE=iE(1 .toString);bp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+nE(++aE+sE,36)}});var ue=f((yV,vp)=>{"use strict";var oE=Z(),uE=Io(),gp=Ge(),lE=Eo(),cE=bo(),dE=go(),$r=oE.Symbol,xo=uE("wks"),pE=dE?$r.for||$r:$r&&$r.withoutSetter||lE;vp.exports=function(a){return gp(xo,a)||(xo[a]=cE&&gp($r,a)?$r[a]:pE("Symbol."+a)),xo[a]}});var Ip=f((TV,Tp)=>{"use strict";var hE=$e(),Sp=Re(),yp=vo(),mE=Ti(),fE=ap(),bE=ue(),gE=TypeError,vE=bE("toPrimitive");Tp.exports=function(a,e){if(!Sp(a)||yp(a))return a;var t=mE(a,vE),r;if(t){if(e===void 0&&(e="default"),r=hE(t,a,e),!Sp(r)||yp(r))return r;throw new gE("Can't convert object to primitive value")}return e===void 0&&(e="number"),fE(a,e)}});var Po=f((IV,Ep)=>{"use strict";var SE=Ip(),yE=vo();Ep.exports=function(a){var e=SE(a,"string");return yE(e)?e:e+""}});var ms=f((EV,Pp)=>{"use strict";var TE=Z(),xp=Re(),wo=TE.document,IE=xp(wo)&&xp(wo.createElement);Pp.exports=function(a){return IE?wo.createElement(a):{}}});var Ao=f((xV,wp)=>{"use strict";var EE=Le(),xE=oe(),PE=ms();wp.exports=!EE&&!xE(function(){return Object.defineProperty(PE("div"),"a",{get:function(){return 7}}).a!==7})});var Lp=f(kp=>{"use strict";var wE=Le(),AE=$e(),kE=lo(),LE=vi(),$E=Zt(),RE=Po(),ME=Ge(),DE=Ao(),Ap=Object.getOwnPropertyDescriptor;kp.f=wE?Ap:function(e,t){if(e=$E(e),t=RE(t),DE)try{return Ap(e,t)}catch(r){}if(ME(e,t))return LE(!AE(kE.f,e,t),e[t])}});var ko=f((wV,$p)=>{"use strict";var CE=oe(),VE=X(),BE=/#|\.prototype\./,Ei=function(a,e){var t=_E[OE(a)];return t===FE?!0:t===NE?!1:VE(e)?CE(e):!!e},OE=Ei.normalize=function(a){return String(a).replace(BE,".").toLowerCase()},_E=Ei.data={},NE=Ei.NATIVE="N",FE=Ei.POLYFILL="P";$p.exports=Ei});var Rr=f((AV,Mp)=>{"use strict";var Rp=oo(),qE=Ze(),UE=gi(),HE=Rp(Rp.bind);Mp.exports=function(a,e){return qE(a),e===void 0?a:UE?HE(a,e):function(){return a.apply(e,arguments)}}});var Lo=f((kV,Dp)=>{"use strict";var jE=Le(),QE=oe();Dp.exports=jE&&QE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var et=f((LV,Cp)=>{"use strict";var GE=Re(),WE=String,YE=TypeError;Cp.exports=function(a){if(GE(a))return a;throw new YE(WE(a)+" is not an object")}});var tr=f(Bp=>{"use strict";var zE=Le(),KE=Ao(),XE=Lo(),fs=et(),Vp=Po(),JE=TypeError,$o=Object.defineProperty,ZE=Object.getOwnPropertyDescriptor,Ro="enumerable",Mo="configurable",Do="writable";Bp.f=zE?XE?function(e,t,r){if(fs(e),t=Vp(t),fs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Do in r&&!r[Do]){var i=ZE(e,t);i&&i[Do]&&(e[t]=r.value,r={configurable:Mo in r?r[Mo]:i[Mo],enumerable:Ro in r?r[Ro]:i[Ro],writable:!1})}return $o(e,t,r)}:$o:function(e,t,r){if(fs(e),t=Vp(t),fs(r),KE)try{return $o(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new JE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Mr=f((RV,Op)=>{"use strict";var ex=Le(),tx=tr(),rx=vi();Op.exports=ex?function(a,e,t){return tx.f(a,e,rx(1,t))}:function(a,e,t){return a[e]=t,a}});var te=f((MV,Np)=>{"use strict";var xi=Z(),ix=so(),ax=oo(),sx=X(),nx=Lp().f,ox=ko(),Dr=kr(),ux=Rr(),Cr=Mr(),_p=Ge();Ii();var lx=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 ix(a,this,arguments)};return e.prototype=a.prototype,e};Np.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?xi:i?xi[t]:xi[t]&&xi[t].prototype,o=r?Dr:Dr[t]||Cr(Dr,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=ox(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&_p(n,p),m=o[p],c&&(a.dontCallGetSet?(v=nx(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=ux(h,xi):a.wrap&&c?g=lx(h):s&&sx(h)?g=ax(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Cr(g,"sham",!0),Cr(o,p,g),s&&(d=t+"Prototype",_p(Dr,d)||Cr(Dr,d,{}),Cr(Dr[d],p,h),a.real&&u&&(l||!u[p])&&Cr(u,p,h)))}});var qp=f((DV,Fp)=>{"use strict";var cx=Math.ceil,dx=Math.floor;Fp.exports=Math.trunc||function(e){var t=+e;return(t>0?dx:cx)(t)}});var Pi=f((CV,Up)=>{"use strict";var px=qp();Up.exports=function(a){var e=+a;return e!==e||e===0?0:px(e)}});var jp=f((VV,Hp)=>{"use strict";var hx=Pi(),mx=Math.max,fx=Math.min;Hp.exports=function(a,e){var t=hx(a);return t<0?mx(t+e,0):fx(t,e)}});var Co=f((BV,Qp)=>{"use strict";var bx=Pi(),gx=Math.min;Qp.exports=function(a){var e=bx(a);return e>0?gx(e,9007199254740991):0}});var Vr=f((OV,Gp)=>{"use strict";var vx=Co();Gp.exports=function(a){return vx(a.length)}});var Vo=f((_V,Yp)=>{"use strict";var Sx=Zt(),yx=jp(),Tx=Vr(),Wp=function(a){return function(e,t,r){var i=Sx(e),s=Tx(i);if(s===0)return!a&&-1;var n=yx(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}};Yp.exports={includes:Wp(!0),indexOf:Wp(!1)}});var wi=f((NV,zp)=>{"use strict";zp.exports=function(){}});var Kp=f(()=>{"use strict";var Ix=te(),Ex=Vo().includes,xx=oe(),Px=wi(),wx=xx(function(){return!Array(1).includes()});Ix({target:"Array",proto:!0,forced:wx},{includes:function(e){return Ex(this,e,arguments.length>1?arguments[1]:void 0)}});Px("includes")});var Lt=f((UV,Xp)=>{"use strict";var Ax=ut();Xp.exports=Ax});var Zp=f((HV,Jp)=>{"use strict";Kp();var kx=Lt();Jp.exports=kx("Array","includes")});var th=f((jV,eh)=>{"use strict";var Lx=Zp();eh.exports=Lx});var We=f((QV,rh)=>{"use strict";var $x=th();rh.exports=$x});var vs=f((iB,ch)=>{"use strict";var _x=Io(),Nx=Eo(),lh=_x("keys");ch.exports=function(a){return lh[a]||(lh[a]=Nx(a))}});var ph=f((aB,dh)=>{"use strict";var Fx=oe();dh.exports=!Fx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Ss=f((sB,mh)=>{"use strict";var qx=Ge(),Ux=X(),Hx=Lr(),jx=vs(),Qx=ph(),hh=jx("IE_PROTO"),_o=Object,Gx=_o.prototype;mh.exports=Qx?_o.getPrototypeOf:function(a){var e=Hx(a);if(qx(e,hh))return e[hh];var t=e.constructor;return Ux(t)&&e instanceof t?t.prototype:e instanceof _o?Gx:null}});var ys=f((nB,fh)=>{"use strict";fh.exports={}});var vh=f((oB,gh)=>{"use strict";var Wx=re(),No=Ge(),Yx=Zt(),zx=Vo().indexOf,Kx=ys(),bh=Wx([].push);gh.exports=function(a,e){var t=Yx(a),r=0,i=[],s;for(s in t)!No(Kx,s)&&No(t,s)&&bh(i,s);for(;e.length>r;)No(t,s=e[r++])&&(~zx(i,s)||bh(i,s));return i}});var Fo=f((uB,Sh)=>{"use strict";Sh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var qo=f((lB,yh)=>{"use strict";var Xx=vh(),Jx=Fo();yh.exports=Object.keys||function(e){return Xx(e,Jx)}});var Uo=f((cB,Ph)=>{"use strict";var Ih=Le(),Zx=oe(),Eh=re(),eP=Ss(),tP=qo(),rP=Zt(),iP=lo().f,xh=Eh(iP),aP=Eh([].push),sP=Ih&&Zx(function(){var a=Object.create(null);return a[2]=2,!xh(a,2)}),Th=function(a){return function(e){for(var t=rP(e),r=tP(t),i=sP&&eP(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Ih||(i?u in t:xh(t,u)))&&aP(o,a?[u,t[u]]:t[u]);return o}};Ph.exports={entries:Th(!0),values:Th(!1)}});var wh=f(()=>{"use strict";var nP=te(),oP=Uo().entries;nP({target:"Object",stat:!0},{entries:function(e){return oP(e)}})});var kh=f((hB,Ah)=>{"use strict";wh();var uP=kr();Ah.exports=uP.Object.entries});var $h=f((mB,Lh)=>{"use strict";var lP=kh();Lh.exports=lP});var Br=f((fB,Rh)=>{"use strict";var cP=$h();Rh.exports=cP});var rr=f((bB,Mh)=>{"use strict";Mh.exports={}});var Vh=f((gB,Ch)=>{"use strict";var dP=Z(),pP=X(),Dh=dP.WeakMap;Ch.exports=pP(Dh)&&/native code/.test(String(Dh))});var Go=f((vB,_h)=>{"use strict";var hP=Vh(),Oh=Z(),mP=Re(),fP=Mr(),Ho=Ge(),jo=Ii(),bP=vs(),gP=ys(),Bh="Object already initialized",Qo=Oh.TypeError,vP=Oh.WeakMap,Ts,Ai,Is,SP=function(a){return Is(a)?Ai(a):Ts(a,{})},yP=function(a){return function(e){var t;if(!mP(e)||(t=Ai(e)).type!==a)throw new Qo("Incompatible receiver, "+a+" required");return t}};hP||jo.state?(Ye=jo.state||(jo.state=new vP),Ye.get=Ye.get,Ye.has=Ye.has,Ye.set=Ye.set,Ts=function(a,e){if(Ye.has(a))throw new Qo(Bh);return e.facade=a,Ye.set(a,e),e},Ai=function(a){return Ye.get(a)||{}},Is=function(a){return Ye.has(a)}):(ir=bP("state"),gP[ir]=!0,Ts=function(a,e){if(Ho(a,ir))throw new Qo(Bh);return e.facade=a,fP(a,ir,e),e},Ai=function(a){return Ho(a,ir)?a[ir]:{}},Is=function(a){return Ho(a,ir)});var Ye,ir;_h.exports={set:Ts,get:Ai,has:Is,enforce:SP,getterFor:yP}});var zo=f((SB,Fh)=>{"use strict";var Wo=Le(),TP=Ge(),Nh=Function.prototype,IP=Wo&&Object.getOwnPropertyDescriptor,Yo=TP(Nh,"name"),EP=Yo&&function(){}.name==="something",xP=Yo&&(!Wo||Wo&&IP(Nh,"name").configurable);Fh.exports={EXISTS:Yo,PROPER:EP,CONFIGURABLE:xP}});var Uh=f(qh=>{"use strict";var PP=Le(),wP=Lo(),AP=tr(),kP=et(),LP=Zt(),$P=qo();qh.f=PP&&!wP?Object.defineProperties:function(e,t){kP(e);for(var r=LP(t),i=$P(t),s=i.length,n=0,o;s>n;)AP.f(e,o=i[n++],r[o]);return e}});var Ko=f((TB,Hh)=>{"use strict";var RP=ut();Hh.exports=RP("document","documentElement")});var eu=f((IB,Kh)=>{"use strict";var MP=et(),DP=Uh(),jh=Fo(),CP=ys(),VP=Ko(),BP=ms(),OP=vs(),Qh=">",Gh="<",Jo="prototype",Zo="script",Yh=OP("IE_PROTO"),Xo=function(){},zh=function(a){return Gh+Zo+Qh+a+Gh+"/"+Zo+Qh},Wh=function(a){a.write(zh("")),a.close();var e=a.parentWindow.Object;return a=null,e},_P=function(){var a=BP("iframe"),e="java"+Zo+":",t;return a.style.display="none",VP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(zh("document.F=Object")),t.close(),t.F},Es,xs=function(){try{Es=new ActiveXObject("htmlfile")}catch(e){}xs=typeof document!="undefined"?document.domain&&Es?Wh(Es):_P():Wh(Es);for(var a=jh.length;a--;)delete xs[Jo][jh[a]];return xs()};CP[Yh]=!0;Kh.exports=Object.create||function(e,t){var r;return e!==null?(Xo[Jo]=MP(e),r=new Xo,Xo[Jo]=null,r[Yh]=e):r=xs(),t===void 0?r:DP.f(r,t)}});var Or=f((EB,Xh)=>{"use strict";var NP=Mr();Xh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:NP(a,e,t),a}});var au=f((xB,em)=>{"use strict";var FP=oe(),qP=X(),UP=Re(),HP=eu(),Jh=Ss(),jP=Or(),QP=ue(),GP=Qe(),iu=QP("iterator"),Zh=!1,lt,tu,ru;[].keys&&(ru=[].keys(),"next"in ru?(tu=Jh(Jh(ru)),tu!==Object.prototype&&(lt=tu)):Zh=!0);var WP=!UP(lt)||FP(function(){var a={};return lt[iu].call(a)!==a});WP?lt={}:GP&&(lt=HP(lt));qP(lt[iu])||jP(lt,iu,function(){return this});em.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Zh}});var Ps=f((PB,rm)=>{"use strict";var YP=ue(),zP=YP("toStringTag"),tm={};tm[zP]="z";rm.exports=String(tm)==="[object z]"});var ki=f((wB,im)=>{"use strict";var KP=Ps(),XP=X(),ws=Jt(),JP=ue(),ZP=JP("toStringTag"),ew=Object,tw=ws(function(){return arguments}())==="Arguments",rw=function(a,e){try{return a[e]}catch(t){}};im.exports=KP?ws:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=rw(e=ew(a),ZP))=="string"?t:tw?ws(e):(r=ws(e))==="Object"&&XP(e.callee)?"Arguments":r}});var sm=f((AB,am)=>{"use strict";var iw=Ps(),aw=ki();am.exports=iw?{}.toString:function(){return"[object "+aw(this)+"]"}});var Li=f((kB,om)=>{"use strict";var sw=Ps(),nw=tr().f,ow=Mr(),uw=Ge(),lw=sm(),cw=ue(),nm=cw("toStringTag");om.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(uw(i,nm)||nw(i,nm,{configurable:!0,value:e}),r&&!sw&&ow(i,"toString",lw))}});var lm=f((LB,um)=>{"use strict";var dw=au().IteratorPrototype,pw=eu(),hw=vi(),mw=Li(),fw=rr(),bw=function(){return this};um.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=pw(dw,{next:hw(+!r,t)}),mw(a,i,!1,!0),fw[i]=bw,a}});var dm=f(($B,cm)=>{"use strict";var gw=re(),vw=Ze();cm.exports=function(a,e,t){try{return gw(vw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var hm=f((RB,pm)=>{"use strict";var Sw=Re();pm.exports=function(a){return Sw(a)||a===null}});var fm=f((MB,mm)=>{"use strict";var yw=hm(),Tw=String,Iw=TypeError;mm.exports=function(a){if(yw(a))return a;throw new Iw("Can't set "+Tw(a)+" as a prototype")}});var su=f((DB,bm)=>{"use strict";var Ew=dm(),xw=Re(),Pw=kt(),ww=fm();bm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Ew(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return Pw(i),ww(s),xw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Am=f((CB,wm)=>{"use strict";var Aw=te(),kw=$e(),As=Qe(),xm=zo(),Lw=X(),$w=lm(),gm=Ss(),vm=su(),Rw=Li(),Mw=Mr(),nu=Or(),Dw=ue(),Sm=rr(),Pm=au(),Cw=xm.PROPER,Vw=xm.CONFIGURABLE,ym=Pm.IteratorPrototype,ks=Pm.BUGGY_SAFARI_ITERATORS,$i=Dw("iterator"),Tm="keys",Ri="values",Im="entries",Em=function(){return this};wm.exports=function(a,e,t,r,i,s,n){$w(t,e,r);var o=function(v){if(v===i&&p)return p;if(!ks&&v&&v in c)return c[v];switch(v){case Tm:return function(){return new t(this,v)};case Ri:return function(){return new t(this,v)};case Im: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=!ks&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=gm(h.call(new a)),m!==Object.prototype&&m.next&&(!As&&gm(m)!==ym&&(vm?vm(m,ym):Lw(m[$i])||nu(m,$i,Em)),Rw(m,u,!0,!0),As&&(Sm[u]=Em))),Cw&&i===Ri&&d&&d.name!==Ri&&(!As&&Vw?Mw(c,"name",Ri):(l=!0,p=function(){return kw(d,this)})),i)if(b={values:o(Ri),keys:s?p:o(Tm),entries:o(Im)},n)for(g in b)(ks||l||!(g in c))&&nu(c,g,b[g]);else Aw({target:e,proto:!0,forced:ks||l},b);return(!As||n)&&c[$i]!==p&&nu(c,$i,p,{name:i}),Sm[e]=p,b}});var Lm=f((VB,km)=>{"use strict";km.exports=function(a,e){return{value:a,done:e}}});var uu=f((BB,Cm)=>{"use strict";var Bw=Zt(),ou=wi(),$m=rr(),Mm=Go(),Ow=tr().f,_w=Am(),Ls=Lm(),Nw=Qe(),Fw=Le(),Dm="Array Iterator",qw=Mm.set,Uw=Mm.getterFor(Dm);Cm.exports=_w(Array,"Array",function(a,e){qw(this,{type:Dm,target:Bw(a),index:0,kind:e})},function(){var a=Uw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ls(void 0,!0);switch(a.kind){case"keys":return Ls(t,!1);case"values":return Ls(e[t],!1)}return Ls([t,e[t]],!1)},"values");var Rm=$m.Arguments=$m.Array;ou("keys");ou("values");ou("entries");if(!Nw&&Fw&&Rm.name!=="values")try{Ow(Rm,"name",{value:"values"})}catch(a){}});var Bm=f((OB,Vm)=>{"use strict";var Hw=ue(),jw=rr(),Qw=Hw("iterator"),Gw=Array.prototype;Vm.exports=function(a){return a!==void 0&&(jw.Array===a||Gw[Qw]===a)}});var lu=f((_B,_m)=>{"use strict";var Ww=ki(),Om=Ti(),Yw=Ar(),zw=rr(),Kw=ue(),Xw=Kw("iterator");_m.exports=function(a){if(!Yw(a))return Om(a,Xw)||Om(a,"@@iterator")||zw[Ww(a)]}});var Fm=f((NB,Nm)=>{"use strict";var Jw=$e(),Zw=Ze(),eA=et(),tA=yi(),rA=lu(),iA=TypeError;Nm.exports=function(a,e){var t=arguments.length<2?rA(a):e;if(Zw(t))return eA(Jw(t,a));throw new iA(tA(a)+" is not iterable")}});var Hm=f((FB,Um)=>{"use strict";var aA=$e(),qm=et(),sA=Ti();Um.exports=function(a,e,t){var r,i;qm(a);try{if(r=sA(a,"return"),!r){if(e==="throw")throw t;return t}r=aA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return qm(r),t}});var Rs=f((qB,Wm)=>{"use strict";var nA=Rr(),oA=$e(),uA=et(),lA=yi(),cA=Bm(),dA=Vr(),jm=Si(),pA=Fm(),hA=lu(),Qm=Hm(),mA=TypeError,$s=function(a,e){this.stopped=a,this.result=e},Gm=$s.prototype;Wm.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=nA(e,r),l,c,d,p,h,m,b,g=function(y){return l&&Qm(l,"normal",y),new $s(!0,y)},v=function(y){return i?(uA(y),o?u(y[0],y[1],g):u(y[0],y[1])):o?u(y,g):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(c=hA(a),!c)throw new mA(lA(a)+" is not iterable");if(cA(c)){for(d=0,p=dA(a);p>d;d++)if(h=v(a[d]),h&&jm(Gm,h))return h;return new $s(!1)}l=pA(a,c)}for(m=s?a.next:l.next;!(b=oA(m,l)).done;){try{h=v(b.value)}catch(y){Qm(l,"throw",y)}if(typeof h=="object"&&h&&jm(Gm,h))return h}return new $s(!1)}});var zm=f((UB,Ym)=>{"use strict";var fA=Le(),bA=tr(),gA=vi();Ym.exports=function(a,e,t){fA?bA.f(a,e,gA(0,t)):a[e]=t}});var Km=f(()=>{"use strict";var vA=te(),SA=Rs(),yA=zm();vA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return SA(e,function(r,i){yA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Jm=f((QB,Xm)=>{"use strict";uu();Km();var TA=kr();Xm.exports=TA.Object.fromEntries});var ef=f((GB,Zm)=>{"use strict";Zm.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 rf=f(()=>{"use strict";uu();var IA=ef(),EA=Z(),xA=Li(),tf=rr();for(Ms in IA)xA(EA[Ms],Ms),tf[Ms]=tf.Array;var Ms});var sf=f((zB,af)=>{"use strict";var PA=Jm();rf();af.exports=PA});var cu=f((KB,nf)=>{"use strict";var wA=sf();nf.exports=wA});var of=f(()=>{"use strict"});var du=f((ZB,uf)=>{"use strict";var Mi=Z(),AA=er(),kA=Jt(),Ds=function(a){return AA.slice(0,a.length)===a};uf.exports=function(){return Ds("Bun/")?"BUN":Ds("Cloudflare-Workers")?"CLOUDFLARE":Ds("Deno/")?"DENO":Ds("Node.js/")?"NODE":Mi.Bun&&typeof Bun.version=="string"?"BUN":Mi.Deno&&typeof Deno.version=="object"?"DENO":kA(Mi.process)==="process"?"NODE":Mi.window&&Mi.document?"BROWSER":"REST"}()});var Cs=f((eO,lf)=>{"use strict";var LA=du();lf.exports=LA==="NODE"});var df=f((tO,cf)=>{"use strict";var $A=tr();cf.exports=function(a,e,t){return $A.f(a,e,t)}});var mf=f((rO,hf)=>{"use strict";var RA=ut(),MA=df(),DA=ue(),CA=Le(),pf=DA("species");hf.exports=function(a){var e=RA(a);CA&&e&&!e[pf]&&MA(e,pf,{configurable:!0,get:function(){return this}})}});var bf=f((iO,ff)=>{"use strict";var VA=Si(),BA=TypeError;ff.exports=function(a,e){if(VA(e,a))return a;throw new BA("Incorrect invocation")}});var hu=f((aO,gf)=>{"use strict";var OA=re(),_A=X(),pu=Ii(),NA=OA(Function.toString);_A(pu.inspectSource)||(pu.inspectSource=function(a){return NA(a)});gf.exports=pu.inspectSource});var fu=f((sO,If)=>{"use strict";var FA=re(),qA=oe(),vf=X(),UA=ki(),HA=ut(),jA=hu(),Sf=function(){},yf=HA("Reflect","construct"),mu=/^\s*(?:class|function)\b/,QA=FA(mu.exec),GA=!mu.test(Sf),Di=function(e){if(!vf(e))return!1;try{return yf(Sf,[],e),!0}catch(t){return!1}},Tf=function(e){if(!vf(e))return!1;switch(UA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return GA||!!QA(mu,jA(e))}catch(t){return!0}};Tf.sham=!0;If.exports=!yf||qA(function(){var a;return Di(Di.call)||!Di(Object)||!Di(function(){a=!0})||a})?Tf:Di});var xf=f((nO,Ef)=>{"use strict";var WA=fu(),YA=yi(),zA=TypeError;Ef.exports=function(a){if(WA(a))return a;throw new zA(YA(a)+" is not a constructor")}});var bu=f((oO,wf)=>{"use strict";var Pf=et(),KA=xf(),XA=Ar(),JA=ue(),ZA=JA("species");wf.exports=function(a,e){var t=Pf(a).constructor,r;return t===void 0||XA(r=Pf(t)[ZA])?e:KA(r)}});var kf=f((uO,Af)=>{"use strict";var ek=re();Af.exports=ek([].slice)});var $f=f((lO,Lf)=>{"use strict";var tk=TypeError;Lf.exports=function(a,e){if(a<e)throw new tk("Not enough arguments");return a}});var gu=f((cO,Rf)=>{"use strict";var rk=er();Rf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(rk)});var wu=f((dO,Ff)=>{"use strict";var Me=Z(),ik=so(),ak=Rr(),Mf=X(),sk=Ge(),Nf=oe(),Df=Ko(),nk=kf(),Cf=ms(),ok=$f(),uk=gu(),lk=Cs(),Eu=Me.setImmediate,xu=Me.clearImmediate,ck=Me.process,vu=Me.Dispatch,dk=Me.Function,Vf=Me.MessageChannel,pk=Me.String,Su=0,Ci={},Bf="onreadystatechange",Vi,ar,yu,Tu;Nf(function(){Vi=Me.location});var Pu=function(a){if(sk(Ci,a)){var e=Ci[a];delete Ci[a],e()}},Iu=function(a){return function(){Pu(a)}},Of=function(a){Pu(a.data)},_f=function(a){Me.postMessage(pk(a),Vi.protocol+"//"+Vi.host)};(!Eu||!xu)&&(Eu=function(e){ok(arguments.length,1);var t=Mf(e)?e:dk(e),r=nk(arguments,1);return Ci[++Su]=function(){ik(t,void 0,r)},ar(Su),Su},xu=function(e){delete Ci[e]},lk?ar=function(a){ck.nextTick(Iu(a))}:vu&&vu.now?ar=function(a){vu.now(Iu(a))}:Vf&&!uk?(yu=new Vf,Tu=yu.port2,yu.port1.onmessage=Of,ar=ak(Tu.postMessage,Tu)):Me.addEventListener&&Mf(Me.postMessage)&&!Me.importScripts&&Vi&&Vi.protocol!=="file:"&&!Nf(_f)?(ar=_f,Me.addEventListener("message",Of,!1)):Bf in Cf("script")?ar=function(a){Df.appendChild(Cf("script"))[Bf]=function(){Df.removeChild(this),Pu(a)}}:ar=function(a){setTimeout(Iu(a),0)});Ff.exports={set:Eu,clear:xu}});var Hf=f((pO,Uf)=>{"use strict";var qf=Z(),hk=Le(),mk=Object.getOwnPropertyDescriptor;Uf.exports=function(a){if(!hk)return qf[a];var e=mk(qf,a);return e&&e.value}});var Au=f((hO,Qf)=>{"use strict";var jf=function(){this.head=null,this.tail=null};jf.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}}};Qf.exports=jf});var Wf=f((mO,Gf)=>{"use strict";var fk=er();Gf.exports=/ipad|iphone|ipod/i.test(fk)&&typeof Pebble!="undefined"});var zf=f((fO,Yf)=>{"use strict";var bk=er();Yf.exports=/web0s(?!.*chrome)/i.test(bk)});var rb=f((bO,tb)=>{"use strict";var Nr=Z(),gk=Hf(),Kf=Rr(),ku=wu().set,vk=Au(),Sk=gu(),yk=Wf(),Tk=zf(),Lu=Cs(),Xf=Nr.MutationObserver||Nr.WebKitMutationObserver,Jf=Nr.document,Zf=Nr.process,Vs=Nr.Promise,Mu=gk("queueMicrotask"),_r,$u,Ru,Bs,eb;Mu||(Bi=new vk,Oi=function(){var a,e;for(Lu&&(a=Zf.domain)&&a.exit();e=Bi.get();)try{e()}catch(t){throw Bi.head&&_r(),t}a&&a.enter()},!Sk&&!Lu&&!Tk&&Xf&&Jf?($u=!0,Ru=Jf.createTextNode(""),new Xf(Oi).observe(Ru,{characterData:!0}),_r=function(){Ru.data=$u=!$u}):!yk&&Vs&&Vs.resolve?(Bs=Vs.resolve(void 0),Bs.constructor=Vs,eb=Kf(Bs.then,Bs),_r=function(){eb(Oi)}):Lu?_r=function(){Zf.nextTick(Oi)}:(ku=Kf(ku,Nr),_r=function(){ku(Oi)}),Mu=function(a){Bi.head||_r(),Bi.add(a)});var Bi,Oi;tb.exports=Mu});var ab=f((gO,ib)=>{"use strict";ib.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Os=f((vO,sb)=>{"use strict";sb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var sr=f((SO,nb)=>{"use strict";var Ik=Z();nb.exports=Ik.Promise});var Fr=f((yO,cb)=>{"use strict";var Ek=Z(),_i=sr(),xk=X(),Pk=ko(),wk=hu(),Ak=ue(),ob=du(),kk=Qe(),Du=fo(),ub=_i&&_i.prototype,Lk=Ak("species"),Cu=!1,lb=xk(Ek.PromiseRejectionEvent),$k=Pk("Promise",function(){var a=wk(_i),e=a!==String(_i);if(!e&&Du===66||kk&&!(ub.catch&&ub.finally))return!0;if(!Du||Du<51||!/native code/.test(a)){var t=new _i(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Lk]=r,Cu=t.then(function(){})instanceof r,!Cu)return!0}return!e&&(ob==="BROWSER"||ob==="DENO")&&!lb});cb.exports={CONSTRUCTOR:$k,REJECTION_EVENT:lb,SUBCLASSING:Cu}});var qr=f((TO,pb)=>{"use strict";var db=Ze(),Rk=TypeError,Mk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Rk("Bad Promise constructor");e=r,t=i}),this.resolve=db(e),this.reject=db(t)};pb.exports.f=function(a){return new Mk(a)}});var Rb=f(()=>{"use strict";var Dk=te(),Ck=Qe(),qs=Cs(),$t=Z(),Qr=$e(),hb=Or(),mb=su(),Vk=Li(),Bk=mf(),Ok=Ze(),Fs=X(),_k=Re(),Nk=bf(),Fk=bu(),Sb=wu().set,Nu=rb(),qk=ab(),Uk=Os(),Hk=Au(),yb=Go(),Us=sr(),Fu=Fr(),Tb=qr(),Hs="Promise",Ib=Fu.CONSTRUCTOR,jk=Fu.REJECTION_EVENT,Qk=Fu.SUBCLASSING,Vu=yb.getterFor(Hs),Gk=yb.set,Ur=Us&&Us.prototype,nr=Us,_s=Ur,Eb=$t.TypeError,Bu=$t.document,qu=$t.process,Ou=Tb.f,Wk=Ou,Yk=!!(Bu&&Bu.createEvent&&$t.dispatchEvent),xb="unhandledrejection",zk="rejectionhandled",fb=0,Pb=1,Kk=2,Uu=1,wb=2,Ns,bb,Xk,gb,Ab=function(a){var e;return _k(a)&&Fs(e=a.then)?e:!1},kb=function(a,e){var t=e.value,r=e.state===Pb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===wb&&Zk(e),e.rejection=Uu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Eb("Promise-chain cycle")):(l=Ab(u))?Qr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Lb=function(a,e){a.notified||(a.notified=!0,Nu(function(){for(var t=a.reactions,r;r=t.get();)kb(r,a);a.notified=!1,e&&!a.rejection&&Jk(a)}))},$b=function(a,e,t){var r,i;Yk?(r=Bu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),$t.dispatchEvent(r)):r={promise:e,reason:t},!jk&&(i=$t["on"+a])?i(r):a===xb&&qk("Unhandled promise rejection",t)},Jk=function(a){Qr(Sb,$t,function(){var e=a.facade,t=a.value,r=vb(a),i;if(r&&(i=Uk(function(){qs?qu.emit("unhandledRejection",t,e):$b(xb,e,t)}),a.rejection=qs||vb(a)?wb:Uu,i.error))throw i.value})},vb=function(a){return a.rejection!==Uu&&!a.parent},Zk=function(a){Qr(Sb,$t,function(){var e=a.facade;qs?qu.emit("rejectionHandled",e):$b(zk,e,a.value)})},Hr=function(a,e,t){return function(r){a(e,r,t)}},jr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Kk,Lb(a,!0))},_u=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Eb("Promise can't be resolved itself");var r=Ab(e);r?Nu(function(){var i={done:!1};try{Qr(r,e,Hr(_u,i,a),Hr(jr,i,a))}catch(s){jr(i,s,a)}}):(a.value=e,a.state=Pb,Lb(a,!1))}catch(i){jr({done:!1},i,a)}}};if(Ib&&(nr=function(e){Nk(this,_s),Ok(e),Qr(Ns,this);var t=Vu(this);try{e(Hr(_u,t),Hr(jr,t))}catch(r){jr(t,r)}},_s=nr.prototype,Ns=function(e){Gk(this,{type:Hs,done:!1,notified:!1,parent:!1,reactions:new Hk,rejection:!1,state:fb,value:void 0})},Ns.prototype=hb(_s,"then",function(e,t){var r=Vu(this),i=Ou(Fk(this,nr));return r.parent=!0,i.ok=Fs(e)?e:!0,i.fail=Fs(t)&&t,i.domain=qs?qu.domain:void 0,r.state===fb?r.reactions.add(i):Nu(function(){kb(i,r)}),i.promise}),bb=function(){var a=new Ns,e=Vu(a);this.promise=a,this.resolve=Hr(_u,e),this.reject=Hr(jr,e)},Tb.f=Ou=function(a){return a===nr||a===Xk?new bb(a):Wk(a)},!Ck&&Fs(Us)&&Ur!==Object.prototype)){gb=Ur.then,Qk||hb(Ur,"then",function(e,t){var r=this;return new nr(function(i,s){Qr(gb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Ur.constructor}catch(a){}mb&&mb(Ur,_s)}Dk({global:!0,constructor:!0,wrap:!0,forced:Ib},{Promise:nr});Vk(nr,Hs,!1,!0);Bk(Hs)});var Bb=f((xO,Vb)=>{"use strict";var eL=ue(),Db=eL("iterator"),Cb=!1;try{Mb=0,Hu={next:function(){return{done:!!Mb++}},return:function(){Cb=!0}},Hu[Db]=function(){return this},Array.from(Hu,function(){throw 2})}catch(a){}var Mb,Hu;Vb.exports=function(a,e){try{if(!e&&!Cb)return!1}catch(i){return!1}var t=!1;try{var r={};r[Db]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var ju=f((PO,Ob)=>{"use strict";var tL=sr(),rL=Bb(),iL=Fr().CONSTRUCTOR;Ob.exports=iL||!rL(function(a){tL.all(a).then(void 0,function(){})})});var _b=f(()=>{"use strict";var aL=te(),sL=$e(),nL=Ze(),oL=qr(),uL=Os(),lL=Rs(),cL=ju();aL({target:"Promise",stat:!0,forced:cL},{all:function(e){var t=this,r=oL.f(t),i=r.resolve,s=r.reject,n=uL(function(){var o=nL(t.resolve),u=[],l=0,c=1;lL(e,function(d){var p=l++,h=!1;c++,sL(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 Fb=f(()=>{"use strict";var dL=te(),pL=Qe(),hL=Fr().CONSTRUCTOR,Gu=sr(),mL=ut(),fL=X(),bL=Or(),Nb=Gu&&Gu.prototype;dL({target:"Promise",proto:!0,forced:hL,real:!0},{catch:function(a){return this.then(void 0,a)}});!pL&&fL(Gu)&&(Qu=mL("Promise").prototype.catch,Nb.catch!==Qu&&bL(Nb,"catch",Qu,{unsafe:!0}));var Qu});var qb=f(()=>{"use strict";var gL=te(),vL=$e(),SL=Ze(),yL=qr(),TL=Os(),IL=Rs(),EL=ju();gL({target:"Promise",stat:!0,forced:EL},{race:function(e){var t=this,r=yL.f(t),i=r.reject,s=TL(function(){var n=SL(t.resolve);IL(e,function(o){vL(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Ub=f(()=>{"use strict";var xL=te(),PL=qr(),wL=Fr().CONSTRUCTOR;xL({target:"Promise",stat:!0,forced:wL},{reject:function(e){var t=PL.f(this),r=t.reject;return r(e),t.promise}})});var Wu=f((CO,Hb)=>{"use strict";var AL=et(),kL=Re(),LL=qr();Hb.exports=function(a,e){if(AL(a),kL(e)&&e.constructor===a)return e;var t=LL.f(a),r=t.resolve;return r(e),t.promise}});var Gb=f(()=>{"use strict";var $L=te(),RL=ut(),jb=Qe(),ML=sr(),Qb=Fr().CONSTRUCTOR,DL=Wu(),CL=RL("Promise"),VL=jb&&!Qb;$L({target:"Promise",stat:!0,forced:jb||Qb},{resolve:function(e){return DL(VL&&this===CL?ML:this,e)}})});var Wb=f(()=>{"use strict";Rb();_b();Fb();qb();Ub();Gb()});var Xb=f(()=>{"use strict";var BL=te(),OL=Qe(),js=sr(),_L=oe(),zb=ut(),Kb=X(),NL=bu(),Yb=Wu(),FL=Or(),zu=js&&js.prototype,qL=!!js&&_L(function(){zu.finally.call({then:function(){}},function(){})});BL({target:"Promise",proto:!0,real:!0,forced:qL},{finally:function(a){var e=NL(this,zb("Promise")),t=Kb(a);return this.then(t?function(r){return Yb(e,a()).then(function(){return r})}:a,t?function(r){return Yb(e,a()).then(function(){throw r})}:a)}});!OL&&Kb(js)&&(Yu=zb("Promise").prototype.finally,zu.finally!==Yu&&FL(zu,"finally",Yu,{unsafe:!0}));var Yu});var Zb=f((qO,Jb)=>{"use strict";of();Wb();Xb();var UL=Lt();Jb.exports=UL("Promise","finally")});var tg=f((UO,eg)=>{"use strict";var HL=Zb();eg.exports=HL});var Qs=f((HO,rg)=>{"use strict";var jL=tg();rg.exports=jL});var fg=f(()=>{"use strict";var a$=te(),s$=Uo().values;a$({target:"Object",stat:!0},{values:function(e){return s$(e)}})});var gg=f((A_,bg)=>{"use strict";fg();var n$=kr();bg.exports=n$.Object.values});var Sg=f((k_,vg)=>{"use strict";var o$=gg();vg.exports=o$});var Wr=f((L_,yg)=>{"use strict";var u$=Sg();yg.exports=u$});var Dg=f(()=>{"use strict";var x$=te(),P$=Lr(),w$=Vr(),A$=Pi(),k$=wi();x$({target:"Array",proto:!0},{at:function(e){var t=P$(this),r=w$(t),i=A$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});k$("at")});var Vg=f((iN,Cg)=>{"use strict";Dg();var L$=Lt();Cg.exports=L$("Array","at")});var Og=f((aN,Bg)=>{"use strict";var $$=Vg();Bg.exports=$$});var Vt=f((sN,_g)=>{"use strict";var R$=Og();_g.exports=R$});var vl=f((UF,Sv)=>{"use strict";var mR=Jt();Sv.exports=Array.isArray||function(e){return mR(e)==="Array"}});var Tv=f((HF,yv)=>{"use strict";var fR=TypeError,bR=9007199254740991;yv.exports=function(a){if(a>bR)throw fR("Maximum allowed index exceeded");return a}});var xv=f((jF,Ev)=>{"use strict";var gR=vl(),vR=Vr(),SR=Tv(),yR=Rr(),Iv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?yR(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&gR(d)?(p=vR(d),u=Iv(a,e,d,p,u,s-1)-1):(SR(u+1),a[u]=d),u++),l++;return u};Ev.exports=Iv});var kv=f((QF,Av)=>{"use strict";var Pv=vl(),TR=fu(),IR=Re(),ER=ue(),xR=ER("species"),wv=Array;Av.exports=function(a){var e;return Pv(a)&&(e=a.constructor,TR(e)&&(e===wv||Pv(e.prototype))?e=void 0:IR(e)&&(e=e[xR],e===null&&(e=void 0))),e===void 0?wv:e}});var $v=f((GF,Lv)=>{"use strict";var PR=kv();Lv.exports=function(a,e){return new(PR(a))(e===0?0:e)}});var Rv=f(()=>{"use strict";var wR=te(),AR=xv(),kR=Ze(),LR=Lr(),$R=Vr(),RR=$v();wR({target:"Array",proto:!0},{flatMap:function(e){var t=LR(this),r=$R(t),i;return kR(e),i=RR(t,0),i.length=AR(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Mv=f(()=>{"use strict";var MR=wi();MR("flatMap")});var Cv=f((XF,Dv)=>{"use strict";Rv();Mv();var DR=Lt();Dv.exports=DR("Array","flatMap")});var Bv=f((JF,Vv)=>{"use strict";var CR=Cv();Vv.exports=CR});var Sl=f((ZF,Ov)=>{"use strict";var VR=Bv();Ov.exports=VR});var ea=f((lq,iS)=>{"use strict";var HR=ki(),jR=String;iS.exports=function(a){if(HR(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return jR(a)}});var Tl=f((cq,aS)=>{"use strict";aS.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 oS=f((dq,nS)=>{"use strict";var QR=re(),GR=kt(),WR=ea(),El=Tl(),sS=QR("".replace),YR=RegExp("^["+El+"]+"),zR=RegExp("(^|[^"+El+"])["+El+"]+$"),Il=function(a){return function(e){var t=WR(GR(e));return a&1&&(t=sS(t,YR,"")),a&2&&(t=sS(t,zR,"$1")),t}};nS.exports={start:Il(1),end:Il(2),trim:Il(3)}});var dS=f((pq,cS)=>{"use strict";var KR=zo().PROPER,XR=oe(),uS=Tl(),lS="\u200B\x85\u180E";cS.exports=function(a){return XR(function(){return!!uS[a]()||lS[a]()!==lS||KR&&uS[a].name!==a})}});var xl=f((hq,pS)=>{"use strict";var JR=oS().start,ZR=dS();pS.exports=ZR("trimStart")?function(){return JR(this)}:"".trimStart});var mS=f(()=>{"use strict";var eM=te(),hS=xl();eM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==hS},{trimLeft:hS})});var bS=f(()=>{"use strict";mS();var tM=te(),fS=xl();tM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==fS},{trimStart:fS})});var vS=f((vq,gS)=>{"use strict";bS();var rM=Lt();gS.exports=rM("String","trimLeft")});var yS=f((Sq,SS)=>{"use strict";var iM=vS();SS.exports=iM});var IS=f((yq,TS)=>{"use strict";var aM=yS();TS.exports=aM});var _S=f(()=>{"use strict"});var NS=f(()=>{"use strict"});var qS=f((Z1,FS)=>{"use strict";var AM=Re(),kM=Jt(),LM=ue(),$M=LM("match");FS.exports=function(a){var e;return AM(a)&&((e=a[$M])!==void 0?!!e:kM(a)==="RegExp")}});var HS=f((eH,US)=>{"use strict";var RM=et();US.exports=function(){var a=RM(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 GS=f((tH,QS)=>{"use strict";var MM=$e(),DM=Ge(),CM=Si(),VM=HS(),jS=RegExp.prototype;QS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in jS)&&!DM(a,"flags")&&CM(jS,a)?MM(VM,a):e}});var YS=f((rH,WS)=>{"use strict";var Dl=re(),BM=Lr(),OM=Math.floor,Rl=Dl("".charAt),_M=Dl("".replace),Ml=Dl("".slice),NM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,FM=/\$([$&'`]|\d{1,2})/g;WS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=FM;return i!==void 0&&(i=BM(i),u=NM),_M(s,u,function(l,c){var d;switch(Rl(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=OM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Rl(c,1):r[h-1]+Rl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var XS=f(()=>{"use strict";var qM=te(),UM=$e(),Vl=re(),zS=kt(),HM=X(),jM=Ar(),QM=qS(),ei=ea(),GM=Ti(),WM=GS(),YM=YS(),zM=ue(),KM=Qe(),XM=zM("replace"),JM=TypeError,Cl=Vl("".indexOf),ZM=Vl("".replace),KS=Vl("".slice),eD=Math.max;qM({target:"String",proto:!0},{replaceAll:function(e,t){var r=zS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!jM(e)){if(i=QM(e),i&&(s=ei(zS(WM(e))),!~Cl(s,"g")))throw new JM("`.replaceAll` does not allow non-global regexes");if(n=GM(e,XM),n)return UM(n,e,r,t);if(KM&&i)return ZM(ei(r),e,t)}for(o=ei(r),u=ei(e),l=HM(t),l||(t=ei(t)),c=u.length,d=eD(1,c),p=Cl(o,u);p!==-1;)h=l?ei(t(u,p,o)):YM(u,o,p,[],void 0,t),b+=KS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Cl(o,u,p+d);return m<o.length&&(b+=KS(o,m)),b}})});var ZS=f((sH,JS)=>{"use strict";_S();NS();XS();var tD=Lt();JS.exports=tD("String","replaceAll")});var ty=f((nH,ey)=>{"use strict";var rD=ZS();ey.exports=rD});var iy=f((oH,ry)=>{"use strict";var iD=ty();ry.exports=iD});var sy=f((uH,ay)=>{"use strict";var aD=Pi(),sD=ea(),nD=kt(),oD=RangeError;ay.exports=function(e){var t=sD(nD(this)),r="",i=aD(e);if(i<0||i===1/0)throw new oD("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var cy=f((lH,ly)=>{"use strict";var uy=re(),uD=Co(),ny=ea(),lD=sy(),cD=kt(),dD=uy(lD),pD=uy("".slice),hD=Math.ceil,oy=function(a){return function(e,t,r){var i=ny(cD(e)),s=uD(t),n=i.length,o=r===void 0?" ":ny(r),u,l;return s<=n||o===""?i:(u=s-n,l=dD(o,hD(u/o.length)),l.length>u&&(l=pD(l,0,u)),a?i+l:l+i)}};ly.exports={start:oy(!1),end:oy(!0)}});var py=f((cH,dy)=>{"use strict";var mD=er();dy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(mD)});var hy=f(()=>{"use strict";var fD=te(),bD=cy().start,gD=py();fD({target:"String",proto:!0,forced:gD},{padStart:function(e){return bD(this,e,arguments.length>1?arguments[1]:void 0)}})});var fy=f((hH,my)=>{"use strict";hy();var vD=Lt();my.exports=vD("String","padStart")});var gy=f((mH,by)=>{"use strict";var SD=fy();by.exports=SD});var Sy=f((fH,vy)=>{"use strict";var yD=gy();vy.exports=yD});var cd="2.0.128-dev.6c63bff4.0";var ke=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ke||{}),At=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(At||{});var cs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(cs||{}),ro=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ro||{});var io=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(io||{}),ds=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(ds||{});var KT=C(We(),1);import{assertNever as uh,assertNonNullable as Rx,isNonNullable as bs,ValueSubject as Bo,Subject as Mx,Subscription as Dx,merge as Cx,observableFrom as Vx,fromEvent as ah,map as sh,tap as nh,filterChanged as Bx,isNullable as Oo,ErrorCategory as oh}from"@vkontakte/videoplayer-shared/es2018";var ih=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 gs=class{constructor(e){this.connection$=new Bo(void 0);this.castState$=new Bo("NOT_AVAILABLE");this.errorEvent$=new Mx;this.realCastState$=new Bo("NOT_AVAILABLE");this.subscription=new Dx;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=bs((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||ih("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:oh.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(){bs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Oo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Oo(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(ah(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 uh(i.sessionState)}})).add(Cx(ah(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(nh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),sh(i=>i.castState)),Vx([r.getCastState()])).pipe(Bx(),sh(Ox),nh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=bs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Rx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Oo(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"?bs(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:oh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Ox=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 uh(a)}};var gc=C(We(),1),MT=C(Br(),1),DT=C(cu(),1);var pg=C(Qs(),1);import{assertNever as ig}from"@vkontakte/videoplayer-shared/es2018";var le=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:ig(t)}return a},Gs=(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:ig(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as QL,Subject as Ws,merge as ag}from"@vkontakte/videoplayer-shared/es2018";var R=class{constructor(e){this.transitionStarted$=new Ws;this.transitionEnded$=new Ws;this.transitionUpdated$=new Ws;this.forceChanged$=new Ws;this.stateChangeStarted$=ag(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=ag(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||QL(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 GL}from"@vkontakte/videoplayer-shared/es2018";var sg=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 GL(a)}};import{assertNever as Gr,assertNonNullable as or,debounce as ng,ErrorCategory as og,fromEvent as ur,isNonNullable as ug,map as lg,merge as cg,observableFrom as WL,Subject as YL,Subscription as Ku,timeout as zL,getHighestQuality as KL}from"@vkontakte/videoplayer-shared/es2018";var XL=5,JL=5,ZL=500,dg=7e3,Ni=class{constructor(e){this.subscription=new Ku;this.loadMediaTimeoutSubscription=new Ku;this.videoState=new R("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:Gr(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:Gr(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:Gr(e)}break}default:Gr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(sg(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 Ku;this.subscription.add(e),this.subscription.add(cg(this.videoState.stateChangeStarted$.pipe(lg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(lg(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 YL;e.add(i.pipe(ng(ZL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(ur(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)>XL)&&i.next(o),s=o})),e.add(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(ur(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<JL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(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:Gr(n)}}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=cg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,WL(["init"])).pipe(ng(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"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(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"),x(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"),x(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"&&x(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];or(c);let d=KL(Object.keys(c));or(d);let p=c[d];or(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];or(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];or(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];or(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];or(c),r=le(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:og.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Gr(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 ug(o)&&(n.metadata.title=o),ug(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(zL(dg).subscribe(()=>s(`timeout(${dg})`)))});(0,pg.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:og.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var bl=C(We(),1);import{clearVideoElement as mg}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as e$}from"@vkontakte/videoplayer-shared/es2018";var hg=a=>{try{a.pause(),a.playbackRate=0,e$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as t$,Subscription as r$}from"@vkontakte/videoplayer-shared/es2018";var Xu=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)}},Ju=window.WeakMap?new WeakMap:new Xu,Zu=window.WeakMap?new WeakMap:new Map,i$=(a,e=20)=>{let t=0;return t$(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Se=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?mg(r):(r=document.createElement("video"),a.appendChild(r)),Ju.set(r,i);let s=new r$;return s.add(i$(r,e)),Zu.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},ye=a=>{let e=Zu.get(a);e==null||e.unsubscribe(),Zu.delete(a);let t=Ju.get(a);Ju.delete(a),t?mg(a):hg(a)};var tl=C(Wr(),1);import{assertNonNullable as Fi,isNonNullable as rt,isNullable as d$,fromEvent as Yr,merge as Tg,observableFrom as Ig,filterChanged as Eg,map as qi,Subject as xg,Subscription as p$,ValueSubject as h$,ErrorCategory as m$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as el,isNullable as l$,Subscription as c$}from"@vkontakte/videoplayer-shared/es2018";var Ys=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=l$(i),l=new c$;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},tt=(a,e,t)=>Ys(e,()=>a.loop,r=>{el(r)&&(a.loop=r)},{onError:t}),Te=(a,e,t,r)=>Ys(e,()=>({muted:a.muted,volume:a.volume}),i=>{el(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}),Be=(a,e,t,r)=>Ys(e,()=>a.playbackRate,i=>{el(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Rt=Ys;var f$=a=>["__",a.language,a.label].join("|"),b$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},rl=class a{constructor(e){this.available$=new xg;this.current$=new h$(void 0);this.error$=new xg;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:m$.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(Rt(t.internalTextTracks,()=>(0,tl.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(qi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Rt(t.externalTextTracks,()=>(0,tl.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(qi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Rt(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(Rt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Fi(this.video);let{textTracks:e}=this.video;this.subscription.add(Yr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Tg(Yr(e,"addtrack"),Yr(e,"removetrack"),Ig(["init"])).pipe(qi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Eg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Tg(Yr(e,"change"),Ig(["init"])).pipe(qi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),qi(r=>r&&this.htmlTextTrackToITextTrack(r).id),Eg()).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(Yr(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(Yr(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;rt(t.align)&&(i.align=t.align),rt(t.position)&&(i.position=t.position),rt(t.size)&&(i.size=t.size),rt(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Fi(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:f$(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){Fi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(d$(e)||!b$(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){Fi(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){Fi(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)}},Oe=rl;var lr=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 Pg=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},il=a=>{let e=Pg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},wg=a=>{let e=Pg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as _e,map as Mt,merge as kg,filterChanged as v$,isNonNullable as Lg,Subject as S$,filter as $g,mapTo as Rg,combine as y$,once as T$,ErrorCategory as I$,ValueSubject as Mg,clientChecker as E$}from"@vkontakte/videoplayer-shared/es2018";var g$=3,Ag=(a,e,t=g$)=>{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 Ie=a=>{let e=S=>_e(a,S).pipe(Rg(void 0)),r=kg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>_e(a,S))).pipe(Mt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),v$()),i=kg(_e(a,"progress"),_e(a,"timeupdate")).pipe(Mt(()=>Ag(a.buffered,a.currentTime))),s=E$.isSafari?y$({play:e("play").pipe(T$()),playing:e("playing")}).pipe(Rg(void 0)):e("playing"),n=_e(a,"volumechange").pipe(Mt(()=>({muted:a.muted,volume:a.volume}))),o=_e(a,"ratechange").pipe(Mt(()=>a.playbackRate)),u=_e(a,"error").pipe($g(()=>!!(a.error||a.played.length)),Mt(()=>{var E;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:I$.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=_e(a,"timeupdate").pipe(Mt(()=>a.currentTime)),c=new S$,d=.3,p;l.subscribe(S=>{a.loop&&Lg(p)&&Lg(S)&&p>=a.duration-d&&S<=d&&c.next(p),p=S});let h=e("pause").pipe($g(()=>!a.error&&p!==a.duration)),m=_e(a,"enterpictureinpicture"),b=_e(a,"leavepictureinpicture"),g=new Mg(wg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Mg(il(a));return _e(a,"fullscreenchange").pipe(Mt(()=>il(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$:_e(a,"durationchange").pipe(Mt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as Dt}from"@vkontakte/videoplayer-shared/es2018";var Ct=a=>{switch(a){case"mobile":return Dt.Q_144P;case"lowest":return Dt.Q_240P;case"low":return Dt.Q_360P;case"sd":case"medium":return Dt.Q_480P;case"hd":case"high":return Dt.Q_720P;case"fullhd":case"full":return Dt.Q_1080P;case"quadhd":case"quad":return Dt.Q_1440P;case"ultrahd":case"ultra":return Dt.Q_2160P}};var Bt=C(Vt(),1),Yg=C(We(),1),Xs=C(Br(),1);import{isNonNullable as De,isNullable as jg,now as zg,isHigher as Qg,isHigherOrEqual as ol,isInvariantQuality as Gg,isLowerOrEqual as ul,videoSizeToQuality as C$,assertNotEmptyArray as Kg,assertNonNullable as V$}from"@vkontakte/videoplayer-shared/es2018";var al=!1,dt={},Ng=a=>{al=a},Fg=()=>{dt={}},qg=a=>{a(dt)},Ui=(a,e)=>{var t;al&&(dt.meta=(t=dt.meta)!=null?t:{},dt.meta[a]=e)},fe=class{constructor(e){this.name=e}next(e){var r,i;if(!al)return;dt.series=(r=dt.series)!=null?r:{};let t=(i=dt.series[this.name])!=null?i:[];t.push([Date.now(),e]),dt.series[this.name]=t}};import{isHigher as M$,isHigherOrEqual as dN,isLower as Ug,isLowerOrEqual as pN,isNonNullable as zs,isNullable as D$,videoHeightToQuality as Ks}from"@vkontakte/videoplayer-shared/es2018";function sl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function nl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&sl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Hi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return D$(a)||zs(a.min)&&zs(a.max)&&Ug(a.max,a.min)||zs(a.min)&&e&&M$(a.min,e)||zs(a.max)&&t&&Ug(a.max,t)}function Hg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Hi({limits:{max:a!=null&&a.max?Ks(a.max):void 0,min:a!=null&&a.min?Ks(a.min):void 0},highestAvailableQuality:e?Ks(e):void 0,lowestAvailableQuality:t?Ks(t):void 0})}var B$=new fe("best_bitrate"),Xg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ll=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),ji=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=zg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Jg='Assertion "ABR Tracks is empty array" failed',Js=(a,e,t,r)=>{var u;let i=[...e].sort(ll(1)),s=[...t].sort(ll(1)),n=s.filter(l=>De(l.bitrate)&&De(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Bt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Bt.default)(s,-1);return o&&(0,Yg.default)(n,o)?o:n.length?(0,Bt.default)(n,-1):(0,Bt.default)(s,0)},Wg=a=>"quality"in a,Zg=(a,e,t,r)=>{var n;let i=De((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&De(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&zg()-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=Wg(o)?"video":"audio",l=Wg(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var VT=Object.create;var Wc=Object.defineProperty;var _T=Object.getOwnPropertyDescriptor;var OT=Object.getOwnPropertyNames;var BT=Object.getPrototypeOf,NT=Object.prototype.hasOwnProperty;var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var FT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of OT(e))!NT.call(a,i)&&i!==t&&Wc(a,i,{get:()=>e[i],enumerable:!(r=_T(e,i))||r.enumerable});return a};var C=(a,e,t)=>(t=a!=null?VT(BT(a)):{},FT(e||!a||!a.__esModule?Wc(t,"default",{value:a,enumerable:!0}):t,a));var te=f((Kn,zc)=>{"use strict";var pi=function(a){return a&&a.Math===Math&&a};zc.exports=pi(typeof globalThis=="object"&&globalThis)||pi(typeof window=="object"&&window)||pi(typeof self=="object"&&self)||pi(typeof global=="object"&&global)||pi(typeof Kn=="object"&&Kn)||function(){return this}()||Function("return this")()});var ce=f((p0,Kc)=>{"use strict";Kc.exports=function(a){try{return!!a()}catch(e){return!0}}});var hi=f((h0,Xc)=>{"use strict";var qT=ce();Xc.exports=!qT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Xn=f((m0,td)=>{"use strict";var UT=hi(),ed=Function.prototype,Jc=ed.apply,Zc=ed.call;td.exports=typeof Reflect=="object"&&Reflect.apply||(UT?Zc.bind(Jc):function(){return Zc.apply(Jc,arguments)})});var se=f((f0,ad)=>{"use strict";var rd=hi(),id=Function.prototype,Jn=id.call,HT=rd&&id.bind.bind(Jn,Jn);ad.exports=rd?HT:function(a){return function(){return Jn.apply(a,arguments)}}});var Kt=f((b0,nd)=>{"use strict";var sd=se(),jT=sd({}.toString),QT=sd("".slice);nd.exports=function(a){return QT(jT(a),8,-1)}});var Zn=f((g0,od)=>{"use strict";var GT=Kt(),WT=se();od.exports=function(a){if(GT(a)==="Function")return WT(a)}});var Z=f((v0,ud)=>{"use strict";var eo=typeof document=="object"&&document.all;ud.exports=typeof eo=="undefined"&&eo!==void 0?function(a){return typeof a=="function"||a===eo}:function(a){return typeof a=="function"}});var Le=f((S0,ld)=>{"use strict";var YT=ce();ld.exports=!YT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Re=f((y0,cd)=>{"use strict";var zT=hi(),ls=Function.prototype.call;cd.exports=zT?ls.bind(ls):function(){return ls.apply(ls,arguments)}});var to=f(hd=>{"use strict";var dd={}.propertyIsEnumerable,pd=Object.getOwnPropertyDescriptor,KT=pd&&!dd.call({1:2},1);hd.f=KT?function(e){var t=pd(this,e);return!!t&&t.enumerable}:dd});var mi=f((I0,md)=>{"use strict";md.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var bd=f((E0,fd)=>{"use strict";var XT=se(),JT=ce(),ZT=Kt(),ro=Object,eI=XT("".split);fd.exports=JT(function(){return!ro("z").propertyIsEnumerable(0)})?function(a){return ZT(a)==="String"?eI(a,""):ro(a)}:ro});var wr=f((x0,gd)=>{"use strict";gd.exports=function(a){return a==null}});var wt=f((P0,vd)=>{"use strict";var tI=wr(),rI=TypeError;vd.exports=function(a){if(tI(a))throw new rI("Can't call method on "+a);return a}});var Xt=f((w0,Sd)=>{"use strict";var iI=bd(),aI=wt();Sd.exports=function(a){return iI(aI(a))}});var $e=f((k0,yd)=>{"use strict";var sI=Z();yd.exports=function(a){return typeof a=="object"?a!==null:sI(a)}});var kr=f((A0,Td)=>{"use strict";Td.exports={}});var ut=f((L0,Ed)=>{"use strict";var io=kr(),ao=te(),nI=Z(),Id=function(a){return nI(a)?a:void 0};Ed.exports=function(a,e){return arguments.length<2?Id(io[a])||Id(ao[a]):io[a]&&io[a][e]||ao[a]&&ao[a][e]}});var fi=f((R0,xd)=>{"use strict";var oI=se();xd.exports=oI({}.isPrototypeOf)});var Jt=f(($0,kd)=>{"use strict";var uI=te(),Pd=uI.navigator,wd=Pd&&Pd.userAgent;kd.exports=wd?String(wd):""});var no=f((M0,Cd)=>{"use strict";var Md=te(),so=Jt(),Ad=Md.process,Ld=Md.Deno,Rd=Ad&&Ad.versions||Ld&&Ld.version,$d=Rd&&Rd.v8,je,cs;$d&&(je=$d.split("."),cs=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!cs&&so&&(je=so.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=so.match(/Chrome\/(\d+)/),je&&(cs=+je[1])));Cd.exports=cs});var oo=f((C0,Vd)=>{"use strict";var Dd=no(),lI=ce(),cI=te(),dI=cI.String;Vd.exports=!!Object.getOwnPropertySymbols&&!lI(function(){var a=Symbol("symbol detection");return!dI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Dd&&Dd<41})});var uo=f((D0,_d)=>{"use strict";var pI=oo();_d.exports=pI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var lo=f((V0,Od)=>{"use strict";var hI=ut(),mI=Z(),fI=fi(),bI=uo(),gI=Object;Od.exports=bI?function(a){return typeof a=="symbol"}:function(a){var e=hI("Symbol");return mI(e)&&fI(e.prototype,gI(a))}});var bi=f((_0,Bd)=>{"use strict";var vI=String;Bd.exports=function(a){try{return vI(a)}catch(e){return"Object"}}});var Ze=f((O0,Nd)=>{"use strict";var SI=Z(),yI=bi(),TI=TypeError;Nd.exports=function(a){if(SI(a))return a;throw new TI(yI(a)+" is not a function")}});var gi=f((B0,Fd)=>{"use strict";var II=Ze(),EI=wr();Fd.exports=function(a,e){var t=a[e];return EI(t)?void 0:II(t)}});var Ud=f((N0,qd)=>{"use strict";var co=Re(),po=Z(),ho=$e(),xI=TypeError;qd.exports=function(a,e){var t,r;if(e==="string"&&po(t=a.toString)&&!ho(r=co(t,a))||po(t=a.valueOf)&&!ho(r=co(t,a))||e!=="string"&&po(t=a.toString)&&!ho(r=co(t,a)))return r;throw new xI("Can't convert object to primitive value")}});var Qe=f((F0,Hd)=>{"use strict";Hd.exports=!0});var Gd=f((q0,Qd)=>{"use strict";var jd=te(),PI=Object.defineProperty;Qd.exports=function(a,e){try{PI(jd,a,{value:e,configurable:!0,writable:!0})}catch(t){jd[a]=e}return e}});var vi=f((U0,zd)=>{"use strict";var wI=Qe(),kI=te(),AI=Gd(),Wd="__core-js_shared__",Yd=zd.exports=kI[Wd]||AI(Wd,{});(Yd.versions||(Yd.versions=[])).push({version:"3.38.0",mode:wI?"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 mo=f((H0,Xd)=>{"use strict";var Kd=vi();Xd.exports=function(a,e){return Kd[a]||(Kd[a]=e||{})}});var Ar=f((j0,Jd)=>{"use strict";var LI=wt(),RI=Object;Jd.exports=function(a){return RI(LI(a))}});var Ge=f((Q0,Zd)=>{"use strict";var $I=se(),MI=Ar(),CI=$I({}.hasOwnProperty);Zd.exports=Object.hasOwn||function(e,t){return CI(MI(e),t)}});var fo=f((G0,ep)=>{"use strict";var DI=se(),VI=0,_I=Math.random(),OI=DI(1 .toString);ep.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+OI(++VI+_I,36)}});var de=f((W0,rp)=>{"use strict";var BI=te(),NI=mo(),tp=Ge(),FI=fo(),qI=oo(),UI=uo(),Lr=BI.Symbol,bo=NI("wks"),HI=UI?Lr.for||Lr:Lr&&Lr.withoutSetter||FI;rp.exports=function(a){return tp(bo,a)||(bo[a]=qI&&tp(Lr,a)?Lr[a]:HI("Symbol."+a)),bo[a]}});var np=f((Y0,sp)=>{"use strict";var jI=Re(),ip=$e(),ap=lo(),QI=gi(),GI=Ud(),WI=de(),YI=TypeError,zI=WI("toPrimitive");sp.exports=function(a,e){if(!ip(a)||ap(a))return a;var t=QI(a,zI),r;if(t){if(e===void 0&&(e="default"),r=jI(t,a,e),!ip(r)||ap(r))return r;throw new YI("Can't convert object to primitive value")}return e===void 0&&(e="number"),GI(a,e)}});var go=f((z0,op)=>{"use strict";var KI=np(),XI=lo();op.exports=function(a){var e=KI(a,"string");return XI(e)?e:e+""}});var ds=f((K0,lp)=>{"use strict";var JI=te(),up=$e(),vo=JI.document,ZI=up(vo)&&up(vo.createElement);lp.exports=function(a){return ZI?vo.createElement(a):{}}});var So=f((X0,cp)=>{"use strict";var eE=Le(),tE=ce(),rE=ds();cp.exports=!eE&&!tE(function(){return Object.defineProperty(rE("div"),"a",{get:function(){return 7}}).a!==7})});var hp=f(pp=>{"use strict";var iE=Le(),aE=Re(),sE=to(),nE=mi(),oE=Xt(),uE=go(),lE=Ge(),cE=So(),dp=Object.getOwnPropertyDescriptor;pp.f=iE?dp:function(e,t){if(e=oE(e),t=uE(t),cE)try{return dp(e,t)}catch(r){}if(lE(e,t))return nE(!aE(sE.f,e,t),e[t])}});var yo=f((Z0,mp)=>{"use strict";var dE=ce(),pE=Z(),hE=/#|\.prototype\./,Si=function(a,e){var t=fE[mE(a)];return t===gE?!0:t===bE?!1:pE(e)?dE(e):!!e},mE=Si.normalize=function(a){return String(a).replace(hE,".").toLowerCase()},fE=Si.data={},bE=Si.NATIVE="N",gE=Si.POLYFILL="P";mp.exports=Si});var Rr=f((eV,bp)=>{"use strict";var fp=Zn(),vE=Ze(),SE=hi(),yE=fp(fp.bind);bp.exports=function(a,e){return vE(a),e===void 0?a:SE?yE(a,e):function(){return a.apply(e,arguments)}}});var To=f((tV,gp)=>{"use strict";var TE=Le(),IE=ce();gp.exports=TE&&IE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var et=f((rV,vp)=>{"use strict";var EE=$e(),xE=String,PE=TypeError;vp.exports=function(a){if(EE(a))return a;throw new PE(xE(a)+" is not an object")}});var Zt=f(yp=>{"use strict";var wE=Le(),kE=So(),AE=To(),ps=et(),Sp=go(),LE=TypeError,Io=Object.defineProperty,RE=Object.getOwnPropertyDescriptor,Eo="enumerable",xo="configurable",Po="writable";yp.f=wE?AE?function(e,t,r){if(ps(e),t=Sp(t),ps(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Po in r&&!r[Po]){var i=RE(e,t);i&&i[Po]&&(e[t]=r.value,r={configurable:xo in r?r[xo]:i[xo],enumerable:Eo in r?r[Eo]:i[Eo],writable:!1})}return Io(e,t,r)}:Io:function(e,t,r){if(ps(e),t=Sp(t),ps(r),kE)try{return Io(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new LE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var $r=f((aV,Tp)=>{"use strict";var $E=Le(),ME=Zt(),CE=mi();Tp.exports=$E?function(a,e,t){return ME.f(a,e,CE(1,t))}:function(a,e,t){return a[e]=t,a}});var ae=f((sV,Ep)=>{"use strict";var yi=te(),DE=Xn(),VE=Zn(),_E=Z(),OE=hp().f,BE=yo(),Mr=kr(),NE=Rr(),Cr=$r(),Ip=Ge();vi();var FE=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 DE(a,this,arguments)};return e.prototype=a.prototype,e};Ep.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?yi:i?yi[t]:yi[t]&&yi[t].prototype,o=r?Mr:Mr[t]||Cr(Mr,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=BE(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Ip(n,p),m=o[p],c&&(a.dontCallGetSet?(v=OE(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=NE(h,yi):a.wrap&&c?g=FE(h):s&&_E(h)?g=VE(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Cr(g,"sham",!0),Cr(o,p,g),s&&(d=t+"Prototype",Ip(Mr,d)||Cr(Mr,d,{}),Cr(Mr[d],p,h),a.real&&u&&(l||!u[p])&&Cr(u,p,h)))}});var Pp=f((nV,xp)=>{"use strict";var qE=Math.ceil,UE=Math.floor;xp.exports=Math.trunc||function(e){var t=+e;return(t>0?UE:qE)(t)}});var Ti=f((oV,wp)=>{"use strict";var HE=Pp();wp.exports=function(a){var e=+a;return e!==e||e===0?0:HE(e)}});var Ap=f((uV,kp)=>{"use strict";var jE=Ti(),QE=Math.max,GE=Math.min;kp.exports=function(a,e){var t=jE(a);return t<0?QE(t+e,0):GE(t,e)}});var wo=f((lV,Lp)=>{"use strict";var WE=Ti(),YE=Math.min;Lp.exports=function(a){var e=WE(a);return e>0?YE(e,9007199254740991):0}});var Dr=f((cV,Rp)=>{"use strict";var zE=wo();Rp.exports=function(a){return zE(a.length)}});var ko=f((dV,Mp)=>{"use strict";var KE=Xt(),XE=Ap(),JE=Dr(),$p=function(a){return function(e,t,r){var i=KE(e),s=JE(i);if(s===0)return!a&&-1;var n=XE(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}};Mp.exports={includes:$p(!0),indexOf:$p(!1)}});var Ii=f((pV,Cp)=>{"use strict";Cp.exports=function(){}});var Dp=f(()=>{"use strict";var ZE=ae(),ex=ko().includes,tx=ce(),rx=Ii(),ix=tx(function(){return!Array(1).includes()});ZE({target:"Array",proto:!0,forced:ix},{includes:function(e){return ex(this,e,arguments.length>1?arguments[1]:void 0)}});rx("includes")});var kt=f((fV,Vp)=>{"use strict";var ax=ut();Vp.exports=ax});var Op=f((bV,_p)=>{"use strict";Dp();var sx=kt();_p.exports=sx("Array","includes")});var Np=f((gV,Bp)=>{"use strict";var nx=Op();Bp.exports=nx});var _e=f((vV,Fp)=>{"use strict";var ox=Np();Fp.exports=ox});var fs=f((RV,Yp)=>{"use strict";var fx=mo(),bx=fo(),Wp=fx("keys");Yp.exports=function(a){return Wp[a]||(Wp[a]=bx(a))}});var Kp=f(($V,zp)=>{"use strict";var gx=ce();zp.exports=!gx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var bs=f((MV,Jp)=>{"use strict";var vx=Ge(),Sx=Z(),yx=Ar(),Tx=fs(),Ix=Kp(),Xp=Tx("IE_PROTO"),Ro=Object,Ex=Ro.prototype;Jp.exports=Ix?Ro.getPrototypeOf:function(a){var e=yx(a);if(vx(e,Xp))return e[Xp];var t=e.constructor;return Sx(t)&&e instanceof t?t.prototype:e instanceof Ro?Ex:null}});var gs=f((CV,Zp)=>{"use strict";Zp.exports={}});var rh=f((DV,th)=>{"use strict";var xx=se(),$o=Ge(),Px=Xt(),wx=ko().indexOf,kx=gs(),eh=xx([].push);th.exports=function(a,e){var t=Px(a),r=0,i=[],s;for(s in t)!$o(kx,s)&&$o(t,s)&&eh(i,s);for(;e.length>r;)$o(t,s=e[r++])&&(~wx(i,s)||eh(i,s));return i}});var Mo=f((VV,ih)=>{"use strict";ih.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Co=f((_V,ah)=>{"use strict";var Ax=rh(),Lx=Mo();ah.exports=Object.keys||function(e){return Ax(e,Lx)}});var Do=f((OV,lh)=>{"use strict";var nh=Le(),Rx=ce(),oh=se(),$x=bs(),Mx=Co(),Cx=Xt(),Dx=to().f,uh=oh(Dx),Vx=oh([].push),_x=nh&&Rx(function(){var a=Object.create(null);return a[2]=2,!uh(a,2)}),sh=function(a){return function(e){for(var t=Cx(e),r=Mx(t),i=_x&&$x(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!nh||(i?u in t:uh(t,u)))&&Vx(o,a?[u,t[u]]:t[u]);return o}};lh.exports={entries:sh(!0),values:sh(!1)}});var ch=f(()=>{"use strict";var Ox=ae(),Bx=Do().entries;Ox({target:"Object",stat:!0},{entries:function(e){return Bx(e)}})});var ph=f((FV,dh)=>{"use strict";ch();var Nx=kr();dh.exports=Nx.Object.entries});var mh=f((qV,hh)=>{"use strict";var Fx=ph();hh.exports=Fx});var Vr=f((UV,fh)=>{"use strict";var qx=mh();fh.exports=qx});var er=f((HV,bh)=>{"use strict";bh.exports={}});var Sh=f((jV,vh)=>{"use strict";var Ux=te(),Hx=Z(),gh=Ux.WeakMap;vh.exports=Hx(gh)&&/native code/.test(String(gh))});var Bo=f((QV,Ih)=>{"use strict";var jx=Sh(),Th=te(),Qx=$e(),Gx=$r(),Vo=Ge(),_o=vi(),Wx=fs(),Yx=gs(),yh="Object already initialized",Oo=Th.TypeError,zx=Th.WeakMap,vs,Ei,Ss,Kx=function(a){return Ss(a)?Ei(a):vs(a,{})},Xx=function(a){return function(e){var t;if(!Qx(e)||(t=Ei(e)).type!==a)throw new Oo("Incompatible receiver, "+a+" required");return t}};jx||_o.state?(We=_o.state||(_o.state=new zx),We.get=We.get,We.has=We.has,We.set=We.set,vs=function(a,e){if(We.has(a))throw new Oo(yh);return e.facade=a,We.set(a,e),e},Ei=function(a){return We.get(a)||{}},Ss=function(a){return We.has(a)}):(tr=Wx("state"),Yx[tr]=!0,vs=function(a,e){if(Vo(a,tr))throw new Oo(yh);return e.facade=a,Gx(a,tr,e),e},Ei=function(a){return Vo(a,tr)?a[tr]:{}},Ss=function(a){return Vo(a,tr)});var We,tr;Ih.exports={set:vs,get:Ei,has:Ss,enforce:Kx,getterFor:Xx}});var qo=f((GV,xh)=>{"use strict";var No=Le(),Jx=Ge(),Eh=Function.prototype,Zx=No&&Object.getOwnPropertyDescriptor,Fo=Jx(Eh,"name"),eP=Fo&&function(){}.name==="something",tP=Fo&&(!No||No&&Zx(Eh,"name").configurable);xh.exports={EXISTS:Fo,PROPER:eP,CONFIGURABLE:tP}});var wh=f(Ph=>{"use strict";var rP=Le(),iP=To(),aP=Zt(),sP=et(),nP=Xt(),oP=Co();Ph.f=rP&&!iP?Object.defineProperties:function(e,t){sP(e);for(var r=nP(t),i=oP(t),s=i.length,n=0,o;s>n;)aP.f(e,o=i[n++],r[o]);return e}});var Uo=f((YV,kh)=>{"use strict";var uP=ut();kh.exports=uP("document","documentElement")});var Go=f((zV,Dh)=>{"use strict";var lP=et(),cP=wh(),Ah=Mo(),dP=gs(),pP=Uo(),hP=ds(),mP=fs(),Lh=">",Rh="<",jo="prototype",Qo="script",Mh=mP("IE_PROTO"),Ho=function(){},Ch=function(a){return Rh+Qo+Lh+a+Rh+"/"+Qo+Lh},$h=function(a){a.write(Ch("")),a.close();var e=a.parentWindow.Object;return a=null,e},fP=function(){var a=hP("iframe"),e="java"+Qo+":",t;return a.style.display="none",pP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Ch("document.F=Object")),t.close(),t.F},ys,Ts=function(){try{ys=new ActiveXObject("htmlfile")}catch(e){}Ts=typeof document!="undefined"?document.domain&&ys?$h(ys):fP():$h(ys);for(var a=Ah.length;a--;)delete Ts[jo][Ah[a]];return Ts()};dP[Mh]=!0;Dh.exports=Object.create||function(e,t){var r;return e!==null?(Ho[jo]=lP(e),r=new Ho,Ho[jo]=null,r[Mh]=e):r=Ts(),t===void 0?r:cP.f(r,t)}});var _r=f((KV,Vh)=>{"use strict";var bP=$r();Vh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:bP(a,e,t),a}});var Ko=f((XV,Bh)=>{"use strict";var gP=ce(),vP=Z(),SP=$e(),yP=Go(),_h=bs(),TP=_r(),IP=de(),EP=Qe(),zo=IP("iterator"),Oh=!1,lt,Wo,Yo;[].keys&&(Yo=[].keys(),"next"in Yo?(Wo=_h(_h(Yo)),Wo!==Object.prototype&&(lt=Wo)):Oh=!0);var xP=!SP(lt)||gP(function(){var a={};return lt[zo].call(a)!==a});xP?lt={}:EP&&(lt=yP(lt));vP(lt[zo])||TP(lt,zo,function(){return this});Bh.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Oh}});var Is=f((JV,Fh)=>{"use strict";var PP=de(),wP=PP("toStringTag"),Nh={};Nh[wP]="z";Fh.exports=String(Nh)==="[object z]"});var xi=f((ZV,qh)=>{"use strict";var kP=Is(),AP=Z(),Es=Kt(),LP=de(),RP=LP("toStringTag"),$P=Object,MP=Es(function(){return arguments}())==="Arguments",CP=function(a,e){try{return a[e]}catch(t){}};qh.exports=kP?Es:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=CP(e=$P(a),RP))=="string"?t:MP?Es(e):(r=Es(e))==="Object"&&AP(e.callee)?"Arguments":r}});var Hh=f((e_,Uh)=>{"use strict";var DP=Is(),VP=xi();Uh.exports=DP?{}.toString:function(){return"[object "+VP(this)+"]"}});var Pi=f((t_,Qh)=>{"use strict";var _P=Is(),OP=Zt().f,BP=$r(),NP=Ge(),FP=Hh(),qP=de(),jh=qP("toStringTag");Qh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(NP(i,jh)||OP(i,jh,{configurable:!0,value:e}),r&&!_P&&BP(i,"toString",FP))}});var Wh=f((r_,Gh)=>{"use strict";var UP=Ko().IteratorPrototype,HP=Go(),jP=mi(),QP=Pi(),GP=er(),WP=function(){return this};Gh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=HP(UP,{next:jP(+!r,t)}),QP(a,i,!1,!0),GP[i]=WP,a}});var zh=f((i_,Yh)=>{"use strict";var YP=se(),zP=Ze();Yh.exports=function(a,e,t){try{return YP(zP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Xh=f((a_,Kh)=>{"use strict";var KP=$e();Kh.exports=function(a){return KP(a)||a===null}});var Zh=f((s_,Jh)=>{"use strict";var XP=Xh(),JP=String,ZP=TypeError;Jh.exports=function(a){if(XP(a))return a;throw new ZP("Can't set "+JP(a)+" as a prototype")}});var Xo=f((n_,em)=>{"use strict";var ew=zh(),tw=$e(),rw=wt(),iw=Zh();em.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=ew(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return rw(i),iw(s),tw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var dm=f((o_,cm)=>{"use strict";var aw=ae(),sw=Re(),xs=Qe(),um=qo(),nw=Z(),ow=Wh(),tm=bs(),rm=Xo(),uw=Pi(),lw=$r(),Jo=_r(),cw=de(),im=er(),lm=Ko(),dw=um.PROPER,pw=um.CONFIGURABLE,am=lm.IteratorPrototype,Ps=lm.BUGGY_SAFARI_ITERATORS,wi=cw("iterator"),sm="keys",ki="values",nm="entries",om=function(){return this};cm.exports=function(a,e,t,r,i,s,n){ow(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ps&&v&&v in c)return c[v];switch(v){case sm:return function(){return new t(this,v)};case ki:return function(){return new t(this,v)};case nm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[wi]||c["@@iterator"]||i&&c[i],p=!Ps&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=tm(h.call(new a)),m!==Object.prototype&&m.next&&(!xs&&tm(m)!==am&&(rm?rm(m,am):nw(m[wi])||Jo(m,wi,om)),uw(m,u,!0,!0),xs&&(im[u]=om))),dw&&i===ki&&d&&d.name!==ki&&(!xs&&pw?lw(c,"name",ki):(l=!0,p=function(){return sw(d,this)})),i)if(b={values:o(ki),keys:s?p:o(sm),entries:o(nm)},n)for(g in b)(Ps||l||!(g in c))&&Jo(c,g,b[g]);else aw({target:e,proto:!0,forced:Ps||l},b);return(!xs||n)&&c[wi]!==p&&Jo(c,wi,p,{name:i}),im[e]=p,b}});var hm=f((u_,pm)=>{"use strict";pm.exports=function(a,e){return{value:a,done:e}}});var eu=f((l_,vm)=>{"use strict";var hw=Xt(),Zo=Ii(),mm=er(),bm=Bo(),mw=Zt().f,fw=dm(),ws=hm(),bw=Qe(),gw=Le(),gm="Array Iterator",vw=bm.set,Sw=bm.getterFor(gm);vm.exports=fw(Array,"Array",function(a,e){vw(this,{type:gm,target:hw(a),index:0,kind:e})},function(){var a=Sw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ws(void 0,!0);switch(a.kind){case"keys":return ws(t,!1);case"values":return ws(e[t],!1)}return ws([t,e[t]],!1)},"values");var fm=mm.Arguments=mm.Array;Zo("keys");Zo("values");Zo("entries");if(!bw&&gw&&fm.name!=="values")try{mw(fm,"name",{value:"values"})}catch(a){}});var ym=f((c_,Sm)=>{"use strict";var yw=de(),Tw=er(),Iw=yw("iterator"),Ew=Array.prototype;Sm.exports=function(a){return a!==void 0&&(Tw.Array===a||Ew[Iw]===a)}});var tu=f((d_,Im)=>{"use strict";var xw=xi(),Tm=gi(),Pw=wr(),ww=er(),kw=de(),Aw=kw("iterator");Im.exports=function(a){if(!Pw(a))return Tm(a,Aw)||Tm(a,"@@iterator")||ww[xw(a)]}});var xm=f((p_,Em)=>{"use strict";var Lw=Re(),Rw=Ze(),$w=et(),Mw=bi(),Cw=tu(),Dw=TypeError;Em.exports=function(a,e){var t=arguments.length<2?Cw(a):e;if(Rw(t))return $w(Lw(t,a));throw new Dw(Mw(a)+" is not iterable")}});var km=f((h_,wm)=>{"use strict";var Vw=Re(),Pm=et(),_w=gi();wm.exports=function(a,e,t){var r,i;Pm(a);try{if(r=_w(a,"return"),!r){if(e==="throw")throw t;return t}r=Vw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Pm(r),t}});var As=f((m_,$m)=>{"use strict";var Ow=Rr(),Bw=Re(),Nw=et(),Fw=bi(),qw=ym(),Uw=Dr(),Am=fi(),Hw=xm(),jw=tu(),Lm=km(),Qw=TypeError,ks=function(a,e){this.stopped=a,this.result=e},Rm=ks.prototype;$m.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=Ow(e,r),l,c,d,p,h,m,b,g=function(y){return l&&Lm(l,"normal",y),new ks(!0,y)},v=function(y){return i?(Nw(y),o?u(y[0],y[1],g):u(y[0],y[1])):o?u(y,g):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(c=jw(a),!c)throw new Qw(Fw(a)+" is not iterable");if(qw(c)){for(d=0,p=Uw(a);p>d;d++)if(h=v(a[d]),h&&Am(Rm,h))return h;return new ks(!1)}l=Hw(a,c)}for(m=s?a.next:l.next;!(b=Bw(m,l)).done;){try{h=v(b.value)}catch(y){Lm(l,"throw",y)}if(typeof h=="object"&&h&&Am(Rm,h))return h}return new ks(!1)}});var Cm=f((f_,Mm)=>{"use strict";var Gw=Le(),Ww=Zt(),Yw=mi();Mm.exports=function(a,e,t){Gw?Ww.f(a,e,Yw(0,t)):a[e]=t}});var Dm=f(()=>{"use strict";var zw=ae(),Kw=As(),Xw=Cm();zw({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Kw(e,function(r,i){Xw(t,r,i)},{AS_ENTRIES:!0}),t}})});var _m=f((v_,Vm)=>{"use strict";eu();Dm();var Jw=kr();Vm.exports=Jw.Object.fromEntries});var Bm=f((S_,Om)=>{"use strict";Om.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 Fm=f(()=>{"use strict";eu();var Zw=Bm(),ek=te(),tk=Pi(),Nm=er();for(Ls in Zw)tk(ek[Ls],Ls),Nm[Ls]=Nm.Array;var Ls});var Um=f((I_,qm)=>{"use strict";var rk=_m();Fm();qm.exports=rk});var ru=f((E_,Hm)=>{"use strict";var ik=Um();Hm.exports=ik});var jm=f(()=>{"use strict"});var iu=f((w_,Qm)=>{"use strict";var Ai=te(),ak=Jt(),sk=Kt(),Rs=function(a){return ak.slice(0,a.length)===a};Qm.exports=function(){return Rs("Bun/")?"BUN":Rs("Cloudflare-Workers")?"CLOUDFLARE":Rs("Deno/")?"DENO":Rs("Node.js/")?"NODE":Ai.Bun&&typeof Bun.version=="string"?"BUN":Ai.Deno&&typeof Deno.version=="object"?"DENO":sk(Ai.process)==="process"?"NODE":Ai.window&&Ai.document?"BROWSER":"REST"}()});var $s=f((k_,Gm)=>{"use strict";var nk=iu();Gm.exports=nk==="NODE"});var Ym=f((A_,Wm)=>{"use strict";var ok=Zt();Wm.exports=function(a,e,t){return ok.f(a,e,t)}});var Xm=f((L_,Km)=>{"use strict";var uk=ut(),lk=Ym(),ck=de(),dk=Le(),zm=ck("species");Km.exports=function(a){var e=uk(a);dk&&e&&!e[zm]&&lk(e,zm,{configurable:!0,get:function(){return this}})}});var Zm=f((R_,Jm)=>{"use strict";var pk=fi(),hk=TypeError;Jm.exports=function(a,e){if(pk(e,a))return a;throw new hk("Incorrect invocation")}});var su=f(($_,ef)=>{"use strict";var mk=se(),fk=Z(),au=vi(),bk=mk(Function.toString);fk(au.inspectSource)||(au.inspectSource=function(a){return bk(a)});ef.exports=au.inspectSource});var ou=f((M_,nf)=>{"use strict";var gk=se(),vk=ce(),tf=Z(),Sk=xi(),yk=ut(),Tk=su(),rf=function(){},af=yk("Reflect","construct"),nu=/^\s*(?:class|function)\b/,Ik=gk(nu.exec),Ek=!nu.test(rf),Li=function(e){if(!tf(e))return!1;try{return af(rf,[],e),!0}catch(t){return!1}},sf=function(e){if(!tf(e))return!1;switch(Sk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Ek||!!Ik(nu,Tk(e))}catch(t){return!0}};sf.sham=!0;nf.exports=!af||vk(function(){var a;return Li(Li.call)||!Li(Object)||!Li(function(){a=!0})||a})?sf:Li});var uf=f((C_,of)=>{"use strict";var xk=ou(),Pk=bi(),wk=TypeError;of.exports=function(a){if(xk(a))return a;throw new wk(Pk(a)+" is not a constructor")}});var uu=f((D_,cf)=>{"use strict";var lf=et(),kk=uf(),Ak=wr(),Lk=de(),Rk=Lk("species");cf.exports=function(a,e){var t=lf(a).constructor,r;return t===void 0||Ak(r=lf(t)[Rk])?e:kk(r)}});var pf=f((V_,df)=>{"use strict";var $k=se();df.exports=$k([].slice)});var mf=f((__,hf)=>{"use strict";var Mk=TypeError;hf.exports=function(a,e){if(a<e)throw new Mk("Not enough arguments");return a}});var lu=f((O_,ff)=>{"use strict";var Ck=Jt();ff.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Ck)});var vu=f((B_,xf)=>{"use strict";var Me=te(),Dk=Xn(),Vk=Rr(),bf=Z(),_k=Ge(),Ef=ce(),gf=Uo(),Ok=pf(),vf=ds(),Bk=mf(),Nk=lu(),Fk=$s(),fu=Me.setImmediate,bu=Me.clearImmediate,qk=Me.process,cu=Me.Dispatch,Uk=Me.Function,Sf=Me.MessageChannel,Hk=Me.String,du=0,Ri={},yf="onreadystatechange",$i,rr,pu,hu;Ef(function(){$i=Me.location});var gu=function(a){if(_k(Ri,a)){var e=Ri[a];delete Ri[a],e()}},mu=function(a){return function(){gu(a)}},Tf=function(a){gu(a.data)},If=function(a){Me.postMessage(Hk(a),$i.protocol+"//"+$i.host)};(!fu||!bu)&&(fu=function(e){Bk(arguments.length,1);var t=bf(e)?e:Uk(e),r=Ok(arguments,1);return Ri[++du]=function(){Dk(t,void 0,r)},rr(du),du},bu=function(e){delete Ri[e]},Fk?rr=function(a){qk.nextTick(mu(a))}:cu&&cu.now?rr=function(a){cu.now(mu(a))}:Sf&&!Nk?(pu=new Sf,hu=pu.port2,pu.port1.onmessage=Tf,rr=Vk(hu.postMessage,hu)):Me.addEventListener&&bf(Me.postMessage)&&!Me.importScripts&&$i&&$i.protocol!=="file:"&&!Ef(If)?(rr=If,Me.addEventListener("message",Tf,!1)):yf in vf("script")?rr=function(a){gf.appendChild(vf("script"))[yf]=function(){gf.removeChild(this),gu(a)}}:rr=function(a){setTimeout(mu(a),0)});xf.exports={set:fu,clear:bu}});var kf=f((N_,wf)=>{"use strict";var Pf=te(),jk=Le(),Qk=Object.getOwnPropertyDescriptor;wf.exports=function(a){if(!jk)return Pf[a];var e=Qk(Pf,a);return e&&e.value}});var Su=f((F_,Lf)=>{"use strict";var Af=function(){this.head=null,this.tail=null};Af.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Lf.exports=Af});var $f=f((q_,Rf)=>{"use strict";var Gk=Jt();Rf.exports=/ipad|iphone|ipod/i.test(Gk)&&typeof Pebble!="undefined"});var Cf=f((U_,Mf)=>{"use strict";var Wk=Jt();Mf.exports=/web0s(?!.*chrome)/i.test(Wk)});var Ff=f((H_,Nf)=>{"use strict";var Br=te(),Yk=kf(),Df=Rr(),yu=vu().set,zk=Su(),Kk=lu(),Xk=$f(),Jk=Cf(),Tu=$s(),Vf=Br.MutationObserver||Br.WebKitMutationObserver,_f=Br.document,Of=Br.process,Ms=Br.Promise,xu=Yk("queueMicrotask"),Or,Iu,Eu,Cs,Bf;xu||(Mi=new zk,Ci=function(){var a,e;for(Tu&&(a=Of.domain)&&a.exit();e=Mi.get();)try{e()}catch(t){throw Mi.head&&Or(),t}a&&a.enter()},!Kk&&!Tu&&!Jk&&Vf&&_f?(Iu=!0,Eu=_f.createTextNode(""),new Vf(Ci).observe(Eu,{characterData:!0}),Or=function(){Eu.data=Iu=!Iu}):!Xk&&Ms&&Ms.resolve?(Cs=Ms.resolve(void 0),Cs.constructor=Ms,Bf=Df(Cs.then,Cs),Or=function(){Bf(Ci)}):Tu?Or=function(){Of.nextTick(Ci)}:(yu=Df(yu,Br),Or=function(){yu(Ci)}),xu=function(a){Mi.head||Or(),Mi.add(a)});var Mi,Ci;Nf.exports=xu});var Uf=f((j_,qf)=>{"use strict";qf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ds=f((Q_,Hf)=>{"use strict";Hf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ir=f((G_,jf)=>{"use strict";var Zk=te();jf.exports=Zk.Promise});var Nr=f((W_,Yf)=>{"use strict";var eA=te(),Di=ir(),tA=Z(),rA=yo(),iA=su(),aA=de(),Qf=iu(),sA=Qe(),Pu=no(),Gf=Di&&Di.prototype,nA=aA("species"),wu=!1,Wf=tA(eA.PromiseRejectionEvent),oA=rA("Promise",function(){var a=iA(Di),e=a!==String(Di);if(!e&&Pu===66||sA&&!(Gf.catch&&Gf.finally))return!0;if(!Pu||Pu<51||!/native code/.test(a)){var t=new Di(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[nA]=r,wu=t.then(function(){})instanceof r,!wu)return!0}return!e&&(Qf==="BROWSER"||Qf==="DENO")&&!Wf});Yf.exports={CONSTRUCTOR:oA,REJECTION_EVENT:Wf,SUBCLASSING:wu}});var Fr=f((Y_,Kf)=>{"use strict";var zf=Ze(),uA=TypeError,lA=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new uA("Bad Promise constructor");e=r,t=i}),this.resolve=zf(e),this.reject=zf(t)};Kf.exports.f=function(a){return new lA(a)}});var fb=f(()=>{"use strict";var cA=ae(),dA=Qe(),Bs=$s(),At=te(),jr=Re(),Xf=_r(),Jf=Xo(),pA=Pi(),hA=Xm(),mA=Ze(),Os=Z(),fA=$e(),bA=Zm(),gA=uu(),ib=vu().set,$u=Ff(),vA=Uf(),SA=Ds(),yA=Su(),ab=Bo(),Ns=ir(),Mu=Nr(),sb=Fr(),Fs="Promise",nb=Mu.CONSTRUCTOR,TA=Mu.REJECTION_EVENT,IA=Mu.SUBCLASSING,ku=ab.getterFor(Fs),EA=ab.set,qr=Ns&&Ns.prototype,ar=Ns,Vs=qr,ob=At.TypeError,Au=At.document,Cu=At.process,Lu=sb.f,xA=Lu,PA=!!(Au&&Au.createEvent&&At.dispatchEvent),ub="unhandledrejection",wA="rejectionhandled",Zf=0,lb=1,kA=2,Du=1,cb=2,_s,eb,AA,tb,db=function(a){var e;return fA(a)&&Os(e=a.then)?e:!1},pb=function(a,e){var t=e.value,r=e.state===lb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===cb&&RA(e),e.rejection=Du),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new ob("Promise-chain cycle")):(l=db(u))?jr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},hb=function(a,e){a.notified||(a.notified=!0,$u(function(){for(var t=a.reactions,r;r=t.get();)pb(r,a);a.notified=!1,e&&!a.rejection&&LA(a)}))},mb=function(a,e,t){var r,i;PA?(r=Au.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),At.dispatchEvent(r)):r={promise:e,reason:t},!TA&&(i=At["on"+a])?i(r):a===ub&&vA("Unhandled promise rejection",t)},LA=function(a){jr(ib,At,function(){var e=a.facade,t=a.value,r=rb(a),i;if(r&&(i=SA(function(){Bs?Cu.emit("unhandledRejection",t,e):mb(ub,e,t)}),a.rejection=Bs||rb(a)?cb:Du,i.error))throw i.value})},rb=function(a){return a.rejection!==Du&&!a.parent},RA=function(a){jr(ib,At,function(){var e=a.facade;Bs?Cu.emit("rejectionHandled",e):mb(wA,e,a.value)})},Ur=function(a,e,t){return function(r){a(e,r,t)}},Hr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=kA,hb(a,!0))},Ru=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new ob("Promise can't be resolved itself");var r=db(e);r?$u(function(){var i={done:!1};try{jr(r,e,Ur(Ru,i,a),Ur(Hr,i,a))}catch(s){Hr(i,s,a)}}):(a.value=e,a.state=lb,hb(a,!1))}catch(i){Hr({done:!1},i,a)}}};if(nb&&(ar=function(e){bA(this,Vs),mA(e),jr(_s,this);var t=ku(this);try{e(Ur(Ru,t),Ur(Hr,t))}catch(r){Hr(t,r)}},Vs=ar.prototype,_s=function(e){EA(this,{type:Fs,done:!1,notified:!1,parent:!1,reactions:new yA,rejection:!1,state:Zf,value:void 0})},_s.prototype=Xf(Vs,"then",function(e,t){var r=ku(this),i=Lu(gA(this,ar));return r.parent=!0,i.ok=Os(e)?e:!0,i.fail=Os(t)&&t,i.domain=Bs?Cu.domain:void 0,r.state===Zf?r.reactions.add(i):$u(function(){pb(i,r)}),i.promise}),eb=function(){var a=new _s,e=ku(a);this.promise=a,this.resolve=Ur(Ru,e),this.reject=Ur(Hr,e)},sb.f=Lu=function(a){return a===ar||a===AA?new eb(a):xA(a)},!dA&&Os(Ns)&&qr!==Object.prototype)){tb=qr.then,IA||Xf(qr,"then",function(e,t){var r=this;return new ar(function(i,s){jr(tb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete qr.constructor}catch(a){}Jf&&Jf(qr,Vs)}cA({global:!0,constructor:!0,wrap:!0,forced:nb},{Promise:ar});pA(ar,Fs,!1,!0);hA(Fs)});var yb=f((X_,Sb)=>{"use strict";var $A=de(),gb=$A("iterator"),vb=!1;try{bb=0,Vu={next:function(){return{done:!!bb++}},return:function(){vb=!0}},Vu[gb]=function(){return this},Array.from(Vu,function(){throw 2})}catch(a){}var bb,Vu;Sb.exports=function(a,e){try{if(!e&&!vb)return!1}catch(i){return!1}var t=!1;try{var r={};r[gb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var _u=f((J_,Tb)=>{"use strict";var MA=ir(),CA=yb(),DA=Nr().CONSTRUCTOR;Tb.exports=DA||!CA(function(a){MA.all(a).then(void 0,function(){})})});var Ib=f(()=>{"use strict";var VA=ae(),_A=Re(),OA=Ze(),BA=Fr(),NA=Ds(),FA=As(),qA=_u();VA({target:"Promise",stat:!0,forced:qA},{all:function(e){var t=this,r=BA.f(t),i=r.resolve,s=r.reject,n=NA(function(){var o=OA(t.resolve),u=[],l=0,c=1;FA(e,function(d){var p=l++,h=!1;c++,_A(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 UA=ae(),HA=Qe(),jA=Nr().CONSTRUCTOR,Bu=ir(),QA=ut(),GA=Z(),WA=_r(),Eb=Bu&&Bu.prototype;UA({target:"Promise",proto:!0,forced:jA,real:!0},{catch:function(a){return this.then(void 0,a)}});!HA&&GA(Bu)&&(Ou=QA("Promise").prototype.catch,Eb.catch!==Ou&&WA(Eb,"catch",Ou,{unsafe:!0}));var Ou});var Pb=f(()=>{"use strict";var YA=ae(),zA=Re(),KA=Ze(),XA=Fr(),JA=Ds(),ZA=As(),eL=_u();YA({target:"Promise",stat:!0,forced:eL},{race:function(e){var t=this,r=XA.f(t),i=r.reject,s=JA(function(){var n=KA(t.resolve);ZA(e,function(o){zA(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var wb=f(()=>{"use strict";var tL=ae(),rL=Fr(),iL=Nr().CONSTRUCTOR;tL({target:"Promise",stat:!0,forced:iL},{reject:function(e){var t=rL.f(this),r=t.reject;return r(e),t.promise}})});var Nu=f((oO,kb)=>{"use strict";var aL=et(),sL=$e(),nL=Fr();kb.exports=function(a,e){if(aL(a),sL(e)&&e.constructor===a)return e;var t=nL.f(a),r=t.resolve;return r(e),t.promise}});var Rb=f(()=>{"use strict";var oL=ae(),uL=ut(),Ab=Qe(),lL=ir(),Lb=Nr().CONSTRUCTOR,cL=Nu(),dL=uL("Promise"),pL=Ab&&!Lb;oL({target:"Promise",stat:!0,forced:Ab||Lb},{resolve:function(e){return cL(pL&&this===dL?lL:this,e)}})});var $b=f(()=>{"use strict";fb();Ib();xb();Pb();wb();Rb()});var Vb=f(()=>{"use strict";var hL=ae(),mL=Qe(),qs=ir(),fL=ce(),Cb=ut(),Db=Z(),bL=uu(),Mb=Nu(),gL=_r(),qu=qs&&qs.prototype,vL=!!qs&&fL(function(){qu.finally.call({then:function(){}},function(){})});hL({target:"Promise",proto:!0,real:!0,forced:vL},{finally:function(a){var e=bL(this,Cb("Promise")),t=Db(a);return this.then(t?function(r){return Mb(e,a()).then(function(){return r})}:a,t?function(r){return Mb(e,a()).then(function(){throw r})}:a)}});!mL&&Db(qs)&&(Fu=Cb("Promise").prototype.finally,qu.finally!==Fu&&gL(qu,"finally",Fu,{unsafe:!0}));var Fu});var Ob=f((mO,_b)=>{"use strict";jm();$b();Vb();var SL=kt();_b.exports=SL("Promise","finally")});var Nb=f((fO,Bb)=>{"use strict";var yL=Ob();Bb.exports=yL});var Us=f((bO,Fb)=>{"use strict";var TL=Nb();Fb.exports=TL});var Zb=f(()=>{"use strict";var VL=ae(),_L=Do().values;VL({target:"Object",stat:!0},{values:function(e){return _L(e)}})});var tg=f((eB,eg)=>{"use strict";Zb();var OL=kr();eg.exports=OL.Object.values});var ig=f((tB,rg)=>{"use strict";var BL=tg();rg.exports=BL});var Gr=f((rB,ag)=>{"use strict";var NL=ig();ag.exports=NL});var xg=f(()=>{"use strict";var nR=ae(),oR=Ar(),uR=Dr(),lR=Ti(),cR=Ii();nR({target:"Array",proto:!0},{at:function(e){var t=oR(this),r=uR(t),i=lR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});cR("at")});var wg=f((cN,Pg)=>{"use strict";xg();var dR=kt();Pg.exports=dR("Array","at")});var Ag=f((dN,kg)=>{"use strict";var pR=wg();kg.exports=pR});var Ct=f((pN,Lg)=>{"use strict";var hR=Ag();Lg.exports=hR});var dl=f((XF,cv)=>{"use strict";var KR=Kt();cv.exports=Array.isArray||function(e){return KR(e)==="Array"}});var pv=f((JF,dv)=>{"use strict";var XR=TypeError,JR=9007199254740991;dv.exports=function(a){if(a>JR)throw XR("Maximum allowed index exceeded");return a}});var fv=f((ZF,mv)=>{"use strict";var ZR=dl(),e$=Dr(),t$=pv(),r$=Rr(),hv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?r$(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&ZR(d)?(p=e$(d),u=hv(a,e,d,p,u,s-1)-1):(t$(u+1),a[u]=d),u++),l++;return u};mv.exports=hv});var Sv=f((eq,vv)=>{"use strict";var bv=dl(),i$=ou(),a$=$e(),s$=de(),n$=s$("species"),gv=Array;vv.exports=function(a){var e;return bv(a)&&(e=a.constructor,i$(e)&&(e===gv||bv(e.prototype))?e=void 0:a$(e)&&(e=e[n$],e===null&&(e=void 0))),e===void 0?gv:e}});var Tv=f((tq,yv)=>{"use strict";var o$=Sv();yv.exports=function(a,e){return new(o$(a))(e===0?0:e)}});var Iv=f(()=>{"use strict";var u$=ae(),l$=fv(),c$=Ze(),d$=Ar(),p$=Dr(),h$=Tv();u$({target:"Array",proto:!0},{flatMap:function(e){var t=d$(this),r=p$(t),i;return c$(e),i=h$(t,0),i.length=l$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Ev=f(()=>{"use strict";var m$=Ii();m$("flatMap")});var Pv=f((nq,xv)=>{"use strict";Iv();Ev();var f$=kt();xv.exports=f$("Array","flatMap")});var kv=f((oq,wv)=>{"use strict";var b$=Pv();wv.exports=b$});var pl=f((uq,Av)=>{"use strict";var g$=kv();Av.exports=g$});var Ki=f((lq,Lv)=>{"use strict";var v$=xi(),S$=String;Lv.exports=function(a){if(v$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return S$(a)}});var hl=f((cq,Rv)=>{"use strict";Rv.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 Cv=f((dq,Mv)=>{"use strict";var y$=se(),T$=wt(),I$=Ki(),fl=hl(),$v=y$("".replace),E$=RegExp("^["+fl+"]+"),x$=RegExp("(^|[^"+fl+"])["+fl+"]+$"),ml=function(a){return function(e){var t=I$(T$(e));return a&1&&(t=$v(t,E$,"")),a&2&&(t=$v(t,x$,"$1")),t}};Mv.exports={start:ml(1),end:ml(2),trim:ml(3)}});var Ov=f((pq,_v)=>{"use strict";var P$=qo().PROPER,w$=ce(),Dv=hl(),Vv="\u200B\x85\u180E";_v.exports=function(a){return w$(function(){return!!Dv[a]()||Vv[a]()!==Vv||P$&&Dv[a].name!==a})}});var bl=f((hq,Bv)=>{"use strict";var k$=Cv().start,A$=Ov();Bv.exports=A$("trimStart")?function(){return k$(this)}:"".trimStart});var Fv=f(()=>{"use strict";var L$=ae(),Nv=bl();L$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Nv},{trimLeft:Nv})});var Uv=f(()=>{"use strict";Fv();var R$=ae(),qv=bl();R$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==qv},{trimStart:qv})});var jv=f((vq,Hv)=>{"use strict";Uv();var $$=kt();Hv.exports=$$("String","trimLeft")});var Gv=f((Sq,Qv)=>{"use strict";var M$=jv();Qv.exports=M$});var Yv=f((yq,Wv)=>{"use strict";var C$=Gv();Wv.exports=C$});var cS=f(()=>{"use strict"});var dS=f(()=>{"use strict"});var hS=f((eH,pS)=>{"use strict";var rM=$e(),iM=Kt(),aM=de(),sM=aM("match");pS.exports=function(a){var e;return rM(a)&&((e=a[sM])!==void 0?!!e:iM(a)==="RegExp")}});var fS=f((tH,mS)=>{"use strict";var nM=et();mS.exports=function(){var a=nM(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 vS=f((rH,gS)=>{"use strict";var oM=Re(),uM=Ge(),lM=fi(),cM=fS(),bS=RegExp.prototype;gS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in bS)&&!uM(a,"flags")&&lM(bS,a)?oM(cM,a):e}});var yS=f((iH,SS)=>{"use strict";var xl=se(),dM=Ar(),pM=Math.floor,Il=xl("".charAt),hM=xl("".replace),El=xl("".slice),mM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,fM=/\$([$&'`]|\d{1,2})/g;SS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=fM;return i!==void 0&&(i=dM(i),u=mM),hM(s,u,function(l,c){var d;switch(Il(c,0)){case"$":return"$";case"&":return a;case"`":return El(e,0,t);case"'":return El(e,n);case"<":d=i[El(c,1,-1)];break;default:var 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?Il(c,1):r[h-1]+Il(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var ES=f(()=>{"use strict";var bM=ae(),gM=Re(),wl=se(),TS=wt(),vM=Z(),SM=wr(),yM=hS(),Xr=Ki(),TM=gi(),IM=vS(),EM=yS(),xM=de(),PM=Qe(),wM=xM("replace"),kM=TypeError,Pl=wl("".indexOf),AM=wl("".replace),IS=wl("".slice),LM=Math.max;bM({target:"String",proto:!0},{replaceAll:function(e,t){var r=TS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!SM(e)){if(i=yM(e),i&&(s=Xr(TS(IM(e))),!~Pl(s,"g")))throw new kM("`.replaceAll` does not allow non-global regexes");if(n=TM(e,wM),n)return gM(n,e,r,t);if(PM&&i)return AM(Xr(r),e,t)}for(o=Xr(r),u=Xr(e),l=vM(t),l||(t=Xr(t)),c=u.length,d=LM(1,c),p=Pl(o,u);p!==-1;)h=l?Xr(t(u,p,o)):EM(u,o,p,[],void 0,t),b+=IS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Pl(o,u,p+d);return m<o.length&&(b+=IS(o,m)),b}})});var PS=f((nH,xS)=>{"use strict";cS();dS();ES();var RM=kt();xS.exports=RM("String","replaceAll")});var kS=f((oH,wS)=>{"use strict";var $M=PS();wS.exports=$M});var LS=f((uH,AS)=>{"use strict";var MM=kS();AS.exports=MM});var $S=f((lH,RS)=>{"use strict";var CM=Ti(),DM=Ki(),VM=wt(),_M=RangeError;RS.exports=function(e){var t=DM(VM(this)),r="",i=CM(e);if(i<0||i===1/0)throw new _M("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var _S=f((cH,VS)=>{"use strict";var DS=se(),OM=wo(),MS=Ki(),BM=$S(),NM=wt(),FM=DS(BM),qM=DS("".slice),UM=Math.ceil,CS=function(a){return function(e,t,r){var i=MS(NM(e)),s=OM(t),n=i.length,o=r===void 0?" ":MS(r),u,l;return s<=n||o===""?i:(u=s-n,l=FM(o,UM(u/o.length)),l.length>u&&(l=qM(l,0,u)),a?i+l:l+i)}};VS.exports={start:CS(!1),end:CS(!0)}});var BS=f((dH,OS)=>{"use strict";var HM=Jt();OS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(HM)});var NS=f(()=>{"use strict";var jM=ae(),QM=_S().start,GM=BS();jM({target:"String",proto:!0,forced:GM},{padStart:function(e){return QM(this,e,arguments.length>1?arguments[1]:void 0)}})});var qS=f((mH,FS)=>{"use strict";NS();var WM=kt();FS.exports=WM("String","padStart")});var HS=f((fH,US)=>{"use strict";var YM=qS();US.exports=YM});var QS=f((bH,jS)=>{"use strict";var zM=HS();jS.exports=zM});var Yc="2.0.128-dev.d52ca770.0";var Te=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Te||{}),ot=(S=>(S.MPEG="MPEG",S.DASH="DASH",S.DASH_SEP="DASH_SEP",S.DASH_SEP_VK="DASH_SEP",S.DASH_WEBM="DASH_WEBM",S.DASH_WEBM_AV1="DASH_WEBM_AV1",S.DASH_STREAMS="DASH_STREAMS",S.DASH_WEBM_VK="DASH_WEBM",S.DASH_ONDEMAND="DASH_ONDEMAND",S.DASH_ONDEMAND_VK="DASH_ONDEMAND",S.DASH_LIVE="DASH_LIVE",S.DASH_LIVE_CMAF="DASH_LIVE_CMAF",S.DASH_LIVE_WEBM="DASH_LIVE_WEBM",S.HLS="HLS",S.HLS_ONDEMAND="HLS_ONDEMAND",S.HLS_JS="HLS",S.HLS_LIVE="HLS_LIVE",S.HLS_LIVE_CMAF="HLS_LIVE_CMAF",S.WEB_RTC_LIVE="WEB_RTC_LIVE",S))(ot||{});var os=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(os||{}),Yn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Yn||{});var zn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(zn||{}),us=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(us||{});var kT=C(_e(),1);import{assertNever as Gp,assertNonNullable as ux,isNonNullable as hs,ValueSubject as Ao,Subject as lx,Subscription as cx,merge as dx,observableFrom as px,fromEvent as Up,map as Hp,tap as jp,filterChanged as hx,isNullable as Lo,ErrorCategory as Qp}from"@vkontakte/videoplayer-shared/es2018";var qp=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 ms=class{constructor(e){this.connection$=new Ao(void 0);this.castState$=new Ao("NOT_AVAILABLE");this.errorEvent$=new lx;this.realCastState$=new Ao("NOT_AVAILABLE");this.subscription=new cx;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=hs((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||qp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Qp.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(){hs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Lo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Lo(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(Up(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 Gp(i.sessionState)}})).add(dx(Up(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(jp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Hp(i=>i.castState)),px([r.getCastState()])).pipe(hx(),Hp(mx),jp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=hs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();ux(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Lo(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"?hs(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:Qp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},mx=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 Gp(a)}};var nc=C(_e(),1),uT=C(Vr(),1),lT=C(ru(),1);var Kb=C(Us(),1);import{assertNever as qb}from"@vkontakte/videoplayer-shared/es2018";var pe=(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:qb(t)}return a},Hs=(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:qb(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as IL,Subject as js,merge as Ub}from"@vkontakte/videoplayer-shared/es2018";var D=class{constructor(e){this.transitionStarted$=new js;this.transitionEnded$=new js;this.transitionUpdated$=new js;this.forceChanged$=new js;this.stateChangeStarted$=Ub(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Ub(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||IL(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 EL}from"@vkontakte/videoplayer-shared/es2018";var Hb=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 EL(a)}};import{assertNever as Qr,assertNonNullable as sr,debounce as jb,ErrorCategory as Qb,fromEvent as nr,isNonNullable as Gb,map as Wb,merge as Yb,observableFrom as xL,Subject as PL,Subscription as Uu,timeout as wL,getHighestQuality as kL}from"@vkontakte/videoplayer-shared/es2018";var AL=5,LL=5,RL=500,zb=7e3,Vi=class{constructor(e){this.subscription=new Uu;this.loadMediaTimeoutSubscription=new Uu;this.videoState=new D("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:Qr(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:Qr(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:Qr(e)}break}default:Qr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Hb(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 Uu;this.subscription.add(e),this.subscription.add(Yb(this.videoState.stateChangeStarted$.pipe(Wb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Wb(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 PL;e.add(i.pipe(jb(RL)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(nr(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)>AL)&&i.next(o),s=o})),e.add(nr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(nr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(nr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(nr(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<LL&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(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:Qr(n)}}),t(nr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(nr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Yb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xL(["init"])).pipe(jb(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"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(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"),x(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"),x(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"&&x(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];sr(c);let d=kL(Object.keys(c));sr(d);let p=c[d];sr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];sr(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];sr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];sr(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];sr(c),r=pe(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:Qb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Qr(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 Gb(o)&&(n.metadata.title=o),Gb(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(wL(zb).subscribe(()=>s(`timeout(${zb})`)))});(0,Kb.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:Qb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ll=C(_e(),1);import{clearVideoElement as Jb}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as $L}from"@vkontakte/videoplayer-shared/es2018";var Xb=a=>{try{a.pause(),a.playbackRate=0,$L(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as ML,Subscription as CL}from"@vkontakte/videoplayer-shared/es2018";var Hu=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)}},ju=window.WeakMap?new WeakMap:new Hu,Qu=window.WeakMap?new WeakMap:new Map,DL=(a,e=20)=>{let t=0;return ML(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ie=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let r=a.querySelector("video"),i=!!r;r?Jb(r):(r=document.createElement("video"),a.appendChild(r)),ju.set(r,i);let s=new CL;return s.add(DL(r,e)),Qu.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},Ee=a=>{let e=Qu.get(a);e==null||e.unsubscribe(),Qu.delete(a);let t=ju.get(a);ju.delete(a),t?Jb(a):Xb(a)};var Wu=C(Gr(),1);import{assertNonNullable as _i,isNonNullable as rt,isNullable as UL,fromEvent as Wr,merge as sg,observableFrom as ng,filterChanged as og,map as Oi,Subject as ug,Subscription as HL,ValueSubject as jL,ErrorCategory as QL}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Gu,isNullable as FL,Subscription as qL}from"@vkontakte/videoplayer-shared/es2018";var Qs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=FL(i),l=new qL;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},tt=(a,e,t)=>Qs(e,()=>a.loop,r=>{Gu(r)&&(a.loop=r)},{onError:t}),xe=(a,e,t,r)=>Qs(e,()=>({muted:a.muted,volume:a.volume}),i=>{Gu(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}),Oe=(a,e,t,r)=>Qs(e,()=>a.playbackRate,i=>{Gu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Lt=Qs;var GL=a=>["__",a.language,a.label].join("|"),WL=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Yu=class a{constructor(e){this.available$=new ug;this.current$=new jL(void 0);this.error$=new ug;this.subscription=new HL;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:QL.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(Lt(t.internalTextTracks,()=>(0,Wu.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Oi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Lt(t.externalTextTracks,()=>(0,Wu.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Oi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Lt(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(Lt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){_i(this.video);let{textTracks:e}=this.video;this.subscription.add(Wr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(sg(Wr(e,"addtrack"),Wr(e,"removetrack"),ng(["init"])).pipe(Oi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),og((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(sg(Wr(e,"change"),ng(["init"])).pipe(Oi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Oi(r=>r&&this.htmlTextTrackToITextTrack(r).id),og()).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(Wr(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(Wr(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;rt(t.align)&&(i.align=t.align),rt(t.position)&&(i.position=t.position),rt(t.size)&&(i.size=t.size),rt(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){_i(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:GL(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){_i(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(UL(e)||!WL(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){_i(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){_i(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)}},Be=Yu;var dt=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 lg=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},zu=a=>{let e=lg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},cg=a=>{let e=lg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ne,map as Rt,merge as Sg,filterChanged as tR,isNonNullable as yg,Subject as rR,filter as Tg,mapTo as Ig,combine as iR,once as aR,ErrorCategory as sR,ValueSubject as Eg}from"@vkontakte/videoplayer-shared/es2018";var YL=3,dg=(a,e,t=YL)=>{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 Gs=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 pg=C(_e(),1);var Bi=()=>{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 Ws=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,pg.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=Bi()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e){let t=await 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 Ys=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 Ye=()=>window.ManagedMediaSource||window.MediaSource,zs=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},hg=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},mg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var fg,zL=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:gg}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:bg}})]);fg={DASH_WEBM_AV1:e,DASH_WEBM:t}};zL().catch(a=>{console.error(a)});var KL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',XL='video/mp4; codecs="hev1.1.6.L93.B0"',bg='video/webm; codecs="vp09.00.10.08"',gg='video/webm; codecs="av01.0.00M.08"',JL='audio/mp4; codecs="mp4a.40.2"',ZL='audio/webm; codecs="opus"',Ks=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 fg}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,y,S,E;this._video=document.createElement("video");try{this._protocols={mms:zs(),mse:hg(),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=Ye())==null?void 0:l.isTypeSupported)!=null&&c.call(l,KL)),L=!!((p=(d=Ye())==null?void 0:d.isTypeSupported)!=null&&p.call(d,XL)),A=!!((m=(h=Ye())==null?void 0:h.isTypeSupported)!=null&&m.call(h,JL));this._codecs={h264:I,h265:L,vp9:!!((g=(b=Ye())==null?void 0:b.isTypeSupported)!=null&&g.call(b,bg)),av1:!!((y=(v=Ye())==null?void 0:v.isTypeSupported)!=null&&y.call(v,gg)),aac:A,opus:!!((E=(S=Ye())==null?void 0:S.isTypeSupported)!=null&&E.call(S,ZL)),mpeg:(I||L)&&A},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 vg="audio/mpeg",Xs=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,vg))},this._codecs={mp3:!!((i=(r=Ye())==null?void 0:r.isTypeSupported)!=null&&i.call(r,vg))}}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 eR}from"@vkontakte/videoplayer-shared/es2018";var Ku=class{constructor(){this.isInited$=new eR(!1);this._displayChecker=new Ys,this._deviceChecker=new Ws(this._displayChecker),this._browserChecker=new Gs,this._videoChecker=new Ks(this._deviceChecker,this._browserChecker),this._audioChecker=new Xs,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}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},O=new Ku;var Pe=a=>{let e=S=>Ne(a,S).pipe(Ig(void 0)),r=Sg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>Ne(a,S))).pipe(Rt(S=>S.type==="ended"?a.readyState<2:a.readyState<3),tR()),i=Sg(Ne(a,"progress"),Ne(a,"timeupdate")).pipe(Rt(()=>dg(a.buffered,a.currentTime))),s=O.browser.isSafari?iR({play:e("play").pipe(aR()),playing:e("playing")}).pipe(Ig(void 0)):e("playing"),n=Ne(a,"volumechange").pipe(Rt(()=>({muted:a.muted,volume:a.volume}))),o=Ne(a,"ratechange").pipe(Rt(()=>a.playbackRate)),u=Ne(a,"error").pipe(Tg(()=>!!(a.error||a.played.length)),Rt(()=>{var E;let S=a.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:sR.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=Ne(a,"timeupdate").pipe(Rt(()=>a.currentTime)),c=new rR,d=.3,p;l.subscribe(S=>{a.loop&&yg(p)&&yg(S)&&p>=a.duration-d&&S<=d&&c.next(p),p=S});let h=e("pause").pipe(Tg(()=>!a.error&&p!==a.duration)),m=Ne(a,"enterpictureinpicture"),b=Ne(a,"leavepictureinpicture"),g=new Eg(cg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Eg(zu(a));return Ne(a,"fullscreenchange").pipe(Rt(()=>zu(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$:Ne(a,"durationchange").pipe(Rt(()=>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/es2018";var Mt=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 Dt=C(Ct(),1),Ng=C(_e(),1),en=C(Vr(),1);import{isNonNullable as Ce,isNullable as Vg,now as Fg,isHigher as _g,isHigherOrEqual as el,isInvariantQuality as Og,isLowerOrEqual as tl,videoSizeToQuality as bR,assertNotEmptyArray as qg,assertNonNullable as gR}from"@vkontakte/videoplayer-shared/es2018";var Xu=!1,pt={},Rg=a=>{Xu=a},$g=()=>{pt={}},Mg=a=>{a(pt)},Ni=(a,e)=>{var t;Xu&&(pt.meta=(t=pt.meta)!=null?t:{},pt.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var r,i;if(!Xu)return;pt.series=(r=pt.series)!=null?r:{};let t=(i=pt.series[this.name])!=null?i:[];t.push([Date.now(),e]),pt.series[this.name]=t}};import{isHigher as mR,isHigherOrEqual as vN,isLower as Cg,isLowerOrEqual as SN,isNonNullable as Js,isNullable as fR,videoHeightToQuality as Zs}from"@vkontakte/videoplayer-shared/es2018";function Ju({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Zu({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&Ju({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Fi({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return fR(a)||Js(a.min)&&Js(a.max)&&Cg(a.max,a.min)||Js(a.min)&&e&&mR(a.min,e)||Js(a.max)&&t&&Cg(a.max,t)}function Dg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Fi({limits:{max:a!=null&&a.max?Zs(a.max):void 0,min:a!=null&&a.min?Zs(a.min):void 0},highestAvailableQuality:e?Zs(e):void 0,lowestAvailableQuality:t?Zs(t):void 0})}var vR=new ve("best_bitrate"),Ug=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var rl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),qi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Fg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Hg='Assertion "ABR Tracks is empty array" failed',tn=(a,e,t,r)=>{var u;let i=[...e].sort(rl(1)),s=[...t].sort(rl(1)),n=s.filter(l=>Ce(l.bitrate)&&Ce(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Dt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Dt.default)(s,-1);return o&&(0,Ng.default)(n,o)?o:n.length?(0,Dt.default)(n,-1):(0,Dt.default)(s,0)},Bg=a=>"quality"in a,jg=(a,e,t,r)=>{var n;let i=Ce((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&Ce(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Fg()-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=Bg(o)?"video":"audio",l=Bg(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},SR=(a,e)=>Math.log(e)/Math.log(a),yR=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&O.display.pixelRatio){let i=O.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=SR(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return Zu({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}},Vt=(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 H,k,R,Y,ie,w;qg(a,Hg);let{containerSizeFactor:b,containerSizeLimit:g}=yR({container:e,tuning:r,limits:i}),v=r.considerPlaybackRate&&Ce(o)?o:1,y=a.filter(T=>!Og(T.quality)).sort((T,M)=>_g(T.quality,M.quality)?-1:1),S=(H=(0,Dt.default)(y,-1))==null?void 0:H.quality,E=(k=(0,Dt.default)(y,0))==null?void 0:k.quality,I=Fi({limits:i,lowestAvailableQuality:S,highestAvailableQuality:E}),L=v*Ug(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),A={},_=y.filter(T=>{let M=!0;if(g)if(T.size)M=T.size.width<=g.width&&T.size.height<=g.height;else{let be=g&&bR(g);M=be?tl(T.quality,be):!0}if(!M)return A[T.quality]="FitsContainer",!1;let j=h||t,N=Ce(j)&&isFinite(j)&&Ce(T.bitrate)?j-s>=T.bitrate*L:!0,Ae=Zu({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:i})&&(i==null?void 0:i.min)===T.quality;if(!N&&!Ae)return A[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Ce(r.minBufferToSwitchUp)&&u&&!Og(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&_g(T.quality,u.quality))return A[T.quality]="Buffer",!1;if(!!d&&el(T.quality,d)&&!Ae)return A[T.quality]="DroppedFramesLimit",!1;if(!!p&&el(T.quality,p)&&!Ae)return A[T.quality]="StallsLimit",!1;let le=I||(Vg(i==null?void 0:i.max)||tl(T.quality,i.max))&&(Vg(i==null?void 0:i.min)||el(T.quality,i.min)),fe=Ce(c)&&!c?tl(T.quality,r.backgroundVideoQualityLimit):!0;return!le||!fe?(A[T.quality]="FitsQualityLimits",!1):!0})[0];_&&_.bitrate&&vR.next(_.bitrate);let q=(R=_!=null?_:(0,Dt.default)(y,-1))!=null?R:a[0];return q.quality!==((Y=l==null?void 0:l.last)==null?void 0:Y.quality)&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(T=>{var
|
|
12
|
+
${a.map(T=>{var M,j;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${(M=T.size)==null?void 0:M.width}:${(j=T.size)==null?void 0:j.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,en.default)(r!=null?r:{}).map(([T,M])=>`${T}: ${M}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${b},
|
|
21
|
-
containerSizeLimit: ${(
|
|
21
|
+
containerSizeLimit: ${(ie=g==null?void 0:g.width)!=null?ie:0} x ${(w=g==null?void 0:g.height)!=null?w: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},
|
|
@@ -34,19 +34,19 @@ var aI=Object.create;var ld=Object.defineProperty;var sI=Object.getOwnPropertyDe
|
|
|
34
34
|
minQualityLimit: ${i==null?void 0:i.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,en.default)(A).map(([T,M])=>`${T}: ${M}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${_==null?void 0:_.quality}
|
|
41
|
+
[selected video track] ${q==null?void 0:q.quality}
|
|
42
|
+
`}),jg(r,m,q,l)},Qg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;qg(t,Hg);let c=i.considerPlaybackRate&&Ce(s)?s:1,d=[...t].sort(rl(-1)),p=a.bitrate;gR(p);let h=c*Ug(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,b=tn(a,e,t,i.minVideoAudioRatio),g=l||r;return Ce(g)&&isFinite(g)&&(m=d.find(y=>Ce(y.bitrate)&&Ce(b==null?void 0:b.bitrate)?g-p>=y.bitrate*h&&y.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(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,
|
|
49
|
+
${(0,en.default)(i!=null?i:{}).map(([y,S])=>`${y}: ${S}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
@@ -60,14 +60,14 @@ var aI=Object.create;var ld=Object.defineProperty;var sI=Object.getOwnPropertyDe
|
|
|
60
60
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
61
61
|
|
|
62
62
|
[selected audio track] ${m==null?void 0:m.id}
|
|
63
|
-
`}),m&&Zg(i,u,m,o)};var ie=a=>new URL(a).hostname;import{assertNever as dv,assertNonNullable as pv,combine as sR,debounce as nR,ErrorCategory as hv,filter as mv,filterChanged as oR,isNonNullable as ml,map as an,merge as fv,observableFrom as uR,once as lR,Subscription as cR,ValueSubject as fl,videoQualityToHeight as bv,videoSizeToQuality as dR}from"@vkontakte/videoplayer-shared/es2018";var ov=C(Vt(),1);var rv=C(We(),1),tv=a=>{if(a instanceof DOMException&&(0,rv.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"))},Ee=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!tv(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return tv(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as en,isNullable as q$,assertNonNullable as Wi}from"@vkontakte/videoplayer-shared/es2018";var av=C(Wr(),1);import{isNonNullable as iv,assertNonNullable as Zs,now as N$}from"@vkontakte/videoplayer-shared/es2018";function ae(){return N$()}function cl(a){return ae()-a}function dl(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 sv(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;Zs(c);let A=cl(c),k;if(A<b){k=b-A,setTimeout(g,k);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,D()},v=A=>(s=A,F),y=A=>(d=A,F),S=()=>(h="json",F),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=A=>(p=A,F),D=()=>{c=ae(),n=new i,n.open("get",a);let A=0,k,Q=0,ee=()=>(Zs(c),Math.max(c,Math.max(k||0,Q||0)));if(s&&n.addEventListener("progress",w=>{let T=ae();s.updateChunk&&w.loaded>A&&(s.updateChunk(ee(),w.loaded-A),A=w.loaded,k=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;Zs(n);let w=n.status;if(w>=200&&w<300){let{response:T,responseType:$}=n,q=T==null?void 0:T.byteLength;if(typeof q=="number"&&s){let B=q-A;B&&s.updateChunk&&s.updateChunk(ee(),B)}$==="json"&&(!T||!(0,av.default)(T).length)?E():(d&&d(),e(T))}else E()}),n.addEventListener("error",()=>{E()}),p){let w=()=>{Zs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=ae(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=h,n.send(),F},F={withBitrateReporting:v,withParallel:I,withJSONResponse:S,withRetryCount:A=>(l=A,F),withRetryInterval:(A,k)=>(iv(A)&&(b=A),iv(k)&&(m=k),F),withTimeout:A=>(o=A,F),withFinally:y,send:D,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return F}var Qi=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 nv=C(Wr(),1);var Gi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ae(),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=ae()-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=ae()}_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=ae();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,nv.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 U$}from"@vkontakte/videoplayer-shared/es2018";var tn=1e4,pl=3;var H$=6e4,j$=10,Q$=1,G$=500,Yi=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 U$,this.chunkRateEstimator=new Qi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=dl(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=dl(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||{};!Hg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,ov.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||en(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=()=>{sv(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Gi(pl,tn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let E=s&&(!c||c===this.rep);return E||t("Not running!"),E},p=(E,I,D)=>{u&&u.abort(),u=zr(this.urlResolver.resolve(E,!1),I,D,()=>this._retryCallback()).withTimeout(tn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(pl).withFinally(()=>{u=null}).send()},h=(E,I,D)=>{Wi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,D,()=>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 D=ae()-1e4,L=0;for(let V=0;V<this.bufferStates.length;V++){let _=this.bufferStates[V];E=Math.min(E,_.buf),_.ts<D&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${E} drop=${L} jitter=${this.sourceJitter}`);let j=E-Q$;this.sourceJitter>=0?j-=this.sourceJitter/2:this.sourceJitter-=1,j>3?m(1.15):j>1?m(1.1):j>.3?m(1.05):m(1)}},v=E=>{let I,D=()=>I&&I.start?I.start.length:0,L=w=>I.start[w]/1e3,j=w=>I.dur[w]/1e3,V=w=>I.fragIndex+w,_=(w,T)=>({chunkIdx:V(w),startTS:L(w),dur:j(w),discontinuity:T}),F=()=>{let w=0;if(I&&I.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,$=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,q=T;this.sourceJitter>1&&(q+=this.sourceJitter-1);let B=I.dur.length-1;for(;B>=0&&(q-=I.dur[B],!(q<=0));--B);w=Math.min(B,I.dur.length-1-$),w=Math.max(w,0)}return _(w,!0)},A=w=>{let T=D();if(!(T<=0)){if(en(w)){for(let $=0;$<T;$++)if(L($)>w)return _($)}return F()}},k=w=>{let T=D(),$=w?w.chunkIdx+1:0,q=$-I.fragIndex;if(!(T<=0)){if(!w||q<0||q-T>j$)return t(`Resync: offset=${q} bChunks=${T} chunk=`+JSON.stringify(w)),F();if(!(q>=T))return _($-I.fragIndex,!1)}},Q=(w,T,$)=>{l&&l.abort(),l=zr(this.urlResolver.resolve(w,!0,this.lowLatency),T,$,()=>this._retryCallback()).withTimeout(tn).withRetryCount(pl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,T)=>{Q(E,$=>{if(!d())return;I=$;let q=!!I.lowLatency;q!==this.lowLatency&&b(q);let B=0;for(let Ae=0;Ae<I.dur.length;++Ae)B+=I.dur[Ae];B>0&&(Wi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/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,w(A(T))},()=>this._handleNetworkError())},nextChunk:k}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Wi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:I,logger:D}=this.params,L=v(e.jidxUrl),j,V,_,F,A=0,k,Q,ee,w=()=>{k&&(clearTimeout(k),k=void 0);let U=Math.max(G$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=A+U,pe=ae(),he=Math.min(1e4,ne-pe);A=pe;let St=()=>{l||d()&&L.seek(()=>{d()&&(A=ae(),T(),w())})};he>0?k=window.setTimeout(()=>{this.paused?w():St()},he):St()},T=()=>{let U;for(;U=L.nextChunk(F);)F=U,ui(U);let ne=L.nextChunk(_);if(ne){if(_&&ne.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?w():(y(),this._initPlayerWith(e));return}Ae(ne)}else w()},$=(U,ne)=>{if(!d()||!this.sourceBuffer)return;let pe,he,St,Sr=yt=>{window.setTimeout(()=>{d()&&$(U,ne)},yt)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),Sr(100);else{let yt=ae(),Qt=I.currentTime;!this.paused&&I.buffered.length>1&&Q===Qt&&yt-ee>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),Q!==Qt&&(Q=Qt,ee=yt);let yr=this._getBufferSizeSec();if(yr>30)D(`Buffered ${yr} seconds; delaying appendBuffer`),Sr(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:yr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(li){if(li.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),St=this.sourceBuffer.buffered.length,St!==0&&(pe=this.sourceBuffer.buffered.start(0),he=Qt,he-pe>4&&this.sourceBuffer.remove(pe,he-3)),Sr(1e3);else throw li}}},q=()=>{V&&j&&(D([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(_)]),$(V,function(){V=null,T()}))},B=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),Ae=U=>{d()&&h(B(U),(ne,pe)=>{if(d()){if(pe/=1e3,V=ne,_=U,n=U.startTS,pe){let he=Math.min(10,U.dur/pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}q()}},()=>this._handleNetworkError())},ui=U=>{d()&&(Wi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(U),!1)))},vr=U=>{d()&&(e.cachedHeader=U,$(U,()=>{j=!0,q()}))};s=!0,L.seek(U=>{if(d()){if(A=ae(),!U){w();return}F=U,!q$(E)||U.startTS>E?Ae(U):(_=U,T())}},E),e.cachedHeader?vr(e.cachedHeader):p(e.headerUrl,vr,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),en(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,Wi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return en(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=ae();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&&cl(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=ae();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=zr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(tn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ee(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))},H$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var cv=C(Br(),1);import{debounce as W$,filter as uv,fromEvent as Y$,interval as z$,isHigher as K$,isInvariantQuality as X$,isLower as J$,merge as Z$,Subject as lv,Subscription as eR}from"@vkontakte/videoplayer-shared/es2018";var hl=class{constructor(){this.onDroopedVideoFramesLimit$=new lv;this.subscription=new eR;this.playing=!1;this.tracks=[];this.forceChecker$=new lv;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&&!X$(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&&K$(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(Y$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=z$(this.droppedFramesChecker.checkTime).pipe(uv(()=>this.playing),uv(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(W$(this.droppedFramesChecker.checkTime)),r=Z$(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,cv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>J$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},rn=hl;import{map as tR,Observable as rR}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as iR}from"@vkontakte/videoplayer-shared/es2018";var zi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var aR=(a,e)=>new rR(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||zi()))},{...r,...e});i.observe(a);let s=iR(document,"visibilitychange").pipe(tR(n=>!document.hidden||zi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ne=aR;var pR=["paused","playing","ready"],hR=["paused","playing","ready"],Ki=class{constructor(e){this.subscription=new cR;this.videoState=new R("stopped");this.representations$=new fl([]);this.droppedFramesManager=new rn;this.maxSeekBackTime$=new fl(1/0);this.zeroTime$=new fl(void 0);this.liveOffset=new lr;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:hv.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=Ct(u.name))!=null?r:dR(u.video),d=u.bitrate/1e3,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),ml(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,bl.default)(hR,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,bl.default)(pR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(le(this.params.source.url,u))}return;default:return dv(e)}};this.textTracksManager=new Oe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:hv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};fv(this.videoState.stateChangeStarted$.pipe(an(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(an(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Se(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(ie(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=Ie(this.video);this.subscription.add(this.representations$.pipe(an(i=>i.map(({track:s})=>s)),mv(i=>!!i.length),lR()).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(oR(),an(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(sR({zeroTime:this.zeroTime$.pipe(mv(ml)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(Te(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Be(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(Ne(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&bv(i),min:s&&bv(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 dv(i.to)}},t)).add(fv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,uR(["init"])).pipe(nR(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),ye(this.video)}createLiveDashPlayer(){let e=new Yi({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&&ml(t)?t:Ot(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;pv(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;pv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(le(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var gv=Ki;var rT=C(We(),1);var it=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as eC,assertNonNullable as tC,debounce as rC,ErrorCategory as Jy,filter as Zy,filterChanged as _a,fromEvent as iC,isNonNullable as eT,map as ac,merge as Cn,observableFrom as sc,once as tT,Subscription as aC}from"@vkontakte/videoplayer-shared/es2018";var sn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Kr=class extends sn{constructor(){super(),this.listeners||sn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Xi=class{constructor(){Object.defineProperty(this,"signal",{value:new Kr,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&&(Xi.prototype[Symbol.toStringTag]="AbortController",Kr.prototype[Symbol.toStringTag]="AbortSignal");function nn(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function gl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!nn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let 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 Ji=nn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),vv=Ji?gl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,at=Ji?vv.fetch:window.fetch,NF=Ji?vv.Request:window.Request,ce=Ji?Xi:window.AbortController,FF=Ji?Kr:window.AbortSignal;var ec=C(Sl(),1);var fn=C(Vt(),1);var pt=()=>window.ManagedMediaSource||window.MediaSource,on=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_v=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Nv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as gn,clientChecker as bn}from"@vkontakte/videoplayer-shared/es2018";var Fe=document.createElement("video"),_R='video/mp4; codecs="avc1.42000a,mp4a.40.2"',NR='video/mp4; codecs="hev1.1.6.L93.B0"',Kv='video/webm; codecs="vp09.00.10.08"',Xv='video/webm; codecs="av01.0.00M.08"',FR='audio/mp4; codecs="mp4a.40.2"',qR='audio/webm; codecs="opus"',Fv,qv,Zi={mms:on(),mse:_v(),hls:!!((Fv=Fe.canPlayType)!=null&&Fv.call(Fe,"application/x-mpegurl")||(qv=Fe.canPlayType)!=null&&qv.call(Fe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Uv,Hv,xe={mp4:!!((Uv=Fe.canPlayType)!=null&&Uv.call(Fe,"video/mp4")),webm:!!((Hv=Fe.canPlayType)!=null&&Hv.call(Fe,"video/webm")),cmaf:!0},ln,jv,cn,Qv,dn,Gv,pn,Wv,hn,Yv,mn,zv,Pe={h264:!!((jv=(ln=pt())==null?void 0:ln.isTypeSupported)!=null&&jv.call(ln,_R)),h265:!!((Qv=(cn=pt())==null?void 0:cn.isTypeSupported)!=null&&Qv.call(cn,NR)),vp9:!!((Gv=(dn=pt())==null?void 0:dn.isTypeSupported)!=null&&Gv.call(dn,Kv)),av1:!!((Wv=(pn=pt())==null?void 0:pn.isTypeSupported)!=null&&Wv.call(pn,Xv)),aac:!!((Yv=(hn=pt())==null?void 0:hn.isTypeSupported)!=null&&Yv.call(hn,FR)),opus:!!((zv=(mn=pt())==null?void 0:mn.isTypeSupported)!=null&&zv.call(mn,qR))},Xr=(Pe.h264||Pe.h265)&&Pe.aac,cr,UR=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Xv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Kv}})]);cr={DASH_WEBM_AV1:e,DASH_WEBM:t}};UR().catch(a=>{console.error(a)});var Jr=Zi.hls&&xe.mp4,Jv=()=>Object.keys(Pe).filter(a=>Pe[a]),Zv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Zi.mse&&(!r||!!window.MediaStreamTrack)||Zi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&xe.mp4&&Xr;case"DASH_WEBM":return i&&xe.webm&&Pe.vp9&&Pe.opus;case"DASH_WEBM_AV1":return i&&xe.webm&&Pe.av1&&Pe.opus;case"DASH_STREAMS":return i&&(xe.mp4&&Xr||xe.webm&&(Pe.vp9||Pe.av1)&&(Pe.opus||Pe.aac));case"DASH_LIVE":return i&&xe.mp4&&Xr;case"DASH_LIVE_CMAF":return i&&xe.mp4&&Xr&&xe.cmaf;case"DASH_ONDEMAND":return i&&xe.mp4&&Xr;case"HLS":case"HLS_ONDEMAND":return Jr||e&&i&&xe.mp4&&Xr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Jr;case"MPEG":return xe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Zi.webrtc&&Zi.ws&&Pe.h264&&(xe.mp4||xe.webm);default:return gn(s)}})},un=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 cr?cr[t].smooth?[t,e]:cr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return cr?cr[t].powerEfficient?[t,e]:cr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:gn(a)}return[e,t]},eS=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...un(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(bn.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",...un(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...un(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...un(a),...i,"HLS","HLS_ONDEMAND"];default:gn(e)}return Jr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},tS=({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=bn.isMac&&bn.isSafari;if(bn.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:gn(a)}else Jr&&!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"]},yl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],rS=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,fn.default)(t.value.split("."),0)}for(let t of a){let r=(0,fn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,fn.default)(e.value.split("."),0)};var ES=C(IS(),1);import{ErrorCategory as ta}from"@vkontakte/videoplayer-shared/es2018";var xS=a=>{if(!a)return{id:"EmptyResponse",category:ta.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ta.NETWORK,message:`UV Error ${a}`};let e=(0,ES.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ta.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:ta.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ta.PARSER,message:"Response is valid XML, but parser failed"}};var _t=(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 ai,clientChecker as BD,combine as si,ErrorCategory as st,filter as wn,filterChanged as An,flattenObject as Ba,fromEvent as bt,getTraceSubscriptionMethod as OD,interval as Jl,isNonNullable as jy,isNullable as Qy,map as Oa,merge as br,now as Zl,Subject as kn,Subscription as Gy,tap as _D,throttle as ND,ValueSubject as K}from"@vkontakte/videoplayer-shared/es2018";var Sn=C(We(),1),ri=C(Vt(),1),yn=C(Sl(),1);var sM=(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)},nM=a=>window.clearTimeout(a),PS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),wS=!PS(window.requestIdleCallback)||!PS(window.cancelIdleCallback),Pl=wS?sM:window.requestIdleCallback,ra=wS?nM:window.cancelIdleCallback;var Vy=C(Qs(),1);import{assertNever as oM,ErrorCategory as AS,clientChecker as wl,Subject as kS}from"@vkontakte/videoplayer-shared/es2018";var uM=18,LS=!1;try{LS=wl.isSafari&&!!wl.macVersion&&wl.macVersion<=uM}catch(a){console.error(a)}var Al=class{constructor(e){this.bufferFull$=new kS;this.error$=new kS;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:AS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){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()})}async abort(e){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};LS&&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:AS.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:oM(t)}}},$S=Al;var kl=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 Ft,assertNonNullable as we,clientChecker as xD,ErrorCategory as ft,fromEvent as Ql,getExponentialDelay as Gl,isNonNullable as ti,isNullable as de,now as vn,once as PD,Subject as wD,Subscription as AD,ValueSubject as hr}from"@vkontakte/videoplayer-shared/es2018";var O=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 Zr=class extends O{};var ia=class extends O{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 aa=class extends O{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 sa=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var z=class extends O{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var na=class extends z{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 oa=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=class extends O{constructor(e,t){super(e,t),this.data=this.content}};var dr=class extends z{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 la=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ca=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=class extends z{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 pa=class extends z{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ha=class extends z{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ma=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends z{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 ba=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=class extends z{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Sa=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends z{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 Ta=class extends z{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 Ia=class extends z{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 Ea=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xa=class extends z{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 Pa=class extends O{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var cM={ftyp:aa,moov:sa,mvhd:na,moof:oa,mdat:ua,sidx:dr,trak:la,mdia:ma,mfhd:va,tkhd:fa,traf:Sa,tfhd:ya,tfdt:Ta,trun:Ia,minf:ba,sv3d:ca,st3d:da,prhd:pa,proj:ga,equi:ha,uuid:ia,stbl:Ea,stsd:xa,avc1:Pa,unknown:Zr},ht=class a{constructor(e={}){this.options={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=cM[e];return r?new r(t,new a):new Zr(t,new a)}};var Nt=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"),hM=a=>pM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",mM=a=>{let e=new dr(a,new ht),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})},fM=(a,e)=>{let r=new ht().parse(a),i=new Nt(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)},bM=a=>{let t=new ht().parse(a),r=new Nt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},gM=a=>{var i;let t=new ht().parse(a);return(i=new Nt(t).find("sidx"))==null?void 0:i.timescale},vM=(a,e)=>{let r=new ht().parse(a),s=new Nt(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},SM=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 ht().parse(a),i=new Nt(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},RS={validateData:hM,parseInit:SM,getIndexRange:()=>{},parseSegments:mM,parseFeedableSegmentChunk:fM,getChunkEndTime:vM,getServerLatencyTimestamps:bM,getTimescaleFromIndex:gM};var Aa=C(We(),1);import{assertNonNullable as $l,isNonNullable as VS,isNullable as TM}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as yM}from"@vkontakte/videoplayer-shared/es2018";var MS={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"}},DS=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=wa(a,t),i=r in MS,s=i?MS[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=wa(u),d=l*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}},wa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*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 wa(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:yM(e)}},pr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=DS(r);if(!e(i))return;i.type==="master"&&pr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},CS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=DS(a);return pr(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 BS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],IM=[231,22612,22743,167,171,163,160,175],EM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return pr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=ze(m,h);l=wa(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?pr(m,({tag:g,type:v,value:y})=>g===30321?(c=ze(y,v)===1,!1):!0):s&&n&&(0,Aa.default)(BS,p)&&(o=!0),!o}),$l(e,"Failed to parse webm Segment start"),$l(t,"Failed to parse webm Segment end"),$l(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}}}},xM=a=>{if(TM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},PM=(a,e)=>{let t=!1,r=!1,i=o=>VS(o.time)&&VS(o.position),s=[],n;return pr(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)(BS,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}}})},wM=a=>{let e=0,t=!1;try{pr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Aa.default)(IM,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},OS={validateData:CS,parseInit:EM,getIndexRange:xM,parseSegments:PM,parseFeedableSegmentChunk:wM};var ka=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return OS;case"mp4":return RS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ul=C(iy(),1),Ly=C(Br(),1),$y=C(Sy(),1),Ry=C(Vt(),1),Hl=C(Wr(),1);var yy=C(We(),1),Bl=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,yy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as ED,isNullable as Ay}from"@vkontakte/videoplayer-shared/es2018";var Ty=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var Iy=a=>{var e;try{let t=TD(),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 TD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
63
|
+
`}),m&&jg(i,u,m,o)};var ne=a=>new URL(a).hostname;import{assertNever as rv,assertNonNullable as iv,combine as qR,debounce as UR,ErrorCategory as av,filter as sv,filterChanged as HR,isNonNullable as ol,map as on,merge as nv,observableFrom as jR,once as QR,Subscription as GR,ValueSubject as ul,videoQualityToHeight as ov,videoSizeToQuality as WR}from"@vkontakte/videoplayer-shared/es2018";var Jg=C(Ct(),1);var Wg=C(_e(),1),Gg=a=>{if(a instanceof DOMException&&(0,Wg.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"))},we=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!Gg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return Gg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as an,isNullable as ER,assertNonNullable as ji}from"@vkontakte/videoplayer-shared/es2018";var zg=C(Gr(),1);import{isNonNullable as Yg,assertNonNullable as rn,now as TR}from"@vkontakte/videoplayer-shared/es2018";function oe(){return TR()}function il(a){return oe()-a}function al(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 Kg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Yr(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;rn(c);let k=il(c),R;if(k<b){R=b-k,setTimeout(g,R);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,L()},v=k=>(s=k,H),y=k=>(d=k,H),S=()=>(h="json",H),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},I=k=>(p=k,H),L=()=>{c=oe(),n=new i,n.open("get",a);let k=0,R,Y=0,ie=()=>(rn(c),Math.max(c,Math.max(R||0,Y||0)));if(s&&n.addEventListener("progress",w=>{let T=oe();s.updateChunk&&w.loaded>k&&(s.updateChunk(ie(),w.loaded-k),k=w.loaded,R=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;rn(n);let w=n.status;if(w>=200&&w<300){let{response:T,responseType:M}=n,j=T==null?void 0:T.byteLength;if(typeof j=="number"&&s){let N=j-k;N&&s.updateChunk&&s.updateChunk(ie(),N)}M==="json"&&(!T||!(0,zg.default)(T).length)?E():(d&&d(),e(T))}else E()}),n.addEventListener("error",()=>{E()}),p){let w=()=>{rn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Y=oe(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=h,n.send(),H},H={withBitrateReporting:v,withParallel:I,withJSONResponse:S,withRetryCount:k=>(l=k,H),withRetryInterval:(k,R)=>(Yg(k)&&(b=k),Yg(R)&&(m=R),H),withTimeout:k=>(o=k,H),withFinally:y,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return H}var Ui=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 Xg=C(Gr(),1);var Hi=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=oe(),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=oe()-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=Yr(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=oe()}_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=oe();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,Xg.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 xR}from"@vkontakte/videoplayer-shared/es2018";var sn=1e4,sl=3;var PR=6e4,wR=10,kR=1,AR=500,Qi=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 xR,this.chunkRateEstimator=new Ui(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=al(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=al(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*(O.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||{};!Dg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Jg.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||an(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=()=>{Kg(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 Hi(sl,sn,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=Yr(this.urlResolver.resolve(E,!1),I,L,()=>this._retryCallback()).withTimeout(sn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(sl).withFinally(()=>{u=null}).send()},h=(E,I,L)=>{ji(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=oe()-1e4,A=0;for(let _=0;_<this.bufferStates.length;_++){let q=this.bufferStates[_];E=Math.min(E,q.buf),q.ts<L&&A++}this.bufferStates.splice(0,A),t(`update playback rate; minBuffer=${E} drop=${A} jitter=${this.sourceJitter}`);let W=E-kR;this.sourceJitter>=0?W-=this.sourceJitter/2:this.sourceJitter-=1,W>3?m(1.15):W>1?m(1.1):W>.3?m(1.05):m(1)}},v=E=>{let I,L=()=>I&&I.start?I.start.length:0,A=w=>I.start[w]/1e3,W=w=>I.dur[w]/1e3,_=w=>I.fragIndex+w,q=(w,T)=>({chunkIdx:_(w),startTS:A(w),dur:W(w),discontinuity:T}),H=()=>{let w=0;if(I&&I.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,M=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,j=T;this.sourceJitter>1&&(j+=this.sourceJitter-1);let N=I.dur.length-1;for(;N>=0&&(j-=I.dur[N],!(j<=0));--N);w=Math.min(N,I.dur.length-1-M),w=Math.max(w,0)}return q(w,!0)},k=w=>{let T=L();if(!(T<=0)){if(an(w)){for(let M=0;M<T;M++)if(A(M)>w)return q(M)}return H()}},R=w=>{let T=L(),M=w?w.chunkIdx+1:0,j=M-I.fragIndex;if(!(T<=0)){if(!w||j<0||j-T>wR)return t(`Resync: offset=${j} bChunks=${T} chunk=`+JSON.stringify(w)),H();if(!(j>=T))return q(M-I.fragIndex,!1)}},Y=(w,T,M)=>{l&&l.abort(),l=Yr(this.urlResolver.resolve(w,!0,this.lowLatency),T,M,()=>this._retryCallback()).withTimeout(sn).withRetryCount(sl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,T)=>{Y(E,M=>{if(!d())return;I=M;let j=!!I.lowLatency;j!==this.lowLatency&&b(j);let N=0;for(let Ae=0;Ae<I.dur.length;++Ae)N+=I.dur[Ae];N>0&&(ji(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(N/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,w(k(T))},()=>this._handleNetworkError())},nextChunk:R}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ji(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:I,logger:L}=this.params,A=v(e.jidxUrl),W,_,q,H,k=0,R,Y,ie,w=()=>{R&&(clearTimeout(R),R=void 0);let Q=Math.max(AR,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=k+Q,fe=oe(),be=Math.min(1e4,le-fe);k=fe;let vt=()=>{l||d()&&A.seek(()=>{d()&&(k=oe(),T(),w())})};be>0?R=window.setTimeout(()=>{this.paused?w():vt()},be):vt()},T=()=>{let Q;for(;Q=A.nextChunk(H);)H=Q,ai(Q);let le=A.nextChunk(q);if(le){if(q&&le.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?w():(y(),this._initPlayerWith(e));return}Ae(le)}else w()},M=(Q,le)=>{if(!d()||!this.sourceBuffer)return;let fe,be,vt,vr=St=>{window.setTimeout(()=>{d()&&M(Q,le)},St)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),vr(100);else{let St=oe(),Ht=I.currentTime;!this.paused&&I.buffered.length>1&&Y===Ht&&St-ie>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),Y!==Ht&&(Y=Ht,ie=St);let Sr=this._getBufferSizeSec();if(Sr>30)L(`Buffered ${Sr} seconds; delaying appendBuffer`),vr(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:St,buf:Sr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(si){if(si.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),vt=this.sourceBuffer.buffered.length,vt!==0&&(fe=this.sourceBuffer.buffered.start(0),be=Ht,be-fe>4&&this.sourceBuffer.remove(fe,be-3)),vr(1e3);else throw si}}},j=()=>{_&&W&&(L([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(q)]),M(_,function(){_=null,T()}))},N=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),Ae=Q=>{d()&&h(N(Q),(le,fe)=>{if(d()){if(fe/=1e3,_=le,q=Q,n=Q.startTS,fe){let be=Math.min(10,Q.dur/fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*be:be}j()}},()=>this._handleNetworkError())},ai=Q=>{d()&&(ji(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(N(Q),!1)))},gr=Q=>{d()&&(e.cachedHeader=Q,M(Q,()=>{W=!0,j()}))};s=!0,A.seek(Q=>{if(d()){if(k=oe(),!Q){w();return}H=Q,!ER(E)||Q.startTS>E?Ae(Q):(q=Q,T())}},E),e.cachedHeader?gr(e.cachedHeader):p(e.headerUrl,gr,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),an(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 an(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=oe();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&&il(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=oe();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Yr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(sn).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;we(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))},PR))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var tv=C(Vr(),1);import{debounce as LR,filter as Zg,fromEvent as RR,interval as $R,isHigher as MR,isInvariantQuality as CR,isLower as DR,merge as VR,Subject as ev,Subscription as _R}from"@vkontakte/videoplayer-shared/es2018";var nl=class{constructor(){this.onDroopedVideoFramesLimit$=new ev;this.subscription=new _R;this.playing=!1;this.tracks=[];this.forceChecker$=new ev;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&&MR(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(RR(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=$R(this.droppedFramesChecker.checkTime).pipe(Zg(()=>this.playing),Zg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(LR(this.droppedFramesChecker.checkTime)),r=VR(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}},nn=nl;import{map as OR,Observable as BR}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as NR}from"@vkontakte/videoplayer-shared/es2018";var Gi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var FR=(a,e)=>new BR(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Gi()))},{...r,...e});i.observe(a);let s=NR(document,"visibilitychange").pipe(OR(n=>!document.hidden||Gi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Fe=FR;var YR=["paused","playing","ready"],zR=["paused","playing","ready"],Wi=class{constructor(e){this.subscription=new GR;this.videoState=new D("stopped");this.representations$=new ul([]);this.droppedFramesManager=new nn;this.maxSeekBackTime$=new ul(1/0);this.zeroTime$=new ul(void 0);this.liveOffset=new dt;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:av.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=Mt(u.name))!=null?r:WR(u.video),d=u.bitrate/1e3,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),ol(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,ll.default)(zR,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,ll.default)(YR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(pe(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(pe(this.params.source.url,u))}return;default:return rv(e)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:av.WTF,message:"DashLiveProvider internal logic error",thrown:i})};nv(this.videoState.stateChangeStarted$.pipe(on(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(on(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Ie(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(ne(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=Pe(this.video);this.subscription.add(this.representations$.pipe(on(i=>i.map(({track:s})=>s)),sv(i=>!!i.length),QR()).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(HR(),on(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(qR({zeroTime:this.zeroTime$.pipe(sv(ol)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(xe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Oe(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(Fe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i,min:s}})=>{this.dash.setAutoQualityLimits({max:i&&ov(i),min:s&&ov(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 rv(i.to)}},t)).add(nv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,jR(["init"])).pipe(UR(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),Ee(this.video)}createLiveDashPlayer(){let e=new Qi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,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&&ol(t)?t:Vt(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;iv(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;iv(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(pe(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var uv=Wi;var My=C(_e(),1);var it=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as RC,assertNonNullable as $C,debounce as MC,ErrorCategory as Ay,filter as Ly,filterChanged as Va,fromEvent as CC,isNonNullable as Ry,map as zl,merge as kn,observableFrom as Kl,once as $y,Subscription as DC}from"@vkontakte/videoplayer-shared/es2018";var un=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},zr=class extends un{constructor(){super(),this.listeners||un.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Yi=class{constructor(){Object.defineProperty(this,"signal",{value:new zr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Yi.prototype[Symbol.toStringTag]="AbortController",zr.prototype[Symbol.toStringTag]="AbortSignal");function ln(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 cl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!ln({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 zi=ln({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),lv=zi?cl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,at=zi?lv.fetch:window.fetch,YF=zi?lv.Request:window.Request,he=zi?Yi:window.AbortController,zF=zi?zr:window.AbortSignal;var Ql=C(pl(),1);var zv=C(Yv(),1);import{ErrorCategory as Xi}from"@vkontakte/videoplayer-shared/es2018";var Kv=a=>{if(!a)return{id:"EmptyResponse",category:Xi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Xi.NETWORK,message:`UV Error ${a}`};let e=(0,zv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Xi.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:Xi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Xi.PARSER,message:"Response is valid XML, but parser failed"}};var _t=(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 Ul,assertNonNullable as pr,combine as hr,ErrorCategory as st,filter as Ma,filterChanged as Hl,flattenObject as Ca,fromEvent as mr,getTraceSubscriptionMethod as dC,interval as jl,isNonNullable as yy,isNullable as Ty,map as ti,merge as fr,now as pC,Subject as Tn,Subscription as Iy,tap as hC,throttle as mC,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2018";var dn=C(_e(),1),Zr=C(Ct(),1),pn=C(pl(),1);var D$=(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)},V$=a=>window.clearTimeout(a),Xv=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Jv=!Xv(window.requestIdleCallback)||!Xv(window.cancelIdleCallback),gl=Jv?D$:window.requestIdleCallback,Ji=Jv?V$:window.cancelIdleCallback;var oy=C(Us(),1);import{assertNever as _$,ErrorCategory as Zv,Subject as eS}from"@vkontakte/videoplayer-shared/es2018";var O$=18,tS=!1;try{tS=O.browser.isSafari&&!!O.browser.safariVersion&&O.browser.safariVersion<=O$}catch(a){console.error(a)}var vl=class{constructor(e){this.bufferFull$=new eS;this.error$=new eS;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:Zv.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){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()})}async abort(e){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};tS&&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:Zv.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:_$(t)}}},rS=vl;var Sl=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 Bt,assertNonNullable as ke,ErrorCategory as ft,fromEvent as _l,getExponentialDelay as Ol,isNonNullable as Jr,isNullable as me,now as cn,once as ZM,Subject as eC,Subscription as tC,ValueSubject as lr}from"@vkontakte/videoplayer-shared/es2018";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 Kr=class extends F{};var Zi=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 ea=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 ta=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 ra=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 ia=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var aa=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var or=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 sa=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var na=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var oa=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 ua=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var la=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 ca=class extends F{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var da=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 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.children=this.scanForBoxes(this.content)}};var ma=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};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){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ga=class extends 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 va=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 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.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Ta=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 N$={ftyp:ea,moov:ta,mvhd:ra,moof:ia,mdat:aa,sidx:or,trak:sa,mdia:ca,mfhd:ma,tkhd:da,traf:fa,tfhd:ba,tfdt:ga,trun:va,minf:pa,sv3d:na,st3d:oa,prhd:ua,proj:ha,equi:la,uuid:Zi,stbl:Sa,stsd:ya,avc1:Ta,unknown:Kr},ht=class a{constructor(e={}){this.options={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=N$[e];return r?new r(t,new a):new Kr(t,new a)}};var Ot=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 q$=new TextDecoder("ascii"),U$=a=>q$.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",H$=a=>{let e=new or(a,new ht),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})},j$=(a,e)=>{let r=new ht().parse(a),i=new Ot(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)},Q$=a=>{let t=new ht().parse(a),r=new Ot(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},G$=a=>{var i;let t=new ht().parse(a);return(i=new Ot(t).find("sidx"))==null?void 0:i.timescale},W$=(a,e)=>{let r=new ht().parse(a),s=new Ot(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},Y$=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 ht().parse(a),i=new Ot(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},iS={validateData:U$,parseInit:Y$,getIndexRange:()=>{},parseSegments:H$,parseFeedableSegmentChunk:j$,getChunkEndTime:W$,getServerLatencyTimestamps:Q$,getTimescaleFromIndex:G$};var Ea=C(_e(),1);import{assertNonNullable as Tl,isNonNullable as oS,isNullable as K$}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as z$}from"@vkontakte/videoplayer-shared/es2018";var aS={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"}},sS=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=Ia(a,t),i=r in aS,s=i?aS[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=Ia(u),d=l*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}},Ia=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*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 Ia(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:z$(e)}},ur=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=sS(r);if(!e(i))return;i.type==="master"&&ur(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},nS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=sS(a);return ur(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 uS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],X$=[231,22612,22743,167,171,163,160,175],J$=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ur(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=ze(m,h);l=Ia(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?ur(m,({tag:g,type:v,value:y})=>g===30321?(c=ze(y,v)===1,!1):!0):s&&n&&(0,Ea.default)(uS,p)&&(o=!0),!o}),Tl(e,"Failed to parse webm Segment start"),Tl(t,"Failed to parse webm Segment end"),Tl(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}}}},Z$=a=>{if(K$(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},eM=(a,e)=>{let t=!1,r=!1,i=o=>oS(o.time)&&oS(o.position),s=[],n;return ur(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,Ea.default)(uS,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}}})},tM=a=>{let e=0,t=!1;try{ur(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Ea.default)(X$,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Ea.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},lS={validateData:nS,parseInit:J$,getIndexRange:Z$,parseSegments:eM,parseFeedableSegmentChunk:tM};var xa=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return lS;case"mp4":return iS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Cl=C(LS(),1),ty=C(Vr(),1),ry=C(QS(),1),iy=C(Ct(),1),Dl=C(Gr(),1);var GS=C(_e(),1),kl=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,GS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as JM,isNullable as ZS}from"@vkontakte/videoplayer-shared/es2018";var WS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var YS=a=>{var e;try{let t=KM(),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 KM(){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 _l=C(Vt(),1);import{videoSizeToQuality as ID}from"@vkontakte/videoplayer-shared/es2018";var Ey=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ct(s):void 0)!=null?u:ID({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},xy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Py=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),wy=({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,_l.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,_l.default)(i.split("."),0)}),ql=a=>"url"in a,be=a=>a.type==="template",La=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ky=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},mt=(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,Ly.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ul.default)(t,n,(o,u)=>Ay(s)?o:Ay(u)?s:(0,$y.default)(s,parseInt(u,10),"0"))}return t},My=(a,e)=>{var V,_,F,A,k,Q,ee,w,T,$,q,B,Ae,ui,vr,U,ne,pe,he,St,Sr,yt,Qt,yr,li,Pc,wc,Ac,kc,Lc,$c,Rc,Mc,Dc,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;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 Y,Gt;return(Gt=(Y=qe.textContent)==null?void 0:Y.trim())!=null?Gt:""}),o=(V=(0,Ry.default)(n,0))!=null?V:"",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,y=s.getAttribute("mediaPresentationDuration"),S=[...s.getElementsByTagName("Period")],E=S.reduce((qe,Y)=>({...qe,[Y.id]:Y.children}),{}),I=S.reduce((qe,Y)=>({...qe,[Y.id]:Y.getAttribute("duration")}),{});y?v=ky(y):(0,Hl.default)(I).filter(qe=>qe).length&&!u?v=(0,Hl.default)(I).reduce((qe,Y)=>{var Gt;return qe+((Gt=ky(Y))!=null?Gt:0)},0):b&&(v=parseInt(b,10));let D=0,L=(F=(_=s.getAttribute("profiles"))==null?void 0:_.split(","))!=null?F:[];for(let qe of S.map(Y=>Y.id))for(let Y of E[qe]){let Gt=(A=Y.getAttribute("id"))!=null?A:"id"+(D++).toString(10),ci=(k=Y.getAttribute("mimeType"))!=null?k:"",Xn=(Q=Y.getAttribute("codecs"))!=null?Q:"",Jn=(ee=Y.getAttribute("contentType"))!=null?ee:ci==null?void 0:ci.split("/")[0],XT=(T=(w=Y.getAttribute("profiles"))==null?void 0:w.split(","))!=null?T:[],od=(q=Iy(($=Y.getAttribute("lang"))!=null?$:""))!=null?q:{},Xa=(ui=(Ae=(B=Y.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:Ae.trim())!=null?ui:void 0,JT=Y.querySelectorAll("Representation"),ZT=Y.querySelector("SegmentTemplate"),eI=(U=(vr=Y.querySelector("Role"))==null?void 0:vr.getAttribute("value"))!=null?U:void 0,Tr=Jn,J={id:Gt,language:od.language,isDefault:eI==="main",label:Xa,codecs:Xn,hdr:Tr==="video"&&Bl(Xn),mime:ci,representations:[]};for(let W of JT){let Tt=(ne=W.getAttribute("lang"))!=null?ne:void 0,di=(he=(pe=Xa!=null?Xa:Y.getAttribute("label"))!=null?pe:W.getAttribute("label"))!=null?he:void 0,Ja=(yt=(Sr=(St=W.querySelector("BaseURL"))==null?void 0:St.textContent)==null?void 0:Sr.trim())!=null?yt:"",Wt=new URL(Ja||o,e).toString(),It=(Qt=W.getAttribute("mimeType"))!=null?Qt:ci,Za=(li=(yr=W.getAttribute("codecs"))!=null?yr:Xn)!=null?li:"",es;if(Jn==="text"){let Et=W.getAttribute("id")||"",ts=((Pc=od.privateuse)==null?void 0:Pc.includes("x-auto"))||Et.includes("_auto"),Yt=W.querySelector("SegmentTemplate");if(Yt){let pi={representationId:(wc=W.getAttribute("id"))!=null?wc:void 0,bandwidth:(Ac=W.getAttribute("bandwidth"))!=null?Ac:void 0},rs=parseInt((kc=W.getAttribute("bandwidth"))!=null?kc:"",10)/1e3,is=($c=parseInt((Lc=Yt.getAttribute("startNumber"))!=null?Lc:"",10))!=null?$c:1,Ir=parseInt((Rc=Yt.getAttribute("timescale"))!=null?Rc:"",10),Zn=(Mc=Yt.querySelectorAll("SegmentTimeline S"))!=null?Mc:[],Er=Yt.getAttribute("media");if(!Er)continue;let as=[],ss=0,ns="",xr=0,hi=is,me=0;for(let Ue of Zn){let zt=parseInt((Dc=Ue.getAttribute("d"))!=null?Dc:"",10),Ve=parseInt((Cc=Ue.getAttribute("r"))!=null?Cc:"",10)||0,xt=parseInt((Vc=Ue.getAttribute("t"))!=null?Vc:"",10);me=Number.isFinite(xt)?xt:me;let Kt=zt/Ir*1e3,Pt=me/Ir*1e3;for(let Xe=0;Xe<Ve+1;Xe++){let wt=mt(Er,{...pi,segmentNumber:hi.toString(10),segmentTime:(me+Xe*zt).toString(10)}),Pr=(Pt!=null?Pt:0)+Xe*Kt,fi=Pr+Kt;hi++,as.push({time:{from:Pr,to:fi},url:wt})}me+=(Ve+1)*zt,ss+=(Ve+1)*Kt}xr=me/Ir*1e3,ns=mt(Er,{...pi,segmentNumber:hi.toString(10),segmentTime:me.toString(10)});let mi={time:{from:xr,to:1/0},url:ns},ot={type:"template",baseUrl:Wt,segmentTemplateUrl:Er,initUrl:"",totalSegmentsDurationMs:ss,segments:as,nextSegmentBeyondManifest:mi,timescale:Ir};es={id:Et,kind:"text",segmentReference:ot,profiles:[],duration:v,bitrate:rs,mime:"",codecs:"",width:0,height:0,isAuto:ts}}else es={id:Et,isAuto:ts,kind:"text",url:Wt}}else{let Et=(Oc=(Bc=W.getAttribute("contentType"))!=null?Bc:It==null?void 0:It.split("/")[0])!=null?Oc:Jn,ts=(Nc=(_c=Y.getAttribute("profiles"))==null?void 0:_c.split(","))!=null?Nc:[],Yt=parseInt((Fc=W.getAttribute("width"))!=null?Fc:"",10),pi=parseInt((qc=W.getAttribute("height"))!=null?qc:"",10),rs=parseInt((Uc=W.getAttribute("bandwidth"))!=null?Uc:"",10)/1e3,is=(Hc=W.getAttribute("frameRate"))!=null?Hc:"",Ir=(jc=W.getAttribute("quality"))!=null?jc:void 0,Zn=is?Ty(is):void 0,Er=(Qc=W.getAttribute("id"))!=null?Qc:"id"+(D++).toString(10),as=Et==="video"?`${pi}p`:Et==="audio"?`${rs}Kbps`:Za,ss=`${Er}@${as}`,ns=[...L,...XT,...ts],xr,hi=W.querySelector("SegmentBase"),me=(Gc=W.querySelector("SegmentTemplate"))!=null?Gc:ZT;if(hi){let ot=(Yc=(Wc=W.querySelector("SegmentBase Initialization"))==null?void 0:Wc.getAttribute("range"))!=null?Yc:"",[Ue,zt]=ot.split("-").map(wt=>parseInt(wt,10)),Ve={from:Ue,to:zt},xt=(zc=W.querySelector("SegmentBase"))==null?void 0:zc.getAttribute("indexRange"),[Kt,Pt]=xt?xt.split("-").map(wt=>parseInt(wt,10)):[],Xe=xt?{from:Kt,to:Pt}:void 0;xr={type:"byteRange",url:Wt,initRange:Ve,indexRange:Xe}}else if(me){let ot={representationId:(Kc=W.getAttribute("id"))!=null?Kc:void 0,bandwidth:(Xc=W.getAttribute("bandwidth"))!=null?Xc:void 0},Ue=parseInt((Jc=me.getAttribute("timescale"))!=null?Jc:"",10),zt=(Zc=me.getAttribute("initialization"))!=null?Zc:"",Ve=me.getAttribute("media"),xt=(td=parseInt((ed=me.getAttribute("startNumber"))!=null?ed:"",10))!=null?td:1,Kt=mt(zt,ot);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");let Pt=(rd=me.querySelectorAll("SegmentTimeline S"))!=null?rd:[],Xe=[],wt=0,Pr="",fi=0;if(Pt.length){let os=xt,He=0;for(let wr of Pt){let Je=parseInt((id=wr.getAttribute("d"))!=null?id:"",10),Xt=parseInt((ad=wr.getAttribute("r"))!=null?ad:"",10)||0,us=parseInt((sd=wr.getAttribute("t"))!=null?sd:"",10);He=Number.isFinite(us)?us:He;let eo=Je/Ue*1e3,to=He/Ue*1e3;for(let ls=0;ls<Xt+1;ls++){let rI=mt(Ve,{...ot,segmentNumber:os.toString(10),segmentTime:(He+ls*Je).toString(10)}),ud=(to!=null?to:0)+ls*eo,iI=ud+eo;os++,Xe.push({time:{from:ud,to:iI},url:rI})}He+=(Xt+1)*Je,wt+=(Xt+1)*eo}fi=He/Ue*1e3,Pr=mt(Ve,{...ot,segmentNumber:os.toString(10),segmentTime:He.toString(10)})}else if(ED(v)){let He=parseInt((nd=me.getAttribute("duration"))!=null?nd:"",10)/Ue*1e3,wr=Math.ceil(v/He),Je=0;for(let Xt=1;Xt<wr;Xt++){let us=mt(Ve,{...ot,segmentNumber:Xt.toString(10),segmentTime:Je.toString(10)});Xe.push({time:{from:Je,to:Je+He},url:us}),Je+=He}fi=Je,Pr=mt(Ve,{...ot,segmentNumber:wr.toString(10),segmentTime:Je.toString(10)})}let tI={time:{from:fi,to:1/0},url:Pr};xr={type:"template",baseUrl:Wt,segmentTemplateUrl:Ve,initUrl:Kt,totalSegmentsDurationMs:wt,segments:Xe,nextSegmentBeyondManifest:tI,timescale:Ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Et||!It)continue;let mi={video:"video",audio:"audio",text:"text"}[Et];if(!mi)continue;Tr||(Tr=mi),es={id:ss,kind:mi,segmentReference:xr,profiles:ns,duration:v,bitrate:rs,mime:It,codecs:Za,width:Yt,height:pi,fps:Zn,quality:Ir}}J.language||(J.language=Tt),J.label||(J.label=di),J.mime||(J.mime=It),J.codecs||(J.codecs=Za),J.hdr||(J.hdr=Tr==="video"&&Bl(Za)),J.representations.push(es)}if(Tr){let W=i[Tr].find(Tt=>Tt.id===J.id);if(W&&J.representations.every(Tt=>be(Tt.segmentReference)))for(let Tt of W.representations){let di=J.representations.find(It=>It.id===Tt.id),Ja=di==null?void 0:di.segmentReference,Wt=Tt.segmentReference;Wt.segments.push(...Ja.segments),Wt.nextSegmentBeyondManifest=Ja.nextSegmentBeyondManifest}else i[Tr].push(J)}}return{duration:v,streams:i,baseUrls:n,live:g}};var Cy=C(We(),1);import{isNonNullable as Dy}from"@vkontakte/videoplayer-shared/es2018";var ge=(a,e)=>Dy(a)&&Dy(e)&&a.readyState==="open"&&(0,Cy.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 hr(0);this.currentLowLatencySegmentLength$=new hr(0);this.currentSegmentLength$=new hr(0);this.onLastSegment$=new hr(!1);this.fullyBuffered$=new hr(!1);this.playingRepresentation$=new hr(void 0);this.playingRepresentationInit$=new hr(void 0);this.error$=new wD;this.gaps=[];this.subscription=new AD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ce;this.switchAbortController=new ce;this.destroyAbortController=new ce;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=Ft(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);we(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new $S(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:ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:ft.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:ft.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ge(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,kl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=it(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);we(r,"No init buffer for starting representation"),we(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=Ft(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);we(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),we(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ge(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();ti(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ft(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);we(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(de(s)||de(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),we(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ge(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();ti(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ft(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,yn.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||!be(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);we(i);let s=this.segments.get(r);we(s,"No segments for starting representation");let n=this.initData.get(r);if(we(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 ce,Ft(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);we(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(de(o)||de(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),we(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ge(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();ti(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(){!de(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ce,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(de(e)||de(this.downloadingRepresentationId)||de(this.playingRepresentationId)||de(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer)||ti(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(we(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);ti(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=it(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&kl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=it(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,Sn.default)(o,i))l="high";else{let c=(0,ri.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&it(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ri.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;ti(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,yn.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,yn.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||!be(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ri.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;we(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(!be(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=mt(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&&ra&&ra(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&ra&&ra(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),y=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&ge(this.mediaSource,this.sourceBuffer)&&!(_t(this.sourceBuffer.buffered,p)&&_t(this.sourceBuffer.buffered,h)))&&g&&y});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}async loadSegments(e,t,r="auto"){be(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){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&&(await Ft(o,async 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=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=vn(),!c)return;let d=new DataView(c),p=ka(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?await Promise.all(l):await 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]),La(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())be(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){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&&(await Ft(n,async function*(){let u=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Ql(window,"online").pipe(PD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=vn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),La(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(be(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ri.default)(e,0).byte.from,to:(0,ri.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn(),await 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:ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!be(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=vn();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:ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Sn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=ka(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){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)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,m=d<=i;if(!h)continue;let b=ka(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var r;if(!(de(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer))){!this.isLive&&xD.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(_t(this.sourceBuffer.buffered,e.segment.time.from,100)&&_t(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ft.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=Pl(()=>(0,Vy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ft(this.destroyAbortController.signal,async 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,ka(e.mime),i)).then(async o=>{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&&be(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:ft.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!ge(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||de(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({...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,Sn.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?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ge(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||!ge(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||!ge(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||de(e)?0:it(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ge(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||!ge(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=Pl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:ft.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(de(this.sourceBuffer)||!ge(this.mediaSource,this.sourceBuffer)||de(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:ft.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ra=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var By=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 Ma,assertNever as _y,fromEvent as Ny,merge as kD,now as Da,Subscription as LD,Subject as Fy,ValueSubject as Wl,flattenObject as ii,ErrorCategory as Ca}from"@vkontakte/videoplayer-shared/es2018";var Oy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var In=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 Fy;this.error$=new Fy;this.abortAllController=new ce;this.subscription=new LD;this.fetchManifest=Ma(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ra(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Oy(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(Tn);return i?(t.log("success",ii({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ii({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ma(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var F,A;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let k=new URL(l,location.href);k.searchParams.append("bytes",`${r.from}-${r.to}`),l=k.toString();break}default:_y(t)}this.requestQuic&&(l=Ra(l));let p=this.abortAllController.signal,h;if(n){let k=new ce;if(h=kD(Ny(this.abortAllController.signal,"abort"),Ny(n,"abort")).subscribe(()=>{try{k.abort()}catch(Q){Tn(Q)}}),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(Q){Tn(Q)}p=k.signal}let m=Da();d.log("startRequest",ii({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:p}),g=Da();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((F=this.throughputEstimator)==null||F.addRawRtt(g-m),!b.ok||!b.body){h==null||h.unsubscribe();let k=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:k}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let k=Da(),Q={requestStartedAt:m,requestEndedAt:k,duration:k-m};return d.log("endRequest",ii(Q)),d.end(),b.arrayBuffer()}let[v,y]=b.body.tee(),S=v.getReader();o&&((A=this.throughputEstimator)==null||A.trackStream(y,u));let E=0,I=new Uint8Array(0),D=!1,L=k=>{h==null||h.unsubscribe(),D=!0,Tn(k)},j=Ma(p,async function*({done:k,value:Q}){if(E===0&&this.lastRequestFirstBytes$.next(Da()-m),p.aborted){h==null||h.unsubscribe();return}if(!k&&Q){let ee=new Uint8Array(I.length+Q.length);ee.set(I),ee.set(Q,I.length),I=ee,E+=Q.byteLength,i==null||i(new DataView(I.buffer),E),yield S==null?void 0:S.read().then(j,L)}}.bind(this));yield S==null?void 0:S.read().then(j,L),h==null||h.unsubscribe();let V=Da(),_={failed:D,requestStartedAt:m,requestEndedAt:V,duration:V-m};return D?(d.error("endRequest",ii(_)),d.end(),null):(d.log("endRequest",ii(_)),d.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ma(this.abortAllController.signal,async function*(e,t,r){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 y=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ma(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,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}=By(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:_y(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let r=await at(e,t),i=await 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:Ca.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ca.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ca.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ca.FATAL});break;default:console.log(JSON.stringify(r)),console.log(s),this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ca.FATAL})}}},Tn=a=>{if(!La(a))throw a};var mr=(a,e,t)=>t*e+(1-t)*a,Yl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,qy=(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 $D,ValueSubject as Uy}from"@vkontakte/videoplayer-shared/es2018";var qt=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 Uy(e.initial),this.debounced$=new Uy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new fe(`raw_${t}`),this.smoothedSeries$=new fe(`smoothed_${t}`),this.reportedSeries$=new fe(`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+=(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)&&($D(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 En=class extends qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=mr(this.slow,e,this.params.emaAlphaSlow),this.fast=mr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xn=class extends qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Yl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=mr(this.emaSmoothed,e,this.params.emaAlpha);let r=qy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Pn=class extends qt{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?mr(this.smoothed,t,this.params.emaAlpha):t}};var fr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new En({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new xn({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 Pn({initial:e,label:"liveEdgeDelay",...t})}};var zl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as RD,ValueSubject as MD}from"@vkontakte/videoplayer-shared/es2018";var Va=class a{constructor(e,t){this.currentRepresentation$=new MD(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(!RD(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({...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&&be(t.segmentReference))}};var FD=["timeupdate","progress","play","seeked","stalled","waiting"],qD=["timeupdate","progress","loadeddata","playing","seeked"];var Ln=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Gy;this.representationSubscription=new Gy;this.state$=new R("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new kn;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.isActiveLive$=new K(!1);this.isLowLatency$=new K(!1);this.liveDuration$=new K(0);this.liveSeekableDuration$=new K(0);this.liveAvailabilityStartTime$=new K(0);this.liveStreamStatus$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.fetcherRecoverableError$=new kn;this.fetcherError$=new kn;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new kn;this.gapWatchdogActive=!1;this.destroyController=new ce;this.initManifest=Xl(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:st.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Xl(this.destroyController.signal,async 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:st.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=My(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=xS(e))!=null?n:{id:"ManifestParsing",category:st.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=pt())==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=rS(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);BD.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",Ba(s)),s}.bind(this));this.initRepresentations=Xl(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",Ba({initialVideo:e,initialAudio:t,sourceHls:r})),ai(this.manifest),ai(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(bt(p,"error").pipe(wn(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:st.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Nv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&on())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],jy(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)}Va.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Va(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(br(...qD.map(p=>bt(this.element,p))).pipe(Oa(p=>this.element?it(this.element.buffered,this.element.currentTime*1e3):0),An(),_D(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(br(bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(An()).subscribe(h=>this.liveStreamEndTimestamp=Zl())),this.subscription.add(bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Jl(1e3).subscribe(h=>{let m=Gs(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()})})).add(bt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(si({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Oa(({isActiveLive:h,isLowLatency:m})=>h&&m),An()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||zl(this.element,1)})),this.representationSubscription.add(si({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wn(({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(si({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(wn(({isLive:h})=>h),An((h,m)=>m.bufferLength<h.bufferLength),Oa(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let g=Gs(this.manifestUrlString,2);return(h/2+m+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(si({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,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=h-g;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(S)>v&&(E=1+Math.sign(S)*y),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(S=>{var E,I;return(I=(E=S.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(si({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ND(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,g=Gs(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,I=isFinite(h)?h:m,D=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let j="none";if(D?j="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(V=>V.proceedLowLatencyLive()),j="active_low_latency"):g!==0&&I<y?j="live_forward_buffering":I<y+E&&(j="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),j==="live_forward_buffering"||j==="live_with_target_offset"){let V=p-(y+S),_=this.normolizeLiveOffset(Math.trunc(g+V/b)),F=Math.abs(_-g),A=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?A=g:_>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(A=_),this.manifestUrlString=le(this.manifestUrlString,A,2)}(j==="live_with_target_offset"||j==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:st.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=br(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Oa(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=br(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Oa(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(br(this.forceEnded$,si({allBuffersFull:l,someBufferEnded:c}).pipe(wn(({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:st.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(br(...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),be(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&jy(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=Jl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:st.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 In({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=fr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var i,s,n;ai(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Zl()-this.liveStreamEndTimestamp:0,r=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(r===0),this.manifestUrlString=le(this.manifestUrlString,r,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((i=this.videoBufferManager)==null?void 0:i.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ai(this.element),this.state$.setState("running"),this.subscription.add(br(...FD.map(e=>bt(this.element,e)),bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:st.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(bt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&_t(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,y,S,E,I,D;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=Zl(),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=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,c=(E=(S=this.audioBufferManager)==null?void 0:S.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%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(j=>{this.error$.next({id:"stallIntervalCallback",category:st.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:j})}),i.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(L),(D=this.audioBufferManager)==null||D.maintain(L),i.position=L}this.tracer.log("stallIntervalCallback",Ba(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Jl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:st.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){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)}async seek(e,t){var i,s,n,o,u;ai(this.element),ai(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),_t(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Qy(this.element)||Qy(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=OD(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}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await 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={...r,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ba(r)))}}};var $n=class{constructor(e,t){this.fov=e,this.orientation=t}};var Rn=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/(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={...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*(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 Wy=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Ll=C(Ct(),1);import{videoSizeToQuality as XM}from"@vkontakte/videoplayer-shared/es2018";var zS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Mt(s):void 0)!=null?u:XM({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},KS=({id:a,bitrate:e})=>({id:a,bitrate:e}),XS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),JS=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Rl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ll.default)(r.split("."),0),isDefault:i}),$l=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ll.default)(i.split("."),0)}),Ml=a=>"url"in a,Se=a=>a.type==="template",Pa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var ey=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},mt=(a,e)=>{let t=a;t=(0,Cl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,ty.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Cl.default)(t,n,(o,u)=>ZS(s)?o:ZS(u)?s:(0,ry.default)(s,parseInt(u,10),"0"))}return t},ay=(a,e)=>{var I,L,A,W,_,q,H,k,R,Y,ie,w,T,M,j,N,Ae,ai,gr,Q,le,fe,be,vt,vr,St,Ht,Sr,si,hc,mc,fc,bc,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,wc,kc,Ac,Lc,Rc,$c,Mc,Cc,Dc,Vc,_c,Oc,Bc,Nc,Fc,qc,Uc,Hc,jc;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,jt;return(jt=(X=qe.textContent)==null?void 0:X.trim())!=null?jt:""}),o=(I=(0,iy.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,X)=>({...qe,[X.id]:X.children}),{}),v=b.reduce((qe,X)=>({...qe,[X.id]:X.getAttribute("duration")}),{});p?d=ey(p):(0,Dl.default)(v).filter(qe=>qe).length&&!u?d=(0,Dl.default)(v).reduce((qe,X)=>{var jt;return qe+((jt=ey(X))!=null?jt:0)},0):m&&(d=parseInt(m,10));let y=0,S=(A=(L=s.getAttribute("profiles"))==null?void 0:L.split(","))!=null?A:[];for(let qe of b.map(X=>X.id))for(let X of g[qe]){let jt=(W=X.getAttribute("id"))!=null?W:"id"+(y++).toString(10),ni=(_=X.getAttribute("mimeType"))!=null?_:"",Hn=(q=X.getAttribute("codecs"))!=null?q:"",jn=(H=X.getAttribute("contentType"))!=null?H:ni==null?void 0:ni.split("/")[0],AT=(R=(k=X.getAttribute("profiles"))==null?void 0:k.split(","))!=null?R:[],Qc=(ie=YS((Y=X.getAttribute("lang"))!=null?Y:""))!=null?ie:{},Ya=(M=(T=(w=X.querySelector("Label"))==null?void 0:w.textContent)==null?void 0:T.trim())!=null?M:void 0,LT=X.querySelectorAll("Representation"),RT=X.querySelector("SegmentTemplate"),$T=(N=(j=X.querySelector("Role"))==null?void 0:j.getAttribute("value"))!=null?N:void 0,yr=jn,ee={id:jt,language:Qc.language,isDefault:$T==="main",label:Ya,codecs:Hn,hdr:yr==="video"&&kl(Hn),mime:ni,representations:[]};for(let K of LT){let yt=(Ae=K.getAttribute("lang"))!=null?Ae:void 0,oi=(gr=(ai=Ya!=null?Ya:X.getAttribute("label"))!=null?ai:K.getAttribute("label"))!=null?gr:void 0,za=(fe=(le=(Q=K.querySelector("BaseURL"))==null?void 0:Q.textContent)==null?void 0:le.trim())!=null?fe:"",Qt=new URL(za||o,e).toString(),Tt=(be=K.getAttribute("mimeType"))!=null?be:ni,Ka=(vr=(vt=K.getAttribute("codecs"))!=null?vt:Hn)!=null?vr:"",Xa;if(jn==="text"){let It=K.getAttribute("id")||"",Ja=((St=Qc.privateuse)==null?void 0:St.includes("x-auto"))||It.includes("_auto"),Gt=K.querySelector("SegmentTemplate");if(Gt){let ui={representationId:(Ht=K.getAttribute("id"))!=null?Ht:void 0,bandwidth:(Sr=K.getAttribute("bandwidth"))!=null?Sr:void 0},Za=parseInt((si=K.getAttribute("bandwidth"))!=null?si:"",10)/1e3,es=(mc=parseInt((hc=Gt.getAttribute("startNumber"))!=null?hc:"",10))!=null?mc:1,Tr=parseInt((fc=Gt.getAttribute("timescale"))!=null?fc:"",10),Qn=(bc=Gt.querySelectorAll("SegmentTimeline S"))!=null?bc:[],Ir=Gt.getAttribute("media");if(!Ir)continue;let ts=[],rs=0,is="",Er=0,li=es,ge=0;for(let Ue of Qn){let Wt=parseInt((gc=Ue.getAttribute("d"))!=null?gc:"",10),Ve=parseInt((vc=Ue.getAttribute("r"))!=null?vc:"",10)||0,Et=parseInt((Sc=Ue.getAttribute("t"))!=null?Sc:"",10);ge=Number.isFinite(Et)?Et:ge;let Yt=Wt/Tr*1e3,xt=ge/Tr*1e3;for(let Xe=0;Xe<Ve+1;Xe++){let Pt=mt(Ir,{...ui,segmentNumber:li.toString(10),segmentTime:(ge+Xe*Wt).toString(10)}),xr=(xt!=null?xt:0)+Xe*Yt,di=xr+Yt;li++,ts.push({time:{from:xr,to:di},url:Pt})}ge+=(Ve+1)*Wt,rs+=(Ve+1)*Yt}Er=ge/Tr*1e3,is=mt(Ir,{...ui,segmentNumber:li.toString(10),segmentTime:ge.toString(10)});let ci={time:{from:Er,to:1/0},url:is},nt={type:"template",baseUrl:Qt,segmentTemplateUrl:Ir,initUrl:"",totalSegmentsDurationMs:rs,segments:ts,nextSegmentBeyondManifest:ci,timescale:Tr};Xa={id:It,kind:"text",segmentReference:nt,profiles:[],duration:d,bitrate:Za,mime:"",codecs:"",width:0,height:0,isAuto:Ja}}else Xa={id:It,isAuto:Ja,kind:"text",url:Qt}}else{let It=(Tc=(yc=K.getAttribute("contentType"))!=null?yc:Tt==null?void 0:Tt.split("/")[0])!=null?Tc:jn,Ja=(Ec=(Ic=X.getAttribute("profiles"))==null?void 0:Ic.split(","))!=null?Ec:[],Gt=parseInt((xc=K.getAttribute("width"))!=null?xc:"",10),ui=parseInt((Pc=K.getAttribute("height"))!=null?Pc:"",10),Za=parseInt((wc=K.getAttribute("bandwidth"))!=null?wc:"",10)/1e3,es=(kc=K.getAttribute("frameRate"))!=null?kc:"",Tr=(Ac=K.getAttribute("quality"))!=null?Ac:void 0,Qn=es?WS(es):void 0,Ir=(Lc=K.getAttribute("id"))!=null?Lc:"id"+(y++).toString(10),ts=It==="video"?`${ui}p`:It==="audio"?`${Za}Kbps`:Ka,rs=`${Ir}@${ts}`,is=[...S,...AT,...Ja],Er,li=K.querySelector("SegmentBase"),ge=(Rc=K.querySelector("SegmentTemplate"))!=null?Rc:RT;if(li){let nt=(Mc=($c=K.querySelector("SegmentBase Initialization"))==null?void 0:$c.getAttribute("range"))!=null?Mc:"",[Ue,Wt]=nt.split("-").map(Pt=>parseInt(Pt,10)),Ve={from:Ue,to:Wt},Et=(Cc=K.querySelector("SegmentBase"))==null?void 0:Cc.getAttribute("indexRange"),[Yt,xt]=Et?Et.split("-").map(Pt=>parseInt(Pt,10)):[],Xe=Et?{from:Yt,to:xt}:void 0;Er={type:"byteRange",url:Qt,initRange:Ve,indexRange:Xe}}else if(ge){let nt={representationId:(Dc=K.getAttribute("id"))!=null?Dc:void 0,bandwidth:(Vc=K.getAttribute("bandwidth"))!=null?Vc:void 0},Ue=parseInt((_c=ge.getAttribute("timescale"))!=null?_c:"",10),Wt=(Oc=ge.getAttribute("initialization"))!=null?Oc:"",Ve=ge.getAttribute("media"),Et=(Nc=parseInt((Bc=ge.getAttribute("startNumber"))!=null?Bc:"",10))!=null?Nc:1,Yt=mt(Wt,nt);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");let xt=(Fc=ge.querySelectorAll("SegmentTimeline S"))!=null?Fc:[],Xe=[],Pt=0,xr="",di=0;if(xt.length){let as=Et,He=0;for(let Pr of xt){let Je=parseInt((qc=Pr.getAttribute("d"))!=null?qc:"",10),zt=parseInt((Uc=Pr.getAttribute("r"))!=null?Uc:"",10)||0,ss=parseInt((Hc=Pr.getAttribute("t"))!=null?Hc:"",10);He=Number.isFinite(ss)?ss:He;let Gn=Je/Ue*1e3,Wn=He/Ue*1e3;for(let ns=0;ns<zt+1;ns++){let CT=mt(Ve,{...nt,segmentNumber:as.toString(10),segmentTime:(He+ns*Je).toString(10)}),Gc=(Wn!=null?Wn:0)+ns*Gn,DT=Gc+Gn;as++,Xe.push({time:{from:Gc,to:DT},url:CT})}He+=(zt+1)*Je,Pt+=(zt+1)*Gn}di=He/Ue*1e3,xr=mt(Ve,{...nt,segmentNumber:as.toString(10),segmentTime:He.toString(10)})}else if(JM(d)){let He=parseInt((jc=ge.getAttribute("duration"))!=null?jc:"",10)/Ue*1e3,Pr=Math.ceil(d/He),Je=0;for(let zt=1;zt<Pr;zt++){let ss=mt(Ve,{...nt,segmentNumber:zt.toString(10),segmentTime:Je.toString(10)});Xe.push({time:{from:Je,to:Je+He},url:ss}),Je+=He}di=Je,xr=mt(Ve,{...nt,segmentNumber:Pr.toString(10),segmentTime:Je.toString(10)})}let MT={time:{from:di,to:1/0},url:xr};Er={type:"template",baseUrl:Qt,segmentTemplateUrl:Ve,initUrl:Yt,totalSegmentsDurationMs:Pt,segments:Xe,nextSegmentBeyondManifest:MT,timescale:Ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!It||!Tt)continue;let ci={video:"video",audio:"audio",text:"text"}[It];if(!ci)continue;yr||(yr=ci),Xa={id:rs,kind:ci,segmentReference:Er,profiles:is,duration:d,bitrate:Za,mime:Tt,codecs:Ka,width:Gt,height:ui,fps:Qn,quality:Tr}}ee.language||(ee.language=yt),ee.label||(ee.label=oi),ee.mime||(ee.mime=Tt),ee.codecs||(ee.codecs=Ka),ee.hdr||(ee.hdr=yr==="video"&&kl(Ka)),ee.representations.push(Xa)}if(yr){let K=i[yr].find(yt=>yt.id===ee.id);if(K&&ee.representations.every(yt=>Se(yt.segmentReference)))for(let yt of K.representations){let oi=ee.representations.find(Tt=>Tt.id===yt.id),za=oi==null?void 0:oi.segmentReference,Qt=yt.segmentReference;Qt.segments.push(...za.segments),Qt.nextSegmentBeyondManifest=za.nextSegmentBeyondManifest}else i[yr].push(ee)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var ny=C(_e(),1);import{isNonNullable as sy}from"@vkontakte/videoplayer-shared/es2018";var ye=(a,e)=>sy(a)&&sy(e)&&a.readyState==="open"&&(0,ny.default)([...a.activeSourceBuffers],e);var wa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new lr(0);this.currentLowLatencySegmentLength$=new lr(0);this.currentSegmentLength$=new lr(0);this.onLastSegment$=new lr(!1);this.fullyBuffered$=new lr(!1);this.playingRepresentation$=new lr(void 0);this.playingRepresentationInit$=new lr(void 0);this.error$=new eC;this.gaps=[];this.subscription=new tC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new he;this.switchAbortController=new he;this.destroyAbortController=new he;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Bt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ke(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new rS(this.sourceBuffer),this.subscription.add(_l(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(_l(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ft.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ye(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Sl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=it(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ke(r,"No init buffer for starting representation"),ke(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=Bt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);ke(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(me(s)||me(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ke(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ye(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();Jr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Bt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);ke(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(me(s)||me(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ke(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ye(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();Jr(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Bt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,pn.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||!Se(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);ke(i);let s=this.segments.get(r);ke(s,"No segments for starting representation");let n=this.initData.get(r);if(ke(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 he,Bt(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);ke(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(me(o)||me(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),ke(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ye(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();Jr(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(){!me(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new he,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(me(e)||me(this.downloadingRepresentationId)||me(this.playingRepresentationId)||me(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer)||Jr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ke(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);Jr(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=it(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Sl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=it(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,dn.default)(o,i))l="high";else{let c=(0,Zr.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&it(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Zr.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;Jr(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,pn.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,pn.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||!Se(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>({...h,status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,Zr.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;ke(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(!Se(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=mt(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&&Ji&&Ji(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Ji&&Ji(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),y=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&y&&this.sourceBuffer&&ye(this.mediaSource,this.sourceBuffer)&&!(_t(this.sourceBuffer.buffered,p)&&_t(this.sourceBuffer.buffered,h)))&&g&&y});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}async loadSegments(e,t,r="auto"){Se(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){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&&(await Bt(o,async function*(){let c=Ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=cn(),!c)return;let d=new DataView(c),p=xa(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?await Promise.all(l):await 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]),Pa(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())Se(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){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&&(await Bt(n,async function*(){let u=Ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),_l(window,"online").pipe(ZM()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=cn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Pa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Se(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Zr.default)(e,0).byte.from,to:(0,Zr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=cn(),await 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:ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Se(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=cn();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:ft.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,dn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=xa(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){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)continue;if(s.aborted){await n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<i,m=d<=i;if(!h)continue;let b=xa(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var r;if(!(me(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer))){!this.isLive&&O.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(_t(this.sourceBuffer.buffered,e.segment.time.from,100)&&_t(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ft.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",Ml(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=gl(()=>(0,oy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Bt(this.destroyAbortController.signal,async function*(){let o=Ol(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,xa(e.mime),i)).then(async o=>{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&&Se(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:ft.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||me(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({...u.time}),i=n(i);let l=Ml(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,dn.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?(await Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!ye(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||!ye(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||!ye(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||me(e)?0:it(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ye(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||!ye(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=gl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:ft.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(me(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer)||me(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:ft.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ka=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var uy=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 Aa,assertNever as cy,fromEvent as dy,merge as rC,now as La,Subscription as iC,Subject as py,ValueSubject as Bl,flattenObject as ei,ErrorCategory as Ra}from"@vkontakte/videoplayer-shared/es2018";var ly=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var mn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Bl(void 0);this.lastConnectionReused$=new Bl(void 0);this.lastRequestFirstBytes$=new Bl(void 0);this.recoverableError$=new py;this.error$=new py;this.abortAllController=new he;this.subscription=new iC;this.fetchManifest=Aa(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ka(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=ly(r));let i=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(hn);return i?(t.log("success",ei({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ei({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Aa(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var H,k;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let R=new URL(l,location.href);R.searchParams.append("bytes",`${r.from}-${r.to}`),l=R.toString();break}default:cy(t)}this.requestQuic&&(l=ka(l));let p=this.abortAllController.signal,h;if(n){let R=new he;if(h=rC(dy(this.abortAllController.signal,"abort"),dy(n,"abort")).subscribe(()=>{try{R.abort()}catch(Y){hn(Y)}}),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(Y){hn(Y)}p=R.signal}let m=La();d.log("startRequest",ei({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:p}),g=La();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h==null||h.unsubscribe(),null;if((H=this.throughputEstimator)==null||H.addRawRtt(g-m),!b.ok||!b.body){h==null||h.unsubscribe();let R=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:R}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let R=La(),Y={requestStartedAt:m,requestEndedAt:R,duration:R-m};return d.log("endRequest",ei(Y)),d.end(),b.arrayBuffer()}let[v,y]=b.body.tee(),S=v.getReader();o&&((k=this.throughputEstimator)==null||k.trackStream(y,u));let E=0,I=new Uint8Array(0),L=!1,A=R=>{h==null||h.unsubscribe(),L=!0,hn(R)},W=Aa(p,async function*({done:R,value:Y}){if(E===0&&this.lastRequestFirstBytes$.next(La()-m),p.aborted){h==null||h.unsubscribe();return}if(!R&&Y){let ie=new Uint8Array(I.length+Y.length);ie.set(I),ie.set(Y,I.length),I=ie,E+=Y.byteLength,i==null||i(new DataView(I.buffer),E),yield S==null?void 0:S.read().then(W,A)}}.bind(this));yield S==null?void 0:S.read().then(W,A),h==null||h.unsubscribe();let _=La(),q={failed:L,requestStartedAt:m,requestEndedAt:_,duration:_-m};return L?(d.error("endRequest",ei(q)),d.end(),null):(d.log("endRequest",ei(q)),d.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=Aa(this.abortAllController.signal,async function*(e,t,r){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 y=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Aa(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,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}=uy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:cy(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let r=await at(e,t);if(r.ok)return r;let i=await r.text(),s=parseInt(i);switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ra.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ra.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ra.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ra.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ra.FATAL})}}},hn=a=>{if(!Pa(a))throw a};var cr=(a,e,t)=>t*e+(1-t)*a,Nl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,hy=(a,e,t,r)=>{let i=0,s=t,n=Nl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as aC,ValueSubject as my}from"@vkontakte/videoplayer-shared/es2018";var Nt=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 my(e.initial),this.debounced$=new my(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`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+=(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)&&(aC(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 fn=class extends Nt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=cr(this.slow,e,this.params.emaAlphaSlow),this.fast=cr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var bn=class extends Nt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Nl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cr(this.emaSmoothed,e,this.params.emaAlpha);let r=hy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var gn=class extends Nt{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?cr(this.smoothed,t,this.params.emaAlpha):t}};var dr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new fn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new bn({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 gn({initial:e,label:"liveEdgeDelay",...t})}};var Fl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as sC,ValueSubject as nC}from"@vkontakte/videoplayer-shared/es2018";var $a=class a{constructor(e,t){this.currentRepresentation$=new nC(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(!sC(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({...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&&Se(t.segmentReference))}};var Sn=C(Ct(),1);import{assertNever as yn}from"@vkontakte/videoplayer-shared/es2018";var fy=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let{containers:i,protocols:s,codecs:n,nativeHlsSupported:o}=O.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 yn(c)}})},vn=a=>{let{webmDecodingInfo:e}=O.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:yn(a)}return[t,r]},by=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...vn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(O.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",...vn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...vn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...vn(a),...i,"HLS","HLS_ONDEMAND"];default:yn(e)}return O.video.nativeHlsSupported?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},gy=({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=O.device.isMac&&O.browser.isSafari;if(O.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:yn(a)}else O.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"]},ql=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],vy=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Sn.default)(t.value.split("."),0)}for(let t of a){let r=(0,Sn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,Sn.default)(e.value.split("."),0)};var fC=["timeupdate","progress","play","seeked","stalled","waiting"],bC=["timeupdate","progress","loadeddata","playing","seeked"];var In=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Iy;this.representationSubscription=new Iy;this.state$=new D("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new Tn;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.isActiveLive$=new re(!1);this.isLowLatency$=new re(!1);this.liveDuration$=new re(0);this.liveAvailabilityStartTime$=new re(void 0);this.bufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.fetcherRecoverableError$=new Tn;this.fetcherError$=new Tn;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Tn;this.gapWatchdogActive=!1;this.destroyController=new he;this.initManifest=Ul(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=pe(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:st.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ul(this.destroyController.signal,async 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:st.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=ay(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Kv(e))!=null?n:{id:"ManifestParsing",category:st.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=Ye())==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=vy(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);O.display.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",Ca(s)),s}.bind(this));this.initRepresentations=Ul(this.destroyController.signal,async function*(e,t,r){var d;this.tracer.log("initRepresentationsStart",Ca({initialVideo:e,initialAudio:t,sourceHls:r})),pr(this.manifest),pr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(mr(p,"error").pipe(Ma(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:st.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?mg():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&zs())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.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 wa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],yy(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new wa("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(jl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Hs(this.manifestUrlString,2);this.manifestUrlString=pe(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(fr(...bC.map(p=>mr(this.element,p))).pipe(ti(p=>this.element?it(this.element.buffered,this.element.currentTime*1e3):0),Hl(),hC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(fr(mr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(hr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ti(({isActiveLive:h,isLowLatency:m})=>h&&m),Hl()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Fl(this.element,1)})),this.representationSubscription.add(hr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ma(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(hr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$,currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Ma(({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(hr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ma(({isLive:h})=>h),ti(h=>({...h})),Hl((h,m)=>m.bufferLength<h.bufferLength),ti(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let g=Hs(this.manifestUrlString,2);return(h/2+m+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(hr({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,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=h-g;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(S)>v&&(E=1+Math.sign(S)*y),Fl(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(S=>{var E,I;return(I=(E=S.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(hr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(mC(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(pr(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=Hs(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),S=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,I=isFinite(h)?h:m,L=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=v<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLive$.next(A);let W="none";if(L?W="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),W="active_low_latency"):g!==0&&I<y?W="live_forward_buffering":I<y+E&&(W="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),W==="live_forward_buffering"||W==="live_with_target_offset"){let _=p-(y+S),q=this.normolizeLiveOffset(Math.trunc(g+_/b)),H=Math.abs(q-g),k;!h||H<=this.tuning.dashCmafLive.offsetCalculationError?k=g:q>0&&H>this.tuning.dashCmafLive.offsetCalculationError?k=q:k=0,this.manifestUrlString=pe(this.manifestUrlString,k,2)}W!=="none"&&W!=="active_low_latency"&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:st.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=fr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ti(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=fr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ti(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(fr(this.forceEnded$,hr({allBuffersFull:l,someBufferEnded:c}).pipe(Ma(({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:st.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(fr(...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,Ql.default)((0,Ql.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Se(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&yy(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=jl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:st.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 mn({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=dr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;pr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLive$.next(t===0),this.liveLastSeekOffset=t,this.manifestUrlString=pe(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){pr(this.element),this.state$.setState("running"),this.subscription.add(fr(...fC.map(e=>mr(this.element,e)),mr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:st.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(mr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(mr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&_t(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,y,S,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=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,c=(E=(S=this.audioBufferManager)==null?void 0:S.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(A=>{this.error$.next({id:"stallIntervalCallback",category:st.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:A})}),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let A=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(A),(L=this.audioBufferManager)==null||L.maintain(A),i.position=A}this.tracer.log("stallIntervalCallback",Ca(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=jl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:st.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){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)}async seek(e,t){var i,s,n,o,u;pr(this.element),pr(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),_t(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Ty(this.element)||Ty(this.videoBufferManager))&&(this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Ca({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=dC(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}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await 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={...r,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Ca(r)))}}};var En=class{constructor(e,t){this.fov=e,this.orientation=t}};var xn=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/(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={...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*(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 Ey=`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 xy=`#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 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 $n(this.params.fov,this.params.orientation),this.cameraRotationManager=new Rn(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(Wy,this.gl.VERTEX_SHADER),r=this.createShader(Yy,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 jD,now as zy,Subscription as QD,filter as GD,combine as Ky,ValueSubject as tc,isNonNullable as WD}from"@vkontakte/videoplayer-shared/es2018";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 QD;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(Ky({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(GD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Ky({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(jD(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=zy(),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,WD(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=zy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Xy=rc;import{combine as YD,map as zD,observeElementSize as KD,Subscription as XD,ValueSubject as ic,noop as JD}from"@vkontakte/videoplayer-shared/es2018";var Dn=class{constructor(){this.subscription=new XD;this.pipSize$=new ic(void 0);this.videoSize$=new ic(void 0);this.elementSize$=new ic(void 0);this.pictureInPictureWindowRemoveEventListener=JD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(KD(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(YD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(zD(({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 gr=class{constructor(e){this.subscription=new aC;this.videoState=new R("stopped");this.droppedFramesManager=new rn;this.stallsManager=new Xy;this.elementSizeManager=new Dn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ji;this.audioTrackSwitchHistory=new ji;this.syncPlayback=()=>{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"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return eC(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 Oe(e.source.url),this.params=e,this.video=Se(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(ie(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=Ie(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Jy.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(Zy(l=>!!l.length),tT()).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"),_a());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(_a()),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(Zy(eT),tT()),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(tt(this.video,t.isLooped,i)),this.subscription.add(Te(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Be(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ne(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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(tC(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=xy(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=Ey({...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=Py(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(Cn(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$,iC(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,rT.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});eT(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await 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(_a()).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(_a()).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"),_a());this.subscription.add(Cn(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(Cn(o,this.player.state$.stateChangeEnded$,sc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Cn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,sc(["init"])).pipe(rC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var L,j,V,_,F,A,k,Q,ee,w,T,$,q;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(L=e.videoTrack.getState())==null?void 0:L.id,n=[...this.videoTracksMap.keys()].find(({id:B})=>B===i),o=t.currentVideoTrack$.getValue(),u=((_=(V=e.videoStream.getState())!=null?V:n&&((j=this.videoTracksMap.get(n))==null?void 0:j.stream))!=null?_:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:B})=>B===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=it(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=(F=e.audioStream.getState())!=null?F:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(A=[...this.audioStreamsMap.keys()].find(({id:B})=>B===(b==null?void 0:b.id)))!=null?A:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let B=Js(n,c,(k=this.audioStreamsMap.get(g))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(Q=B==null?void 0:B.bitrate)!=null?Q:-1/0)}if(o){let B=Js(o,c,(ee=this.audioStreamsMap.get(g))!=null?ee:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(w=B==null?void 0:B.bitrate)!=null?w:-1/0)}}let y=Ot(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}),S=r?y!=null?y:n:n!=null?n:y,E=g&&ev(S,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=($=this.videoTracksMap.get(S))==null?void 0:$.representation,D=E&&((q=this.audioTracksMap.get(E))==null?void 0:q.representation);if(I&&D)return[I,D];if(I&&!D&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Jy.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),ye(this.video),this.tracer.end()}};var Na=class extends gr{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 Vn,merge as iT,filter as sC,filterChanged as nC,isNullable as nc,map as aT,ValueSubject as oc}from"@vkontakte/videoplayer-shared/es2018";var Fa=class extends gr{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 oc(1);s(r.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(i.isLowLatency.stateChangeEnded$.pipe(aT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Vn({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(aT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(Vn({position:t.position$,liveStreamStatus:this.player.liveStreamStatus$}).subscribe(({position:o,liveStreamStatus:u})=>t.isLiveEnded$.next(u!=="active"&&o===0))).add(Vn({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:iT(r.playbackRateState$,new oc(1))}).pipe(sC(({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||nc(l)||(e=o-l)})).add(Vn({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:iT(r.playbackRateState$,new oc(1))}).pipe(nC((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||nc(o)||nc(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=wy(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 nT=C(Qs(),1);import{assertNever as qa,assertNonNullable as sT,debounce as oC,ErrorCategory as Bn,filter as uC,isNonNullable as lC,isNullable as cC,map as On,merge as dC,Observable as pC,observableFrom as hC,Subscription as mC,videoSizeToQuality as fC}from"@vkontakte/videoplayer-shared/es2018";var Ke={};var ni=(a,e)=>new pC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ua=class{constructor(e){this.subscription=new mC;this.videoState=new R("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:qa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:qa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:qa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:qa(e)}break;default:qa(t)}};this.textTracksManager=new Oe(e.source.url),this.video=Se(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(ie(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),ye(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Bn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,nT.default)(import("hls.js").then(i=>{e||(Ke.Hls=i.default,Ke.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){sT(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){sT(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Bn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ie(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(tt(this.video,e.isLooped,r)),this.subscription.add(Te(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Be(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ne(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(On(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ni(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Bn.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"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(ni(this.hls,Ke.Events.MANIFEST_PARSED).pipe(On(({levels:l})=>l.reduce((c,d)=>{var y,S;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(S=Ct((y=d.attrs.QUALITY)!=null?y:""))!=null?S:fC({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(ni(this.hls,Ke.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(ni(this.hls,Ke.Events.LEVEL_LOADING).pipe(On(({url:l})=>ie(l))),t.hostname$),s(ni(this.hls,Ke.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(Rt(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=ni(this.hls,Ke.Events.LEVEL_SWITCHED).pipe(On(({level:l})=>n(this.hls.levels[l])));o.pipe(uC(lC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Rt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(cC(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=dC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hC(["init"])).pipe(oC(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)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:t}))||(this.videoState.setState("paused"),x(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"),x(this.params.desiredState.playbackState,"stopped",!0)}};var oT="X-Playback-Duration",uc=async a=>{var i;let e=await at(a),t=await 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(oT)?parseInt(e.headers.get(oT),10):void 0};import{assertNever as wC,combine as AC,debounce as kC,ErrorCategory as Fn,filter as LC,filterChanged as $C,isNonNullable as cT,isNullable as qn,map as dT,merge as RC,observableFrom as MC,Subscription as DC,ValueSubject as dc,VideoQuality as CC}from"@vkontakte/videoplayer-shared/es2018";var cc=C(cu(),1);import{videoSizeToQuality as bC,getExponentialDelay as gC}from"@vkontakte/videoplayer-shared/es2018";var vC=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=bC({width:t,height:r})}return e!=null?e:null},SC=(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(TC(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([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ce;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:PC.WTF,thrown:t,message:e})}};var Ha=class{constructor(e){this.subscription=new DC;this.videoState=new R("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new dc([]);this.liveOffset=new lr;this.manifestStartTime$=new dc(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"),x(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"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(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"&&x(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"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return wC(t)}};var r;this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:CC.INVARIANT,url:this.params.source.url};let t=(i,s)=>_n(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 Nn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Oe(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:Fn.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:Fn.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(ie(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new dc((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:Fn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ie(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(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ne(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"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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($C(),dT(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&&cT(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(ie(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(AC({startTime:this.manifestStartTime$.pipe(LC(cT)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(dT(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=RC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,MC(["init"])).pipe(kC(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),ye(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(qn(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=le(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),uc(n).then(c=>{var d;if(!qn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(qn(p)||!isFinite(p))&&at(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();uc(g).then(v=>{qn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Fn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=le(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as VC,debounce as BC,ErrorCategory as pc,fromEvent as hc,isNonNullable as OC,isNullable as _C,map as pT,merge as hT,observableFrom as mT,Subscription as NC,ValueSubject as FC,VideoQuality as qC,clientChecker as UC}from"@vkontakte/videoplayer-shared/es2018";var ja=class{constructor(e){this.subscription=new NC;this.videoState=new R("stopped");this.manifests$=new FC([]);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"),x(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"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return VC(t)}};this.textTracksManager=new Oe(e.source.url),this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:qC.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(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),_n(le(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:pc.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:pc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ie(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(pT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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&&OC(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(ie(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(pT(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)),!UC.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(hT(hc(o,"addtrack"),hc(o,"removetrack"),hc(o,"change"),mT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=hT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,mT(["init"])).pipe(BC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){var s,n;let e=this.selectManifest();if(_C(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(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var gT=C(Br(),1),mc=C(Wr(),1),vT=C(Vt(),1);import{assertNever as HC,assertNonNullable as fT,debounce as jC,ErrorCategory as bT,isHigherOrEqual as QC,isLowerOrEqual as GC,isNonNullable as WC,merge as YC,observableFrom as zC,Subscription as KC,map as XC}from"@vkontakte/videoplayer-shared/es2018";var Qa=class{constructor(e){this.subscription=new KC;this.videoState=new R("stopped");this.trackUrls={};this.textTracksManager=new Oe;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"),x(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"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return HC(e)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),(0,gT.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,mc.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:bT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ie(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(XC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ne(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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&&WC(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=YC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,zC(["init"])).pipe(jC(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),ye(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;fT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];fT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ra(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ie(t))}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bT.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=Ot(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,mc.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Hi({limits:e,lowestAvailableQuality:(c=(0,vT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?GC(i,e.max):!0,u=e.min?QC(i,e.min):!0;o&&u||r(e)}};import{assertNever as yT,debounce as t0,merge as TT,observableFrom as r0,Subscription as i0,map as IT,ValueSubject as a0,ErrorCategory as bc,VideoQuality as s0}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as JC}from"@vkontakte/videoplayer-shared/es2018";var ST=["stun:videostun.mycdn.me:80"],ZC=1e3,e0=3,fc=()=>null,Un=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=fc;this.externalStopCallback=fc;this.externalErrorCallback=fc;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:ST}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await 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:JC.WTF,message:e.message})}async onPeerConnectionStream(e){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()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await 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),ZC)}normalizeOptions(e={}){let t={stunServerList:ST,maxRetryNumber:e0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ga=class{constructor(e){this.videoState=new R("stopped");this.maxSeekBackTime$=new a0(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"),x(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"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return yT(e)}};this.subscription=new i0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Se(e.container,e.tuning),this.liveStreamClient=new Un(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),ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:bc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};TT(this.videoState.stateChangeStarted$.pipe(IT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(IT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ie(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(Ne(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(Te(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 yT(n.to)}},r)).add(TT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r0(["init"])).pipe(t0(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(ie(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:s0.INVARIANT}),this.video.srcObject=e,x(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:bc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:bc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Wa=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 za,assertNonNullable as Ut,ErrorCategory as Hn,filter as kT,isNonNullable as LT,isNullable as h0,map as m0,merge as f0,once as b0,Subject as se,Subscription as $T,ValueSubject as M,flattenObject as RT}from"@vkontakte/videoplayer-shared/es2018";import{Observable as n0,map as ET,Subscription as o0,Subject as u0}from"@vkontakte/videoplayer-shared/es2018";var xT=a=>new n0(e=>{let t=new o0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(ET(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(ET(({type:l})=>l!==void 0)),n=new u0,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 l0,Subscription as c0,combine as d0,filter as wT,once as AT}from"@vkontakte/videoplayer-shared/es2018";function PT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as p0}from"@vkontakte/videoplayer-shared/es2018";var Ya=class Ya{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ce;this.subscriptions=new c0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(wT(s=>!!s.type),AT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){p0.isSafari&&e!=="MPEG"||this.subscriptions.add(d0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(wT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),AT()).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}async initAudioContextOnce(e){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"&&(await 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:Ya.errorId,category:l0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ya.errorId} exception`,thrown:e})}};Ya.errorId="VolumeMultiplierManager";var oi=Ya;var g0={chunkDuration:5e3,maxParallelRequests:5},Ka=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new se;this.noAvailableProvidersError$=new se;this.volumeMultiplierError$=new se;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new se,fetcherError$:new se,fetcherRecoverableError$:new se,warning$:new se,willSeekEvent$:new se,soundProhibitedEvent$:new se,seekedEvent$:new se,loopedEvent$:new se,endedEvent$:new se,firstBytesEvent$:new se,loadedMetadataEvent$:new se,firstFrameEvent$:new se,canplay$:new se,isLive$:new M(void 0),isLiveEnded$:new M(null),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),severeStallOccurred$:new se,availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M(""),getCurrentTime$:new M(null)};this.subscription=new $T;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=Zv([...tS(this.params.tuning),...eS(this.params.tuning)],this.params.tuning).filter(l=>LT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,gc.default)(i,l)),...t.filter(l=>(0,gc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",RT(s)),this.screenFormatsIterator=new Wa(s);let n=[...yl(!0),...yl(!1)];this.chromecastFormatsIterator=new Wa(n.filter(l=>LT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&oi.isSupported()&&(this.volumeMultiplierManager=new oi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(h0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Hn.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 za(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 Ut(o),new Na({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Fa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ut(o),Jr||!this.params.tuning.useHlsJs?new ja({...n,source:o}):new Ua({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Ha({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Qa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ut(o),new gv({...n,source:o,config:{...g0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Ga({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 za(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 Ut(o),new Ni({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return za(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return za(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 za(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{...e,url:r(e.url)}}return(0,DT.default)((0,MT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new $T,t=!1,r=0;return e.add(f0(this.providerOutput.error$.pipe(kT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),xT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(m0(i=>({id:`ProviderHangup:${i}`,category:Hn.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(kT(({to:s})=>s==="playing"),b0()).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===Hn.NETWORK,u=i.category===Hn.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={...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",RT(n))})),e}};import{fromEvent as jn,once as v0,combine as S0,Subscription as CT,ValueSubject as vc,map as y0,filter as T0,isNonNullable as Qn,now as Ce,safeStorage as Sc}from"@vkontakte/videoplayer-shared/es2018";var I0=5e3,VT="one_video_throughput",BT="one_video_rtt",gt=window.navigator.connection,OT=()=>{let a=gt==null?void 0:gt.downlink;if(Qn(a)&&a!==10)return a*1e3},_T=()=>{let a=gt==null?void 0:gt.rtt;if(Qn(a)&&a!==3e3)return a},NT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},yc=class a{constructor(e){this.subscription=new CT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(VT)||(e.useBrowserEstimation?OT():void 0)||I0,r=(s=(i=a.load(BT))!=null?i:e.useBrowserEstimation?_T():void 0)!=null?s:0;if(this.throughput$=new vc(t),this.rtt$=new vc(r),this.rttAdjustedThroughput$=new vc(NT(t,r,e.rttPenaltyRequestSize)),this.throughput=fr.getSmoothedValue(t,-1,e),this.rtt=fr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=OT();u&&this.throughput.next(u);let l=_T();Qn(l)&&this.rtt.next(l)};gt&&"onchange"in gt&&this.subscription.add(jn(gt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Sc.set(VT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Sc.set(BT,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(y0(({throughput:n,rtt:o})=>NT(n,o,e.rttPenaltyRequestSize)),T0(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=Ce(),i=new CT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(jn(e,"progress").pipe(v0()).subscribe(s=>{t=s.loaded,r=Ce()}));break;case 1:case 0:i.add(jn(e,"loadstart").subscribe(()=>{t=0,r=Ce()}));break}i.add(jn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ce(),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=Ce(),n=0,o=Ce(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,Ce()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ce();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=Ce()}else n+=d.byteLength;o=Ce()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ce()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ce()-o,this.concurrentDownloads.size),n=0,o=Ce());await(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=Sc.get(e);if(Qn(t))return(r=parseInt(t,10))!=null?r:void 0}},FT=yc;import{fillWithDefault as E0,VideoQuality as Gn}from"@vkontakte/videoplayer-shared/es2018";var qT={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:Gn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Gn.Q_720P,trafficSavingLimit:Gn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Gn.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},UT=a=>{var e;return{...E0(a,qT),configName:[...(e=a.configName)!=null?e:[],...qT.configName]}};import{assertNonNullable as Wn,combine as vt,ErrorCategory as Yn,filter as ve,filterChanged as H,fromEvent as Ic,isNonNullable as $0,isNullable as R0,Logger as M0,map as N,mapTo as GT,merge as Ht,now as zn,once as nt,Subject as G,Subscription as WT,tap as Ec,ValueSubject as P,isHigher as D0,isInvariantQuality as YT,flattenObject as jt,throttle as xc,getTraceSubscriptionMethod as zT,Tracer as C0,InternalsExposure as V0}from"@vkontakte/videoplayer-shared/es2018";import{merge as x0,map as P0,filter as HT,isNonNullable as w0}from"@vkontakte/videoplayer-shared/es2018";var Tc=({seekState:a,position$:e})=>x0(a.stateChangeEnded$.pipe(P0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),HT(w0)),e.pipe(HT(()=>a.getState().state==="none")));import{assertNonNullable as A0}from"@vkontakte/videoplayer-shared/es2018";var jT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return A0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as k0,once as L0}from"@vkontakte/videoplayer-shared/es2018";var QT=(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(k0(i=>i.length>0),L0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Kn=class{constructor(e={configName:[]},t=C0.createRootTracer(!1)){this.subscription=new WT;this.logger=new M0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new R("stopped"),seekState:new R({state:"none"}),volume:new R({volume:1,muted:!1}),videoTrack:new R(void 0),videoStream:new R(void 0),audioStream:new R(void 0),autoVideoTrackSwitching:new R(!0),autoVideoTrackLimits:new R({}),isLooped:new R(!1),isLowLatency:new R(!1),playbackRate:new R(1),externalTextTracks:new R([]),internalTextTracks:new R([]),currentTextTrack:new R(void 0),textTrackCuesSettings:new R({}),cameraOrientation:new R({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),predefinedQualityLimitType$:new P("unknown"),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),isLiveEnded$:new P(null),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new G,ready$:new G,started$:new G,playing$:new G,paused$:new G,stopped$:new G,willStart$:new G,willResume$:new G,willPause$:new G,willStop$:new G,willDestruct$:new G,watchCoverageRecord$:new G,watchCoverageLive$:new G,managedError$:new G,fatalError$:new G,fetcherRecoverableError$:new G,ended$:new G,looped$:new G,seeked$:new G,willSeek$:new G,autoplaySoundProhibited$:new G,firstBytes$:new G,loadedMetadata$:new G,firstFrame$:new G,canplay$:new G,log$:new G,fetcherError$:new G,severeStallOccured$:new G};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:qg,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=UT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new gs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new FT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new V0("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,KT.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:Yn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",jt(r)),this.domContainer=jT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new Ka({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],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(),(o=this.internalsExposure)==null||o.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&&!zi()?(this.tracer.log("request play from hidden tab"),Ic(document,"visibilitychange").pipe(nt()).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){Wn(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(ve(r=>r.length>0),nt()).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",jt(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;Wn(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",jt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return QT(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",{...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(R0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return $0(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(Ht(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(sl({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ve(({from:e})=>e==="stopped"),nt()).subscribe(()=>{this.initedAt=zn(),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",jt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Yn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(nt()).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",jt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(N(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(N(n=>n.destination),H()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(vt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(N(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>YT(u)?1:YT(l)?-1:D0(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(H()).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(H((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(H((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(H()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(H()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(H()).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(N(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(Ec(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(vt({hasLiveOffsetByPaused:Ht(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(n=>n.to),H(),N(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(vt({atLiveEdge:vt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Tc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(N(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),H(),Ec(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(N(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(vt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(N(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),H(),Ec(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(N(n=>n.muted),H()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(N(n=>n.volume),H()).subscribe(this.info.volume$)).add(Tc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ht(e.providerOutput.endedEvent$.pipe(GT(!0)),e.providerOutput.seekedEvent$.pipe(GT(!1))).pipe(H()).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(N(n=>({id:n?`No${n}`:"NoProviders",category:Yn.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(nt(),N(n=>n!=null?n:zn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(nt(),N(()=>zn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(nt(),N(()=>zn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ve(({to:n})=>n==="playing"),nt()).subscribe(()=>r.next(!1)));let i=0,s=Ht(e.providerOutput.isBuffering$,t,r).pipe(N(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),H());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(Ht(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(Ht(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(N(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 WT;this.subscription.add(t),this.subscription.add(e.current$.pipe(H((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),nt()).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=Ot(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(Ht(this.desiredState.videoTrack.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(N(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;Wn(this.providerContainer),Wn(e),Fg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Ng(r)),this.providerContainer.current$.subscribe(({type:r})=>Ui("provider",r)),e.duration$.subscribe(r=>Ui("duration",r)),e.availableVideoTracks$.pipe(ve(r=>!!r.length),nt()).subscribe(r=>Ui("tracks",r)),this.events.fatalError$.subscribe(new fe("fatalError")),this.events.managedError$.subscribe(new fe("managedError")),e.position$.subscribe(new fe("position")),e.currentVideoTrack$.pipe(N(r=>r==null?void 0:r.quality)).subscribe(new fe("quality")),this.info.currentBuffer$.subscribe(new fe("buffer")),e.isBuffering$.subscribe(new fe("isBuffering"))].forEach(r=>this.subscription.add(r)),Ui("codecs",Jv())}initTracerSubscription(){let e=zT(this.tracer.log.bind(this.tracer)),t=zT(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(H()).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(vt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ve(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),H((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ve(r=>r>0),H()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ve(r=>r>0),H()).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(vt({currentBuffer:this.info.currentBuffer$.pipe(ve(r=>r.end>0),H((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(H())}).pipe(xc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(H()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(H()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(H()).subscribe(e("canChangePlaybackSpeed"))).add(vt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ve(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),xc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(H(),ve(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(H(),ve(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(H()).subscribe(e("muted"))).add(this.info.volume$.pipe(H()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(H(),ve(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(vt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ve(({throughputEstimation:r,rtt:i})=>!!r&&!!i),xc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(H(),ve(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=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Yn.DOM,message:String(i)})})};this.subscription.add(Ht(Ic(document,"visibilitychange"),Ic(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",jt({quality:t,availableTracks:jt(e),track:jt(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 N4,Observable as F4,Subject as q4,ValueSubject as U4,VideoQuality as H4}from"@vkontakte/videoplayer-shared/es2018";var j4=`@vkontakte/videoplayer-core@${cd}`;export{cs as ChromecastState,ro as HttpConnectionType,F4 as Observable,ke as PlaybackState,Kn as Player,ds as PredefinedQualityLimits,j4 as SDK_VERSION,q4 as Subject,N4 as Subscription,io as Surface,cd as VERSION,U4 as ValueSubject,At as VideoFormat,H4 as VideoQuality};
|
|
124
|
+
`;var Pn=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 En(this.params.fov,this.params.orientation),this.cameraRotationManager=new xn(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(Ey,this.gl.VERTEX_SHADER),r=this.createShader(xy,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 SC,now as Py,Subscription as yC,filter as TC,combine as wy,ValueSubject as Gl,isNonNullable as IC}from"@vkontakte/videoplayer-shared/es2018";var Wl=class{constructor(){this.isSeeked$=new Gl(!1);this.isBuffering$=new Gl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new yC;this.severeStallOccurred$=new Gl(!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(wy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(TC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(wy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(SC(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=Py(),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,IC(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=Py(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},ky=Wl;import{combine as EC,map as xC,observeElementSize as PC,Subscription as wC,ValueSubject as Yl,noop as kC}from"@vkontakte/videoplayer-shared/es2018";var wn=class{constructor(){this.subscription=new wC;this.pipSize$=new Yl(void 0);this.videoSize$=new Yl(void 0);this.elementSize$=new Yl(void 0);this.pictureInPictureWindowRemoveEventListener=kC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(PC(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(EC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(xC(({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 br=class{constructor(e){this.subscription=new DC;this.videoState=new D("stopped");this.droppedFramesManager=new nn;this.stallsManager=new ky;this.elementSizeManager=new wn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new qi;this.audioTrackSwitchHistory=new qi;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"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(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"&&x(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"&&x(this.params.desiredState.playbackState,"paused");return;default:return RC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Pn(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 Be(e.source.url),this.params=e,this.video=Ie(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(ne(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 In({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=Pe(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Ay.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(Ly(l=>!!l.length),$y()).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(zl(l=>l.to.state!=="none"),Va());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Va()),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(Ly(Ry),$y()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(zl(l=>l.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(tt(this.video,t.isLooped,i)),this.subscription.add(xe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Oe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Fe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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($C(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(Rl(h));let m=[];for(let b of h.representations){let g=KS(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($l(p));let h=[];for(let m of p.representations){let b=zS({...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=XS(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(kn(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$,CC(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,My.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});Ry(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let g=!!t.audioStream.getTransition();await 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(Va()).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($l(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Va()).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(Rl(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(zl(({to:l})=>l==="ready"),Va());this.subscription.add(kn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Kl(["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(kn(o,this.player.state$.stateChangeEnded$,Kl(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=kn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Kl(["init"])).pipe(MC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var A,W,_,q,H,k,R,Y,ie,w,T,M,j;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(A=e.videoTrack.getState())==null?void 0:A.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===i),o=t.currentVideoTrack$.getValue(),u=((q=(_=e.videoStream.getState())!=null?_:n&&((W=this.videoTracksMap.get(n))==null?void 0:W.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=it(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=(H=e.audioStream.getState())!=null?H:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(k=[...this.audioStreamsMap.keys()].find(({id:N})=>N===(b==null?void 0:b.id)))!=null?k:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let N=tn(n,c,(R=this.audioStreamsMap.get(g))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(Y=N==null?void 0:N.bitrate)!=null?Y:-1/0)}if(o){let N=tn(o,c,(ie=this.audioStreamsMap.get(g))!=null?ie:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(w=N==null?void 0:N.bitrate)!=null?w:-1/0)}}let y=Vt(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}),S=r?y!=null?y:n:n!=null?n:y,E=g&&Qg(S,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=(M=this.videoTracksMap.get(S))==null?void 0:M.representation,L=E&&((j=this.audioTracksMap.get(E))==null?void 0:j.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(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ay.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),Ee(this.video),this.tracer.end()}};var _a=class extends br{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 Cy,interval as VC,map as Dy}from"@vkontakte/videoplayer-shared/es2018";var Oa=class extends br{constructor(e){super(e),this.liveOffset=new dt,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(Dy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Cy({interval:VC(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(Cy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Dy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=JS(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 _y=C(Us(),1);import{assertNever as Ba,assertNonNullable as Vy,debounce as _C,ErrorCategory as An,filter as OC,isNonNullable as BC,isNullable as NC,map as Ln,merge as FC,Observable as qC,observableFrom as UC,Subscription as HC,videoSizeToQuality as jC}from"@vkontakte/videoplayer-shared/es2018";var Ke={};var ri=(a,e)=>new qC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Na=class{constructor(e){this.subscription=new HC;this.videoState=new D("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:Ba(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ba(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ba(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ba(e)}break;default:Ba(t)}};this.textTracksManager=new Be(e.source.url),this.video=Ie(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(ne(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),Ee(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:An.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,_y.default)(import("hls.js").then(i=>{e||(Ke.Hls=i.default,Ke.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Vy(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Vy(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:An.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Pe(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(tt(this.video,e.isLooped,r)),this.subscription.add(xe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Oe(this.video,e.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Ln(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ri(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:An.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"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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(ri(this.hls,Ke.Events.MANIFEST_PARSED).pipe(Ln(({levels:l})=>l.reduce((c,d)=>{var y,S;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(S=Mt((y=d.attrs.QUALITY)!=null?y:""))!=null?S:jC({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(ri(this.hls,Ke.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(ri(this.hls,Ke.Events.LEVEL_LOADING).pipe(Ln(({url:l})=>ne(l))),t.hostname$),s(ri(this.hls,Ke.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(Lt(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=ri(this.hls,Ke.Events.LEVEL_SWITCHED).pipe(Ln(({level:l})=>n(this.hls.levels[l])));o.pipe(OC(BC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Lt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(NC(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=FC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,UC(["init"])).pipe(_C(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)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:An.DOM,thrown:t}))||(this.videoState.setState("paused"),x(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"),x(this.params.desiredState.playbackState,"stopped",!0)}};var Oy="X-Playback-Duration",Xl=async a=>{var i;let e=await at(a),t=await 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(Oy)?parseInt(e.headers.get(Oy),10):void 0};import{assertNever as tD,combine as rD,debounce as iD,ErrorCategory as Mn,filter as aD,filterChanged as sD,isNonNullable as Fy,isNullable as Cn,map as qy,merge as nD,observableFrom as oD,Subscription as uD,ValueSubject as ec,VideoQuality as lD}from"@vkontakte/videoplayer-shared/es2018";var Zl=C(ru(),1);import{videoSizeToQuality as QC,getExponentialDelay as GC}from"@vkontakte/videoplayer-shared/es2018";var WC=a=>{let e=null;if(a.QUALITY&&(e=Mt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=QC({width:t,height:r})}return e!=null?e:null},YC=(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,Zl.default)(l[1].split(",").map(y=>y.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=WC(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[y,S]=d.RESOLUTION.split("x").map(E=>parseInt(E,10));y&&S&&(g={width:y,height:S})}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,Zl.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}},zC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Jl=0,By=async(a,e=a,t,r)=>{let s=await(await at(a,r)).text();Jl+=1;try{let{qualityManifests:n,textTracks:o}=YC(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Jl<=t.manifestRetryMaxCount)return await zC(GC(Jl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),By(a,e,t)}return{qualityManifests:[],textTracks:[]}},Rn=By;import{isNonNullable as KC,Subscription as XC,throttle as JC,ValueSubject as Ny,Subject as ZC,ErrorCategory as eD}from"@vkontakte/videoplayer-shared/es2018";var $n=class{constructor(e,t,r,i,s){this.subscription=new XC;this.abortControllers={destroy:new he,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Ny(null);this.getCurrentTime$=new Ny(null);this.error$=new ZC;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(JC(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()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=await this.fetchManifestData();await this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let r=await this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}}async parseTextTracks(e,t){for(let r of e){let i=new URL(r.url,t).toString(),n=await(await at(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(KC(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([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new he;let{textTracks:e}=await this.fetchManifestData(),t=await 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}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:eD.WTF,thrown:t,message:e})}};var Fa=class{constructor(e){this.subscription=new uD;this.videoState=new D("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ec([]);this.liveOffset=new dt;this.manifestStartTime$=new ec(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"),x(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"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(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"&&x(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"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return tD(t)}};var r;this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:lD.INVARIANT,url:this.params.source.url};let t=(i,s)=>Rn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new $n(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Be(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:Mn.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:Mn.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(ne(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ec((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:Mn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Pe(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(xe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,r)),s(Fe(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"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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(sD(),qy(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&&Fy(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(ne(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(rD({startTime:this.manifestStartTime$.pipe(aD(Fy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(qy(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=nD(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,oD(["init"])).pipe(iD(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),Ee(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Cn(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=pe(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Xl(n).then(c=>{var d;if(!Cn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Cn(p)||!isFinite(p))&&at(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();Xl(g).then(v=>{Cn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Mn.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=pe(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 cD,debounce as dD,ErrorCategory as tc,fromEvent as rc,isNonNullable as pD,isNullable as hD,map as Uy,merge as Hy,observableFrom as jy,Subscription as mD,ValueSubject as fD,VideoQuality as bD}from"@vkontakte/videoplayer-shared/es2018";var qa=class{constructor(e){this.subscription=new mD;this.videoState=new D("stopped");this.manifests$=new fD([]);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"),x(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"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return cD(t)}};this.textTracksManager=new Be(e.source.url),this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:bD.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(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Rn(pe(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=Pe(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(Uy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(xe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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(ne(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(Uy(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)),!O.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Hy(rc(o,"addtrack"),rc(o,"removetrack"),rc(o,"change"),jy(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Hy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,jy(["init"])).pipe(dD(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}prepare(){var s,n;let e=this.selectManifest();if(hD(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(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(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 Wy=C(Vr(),1),ic=C(Gr(),1),Yy=C(Ct(),1);import{assertNever as gD,assertNonNullable as Qy,debounce as vD,ErrorCategory as Gy,isHigherOrEqual as SD,isLowerOrEqual as yD,isNonNullable as TD,merge as ID,observableFrom as ED,Subscription as xD,map as PD}from"@vkontakte/videoplayer-shared/es2018";var Ua=class{constructor(e){this.subscription=new xD;this.videoState=new D("stopped");this.trackUrls={};this.textTracksManager=new Be;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"),x(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"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return gD(e)}};this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Wy.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,ic.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:Gy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Pe(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(PD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(xe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Oe(this.video,t.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(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&&TD(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=ID(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,ED(["init"])).pipe(vD(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),Ee(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Qy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Qy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ka(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ne(t))}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Gy.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=Vt(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,ic.default)(this.trackUrls).map(d=>d.track);if(!i||!s||Fi({limits:e,lowestAvailableQuality:(c=(0,Yy.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?yD(i,e.max):!0,u=e.min?SD(i,e.min):!0;o&&u||r(e)}};import{assertNever as Ky,debounce as LD,merge as Xy,observableFrom as RD,Subscription as $D,map as Jy,ValueSubject as MD,ErrorCategory as sc,VideoQuality as CD}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as wD}from"@vkontakte/videoplayer-shared/es2018";var zy=["stun:videostun.mycdn.me:80"],kD=1e3,AD=3,ac=()=>null,Dn=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=ac;this.externalStopCallback=ac;this.externalErrorCallback=ac;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}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:zy}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await 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:wD.WTF,message:e.message})}async onPeerConnectionStream(e){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()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await 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),kD)}normalizeOptions(e={}){let t={stunServerList:zy,maxRetryNumber:AD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ha=class{constructor(e){this.videoState=new D("stopped");this.maxSeekBackTime$=new MD(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"),x(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"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Ky(e)}};this.subscription=new $D,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ie(e.container,e.tuning),this.liveStreamClient=new Dn(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),Ee(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:sc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Xy(this.videoState.stateChangeStarted$.pipe(Jy(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Jy(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Pe(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(Fe(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(xe(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 Ky(n.to)}},r)).add(Xy(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,RD(["init"])).pipe(LD(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(ne(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:CD.INVARIANT}),this.video.srcObject=e,x(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:sc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sc.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 Ga,assertNonNullable as Ft,ErrorCategory as Vn,filter as aT,isNonNullable as sT,isNullable as FD,map as qD,merge as UD,once as HD,Subject as ue,Subscription as nT,ValueSubject as V,flattenObject as oT}from"@vkontakte/videoplayer-shared/es2018";import{Observable as DD,map as Zy,Subscription as VD,Subject as _D}from"@vkontakte/videoplayer-shared/es2018";var eT=a=>new DD(e=>{let t=new VD,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(Zy(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(Zy(({type:l})=>l!==void 0)),n=new _D,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 OD,Subscription as BD,combine as ND,filter as rT,once as iT}from"@vkontakte/videoplayer-shared/es2018";function tT(){return new(window.AudioContext||window.webkitAudioContext)}var Qa=class Qa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new he;this.subscriptions=new BD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(rT(s=>!!s.type),iT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){O.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(ND({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(rT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),iT()).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}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=tT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Qa.errorId,category:OD.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Qa.errorId} exception`,thrown:e})}};Qa.errorId="VolumeMultiplierManager";var ii=Qa;var jD={chunkDuration:5e3,maxParallelRequests:5},Wa=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new ue;this.noAvailableProvidersError$=new ue;this.volumeMultiplierError$=new ue;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new ue,fetcherError$:new ue,fetcherRecoverableError$:new ue,warning$:new ue,willSeekEvent$:new ue,soundProhibitedEvent$:new ue,seekedEvent$:new ue,loopedEvent$:new ue,endedEvent$:new ue,firstBytesEvent$:new ue,loadedMetadataEvent$:new ue,firstFrameEvent$:new ue,canplay$:new ue,isLive$:new V(void 0),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),severeStallOccurred$:new ue,availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new nT;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=fy([...gy(this.params.tuning),...by(this.params.tuning)],this.params.tuning).filter(l=>sT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,nc.default)(i,l)),...t.filter(l=>(0,nc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",oT(s)),this.screenFormatsIterator=new ja(s);let n=[...ql(!0),...ql(!1)];this.chromecastFormatsIterator=new ja(n.filter(l=>sT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ii.isSupported()&&(this.volumeMultiplierManager=new ii(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(FD(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Vn.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 Ga(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 Ft(o),new _a({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ft(o),new Oa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ft(o),O.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new qa({...n,source:o}):new Na({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ft(o),new Fa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ft(o),new Ua({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ft(o),new uv({...n,source:o,config:{...jD,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ft(o),new Ha({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ga(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 Ft(o),new Vi({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 Ga(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ga(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 Ga(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{...e,url:r(e.url)}}return(0,lT.default)((0,uT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new nT,t=!1,r=0;return e.add(UD(this.providerOutput.error$.pipe(aT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),eT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(qD(i=>({id:`ProviderHangup:${i}`,category:Vn.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(aT(({to:s})=>s==="playing"),HD()).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===Vn.NETWORK,u=i.category===Vn.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={...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",oT(n))})),e}};import{fromEvent as _n,once as QD,combine as GD,Subscription as cT,ValueSubject as oc,map as WD,filter as YD,isNonNullable as On,now as De,safeStorage as uc}from"@vkontakte/videoplayer-shared/es2018";var zD=5e3,dT="one_video_throughput",pT="one_video_rtt",bt=window.navigator.connection,hT=()=>{let a=bt==null?void 0:bt.downlink;if(On(a)&&a!==10)return a*1e3},mT=()=>{let a=bt==null?void 0:bt.rtt;if(On(a)&&a!==3e3)return a},fT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},lc=class a{constructor(e){this.subscription=new cT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(dT)||(e.useBrowserEstimation?hT():void 0)||zD,r=(s=(i=a.load(pT))!=null?i:e.useBrowserEstimation?mT():void 0)!=null?s:0;if(this.throughput$=new oc(t),this.rtt$=new oc(r),this.rttAdjustedThroughput$=new oc(fT(t,r,e.rttPenaltyRequestSize)),this.throughput=dr.getSmoothedValue(t,-1,e),this.rtt=dr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=hT();u&&this.throughput.next(u);let l=mT();On(l)&&this.rtt.next(l)};bt&&"onchange"in bt&&this.subscription.add(_n(bt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{uc.set(dT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{uc.set(pT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(GD({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(WD(({throughput:n,rtt:o})=>fT(n,o,e.rttPenaltyRequestSize)),YD(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=De(),i=new cT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(_n(e,"progress").pipe(QD()).subscribe(s=>{t=s.loaded,r=De()}));break;case 1:case 0:i.add(_n(e,"loadstart").subscribe(()=>{t=0,r=De()}));break}i.add(_n(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=De(),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=De(),n=0,o=De(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(i,De()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=De();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=De()}else n+=d.byteLength;o=De()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&De()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,De()-o,this.concurrentDownloads.size),n=0,o=De());await(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=uc.get(e);if(On(t))return(r=parseInt(t,10))!=null?r:void 0}},bT=lc;import{fillWithDefault as KD,VideoQuality as Bn}from"@vkontakte/videoplayer-shared/es2018";var gT={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:Bn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Bn.Q_720P,trafficSavingLimit:Bn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Bn.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},vT=a=>{var e;return{...KD(a,gT),configName:[...(e=a.configName)!=null?e:[],...gT.configName]}};import{assertNonNullable as Nn,combine as gt,ErrorCategory as Fn,filter as $,filterChanged as G,fromEvent as dc,isNonNullable as i0,isNullable as a0,Logger as s0,map as U,mapTo as IT,merge as qt,now as qn,once as B,Subject as z,Subscription as ET,tap as xT,ValueSubject as P,isHigher as n0,isInvariantQuality as PT,flattenObject as Ut,throttle as pc,getTraceSubscriptionMethod as wT,Tracer as o0,InternalsExposure as u0}from"@vkontakte/videoplayer-shared/es2018";import{merge as XD,map as JD,filter as ST,isNonNullable as ZD}from"@vkontakte/videoplayer-shared/es2018";var cc=({seekState:a,position$:e})=>XD(a.stateChangeEnded$.pipe(JD(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),ST(ZD)),e.pipe(ST(()=>a.getState().state==="none")));import{assertNonNullable as e0}from"@vkontakte/videoplayer-shared/es2018";var yT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return e0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as t0,once as r0}from"@vkontakte/videoplayer-shared/es2018";var TT=(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(t0(i=>i.length>0),r0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Un=class{constructor(e={configName:[]},t=o0.createRootTracer(!1)){this.subscription=new ET;this.logger=new s0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInited=new P(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new D("stopped"),seekState:new D({state:"none"}),volume:new D({volume:1,muted:!1}),videoTrack:new D(void 0),videoStream:new D(void 0),audioStream:new D(void 0),autoVideoTrackSwitching:new D(!0),autoVideoTrackLimits:new D({}),isLooped:new D(!1),isLowLatency:new D(!1),playbackRate:new D(1),externalTextTracks:new D([]),internalTextTracks:new D([]),currentTextTrack:new D(void 0),textTrackCuesSettings:new D({}),cameraOrientation:new D({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),predefinedQualityLimitType$:new P("unknown"),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,fetcherRecoverableError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z,fetcherError$:new z,severeStallOccured$:new z};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Mg,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=vT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ms({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new bT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new u0("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,kT.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:Fn.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 o,u,l;let{container:s,...n}=e;this.tracer.log("initVideo",Ut(n)),this.domContainer=yT(e),this.chromecastInitializer.contentId=(o=e.meta)==null?void 0:o.videoId,this.providerContainer=new Wa({sources:e.sources,meta:(u=e.meta)!=null?u:{},failoverHosts:(l=e.failoverHosts)!=null?l:[],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?O.isInited$.pipe($(s=>!!s),B()).subscribe(()=>{console.log("Core SDK async start"),t()}):t()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),dc(document,"visibilitychange").pipe(B()).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($(e=>!!e),B()).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($(e=>!!e),B()).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($(e=>!!e),B()).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($(e=>!!e),B()).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($(r=>!!r),B()).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($(t=>!!t),B()).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($(r=>!!r),B()).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($(t=>!!t),B()).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($(t=>!!t),B()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.playerInited.pipe($(t=>!!t),B()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.playerInited.pipe($(t=>!!t),B()).subscribe(()=>{Nn(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($(r=>r.length>0),B()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.playerInited.pipe($(t=>!!t),B()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.playerInited.pipe($(t=>!!t),B()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Ut(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.playerInited.pipe($(t=>!!t),B()).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($(t=>!!t),B()).subscribe(()=>{var r;Nn(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($(t=>!!t),B()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Ut(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.playerInited.pipe($(t=>!!t),B()).subscribe(()=>{var t;TT(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($(t=>!!t),B()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...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($(t=>!!t),B()).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($(r=>!!r),B()).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($(t=>!!t),B()).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($(r=>!!r),B()).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($(e=>e),B()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.playerInited.pipe($(e=>!!e),B()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(a0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return i0(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(qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Ju({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe($(({from:e})=>e==="stopped"),B()).subscribe(()=>{this.initedAt=qn(),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",Ut(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Fn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(B()).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",Ut(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(U(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(U(n=>n.destination),G()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(gt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(U(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>PT(u)?1:PT(l)?-1:n0(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(G()).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(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(G()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(G()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(G()).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(U(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(gt({hasLiveOffsetByPaused:qt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(n=>n.to),G(),U(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(gt({atLiveEdge:gt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:cc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(U(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),G(),xT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(U(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(gt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(U(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),G(),xT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(U(n=>n.muted),G()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(U(n=>n.volume),G()).subscribe(this.info.volume$)).add(cc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(qt(e.providerOutput.endedEvent$.pipe(IT(!0)),e.providerOutput.seekedEvent$.pipe(IT(!1))).pipe(G()).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(U(n=>({id:n?`No${n}`:"NoProviders",category:Fn.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(B(),U(n=>n!=null?n:qn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(B(),U(()=>qn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(B(),U(()=>qn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe($(({to:n})=>n==="playing"),B()).subscribe(()=>r.next(!1)));let i=0,s=qt(e.providerOutput.isBuffering$,t,r).pipe(U(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),G());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(qt(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(qt(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(U(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 ET;this.subscription.add(t),this.subscription.add(e.current$.pipe(G((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe($(r=>r.length>0),B()).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=Vt(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(qt(this.desiredState.videoTrack.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(U(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;Nn(this.providerContainer),Nn(e),$g(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Rg(r)),this.providerContainer.current$.subscribe(({type:r})=>Ni("provider",r)),e.duration$.subscribe(r=>Ni("duration",r)),e.availableVideoTracks$.pipe($(r=>!!r.length),B()).subscribe(r=>Ni("tracks",r)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(U(r=>r==null?void 0:r.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(r=>this.subscription.add(r)),Ni("codecs",O.video.supportedCodecs)}initTracerSubscription(){let e=wT(this.tracer.log.bind(this.tracer)),t=wT(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(G()).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(gt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe($(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),G((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe($(r=>r>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe($(r=>r>0),G()).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(gt({currentBuffer:this.info.currentBuffer$.pipe($(r=>r.end>0),G((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(G())}).pipe(pc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(G()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(G()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(G()).subscribe(e("canChangePlaybackSpeed"))).add(gt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe($(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),pc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),$(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),$(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(G()).subscribe(e("muted"))).add(this.info.volume$.pipe(G()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(G(),$(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(gt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe($(({throughputEstimation:r,rtt:i})=>!!r&&!!i),pc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),$(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=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Fn.DOM,message:String(i)})})};this.subscription.add(qt(dc(document,"visibilitychange"),dc(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",Ut({quality:t,availableTracks:Ut(e),track:Ut(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&&!Gi()}};import{Subscription as J4,Observable as Z4,Subject as eK,ValueSubject as tK,VideoQuality as rK}from"@vkontakte/videoplayer-shared/es2018";var iK=`@vkontakte/videoplayer-core@${Yc}`;export{os as ChromecastState,Yn as HttpConnectionType,Z4 as Observable,Te as PlaybackState,Un as Player,us as PredefinedQualityLimits,iK as SDK_VERSION,eK as Subject,J4 as Subscription,zn as Surface,Yc as VERSION,tK as ValueSubject,ot as VideoFormat,rK as VideoQuality,O as clientChecker,Bi as isMobile};
|