@vkontakte/videoplayer-core 2.0.131-dev.abb2b2b1.0 → 2.0.131-dev.c235b295.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 +93 -32
- package/es2015.esm.js +89 -28
- package/es2018.cjs.js +94 -33
- package/es2018.esm.js +90 -29
- package/es2024.cjs.js +95 -34
- package/es2024.esm.js +94 -33
- package/esnext.cjs.js +95 -34
- package/esnext.esm.js +94 -33
- package/evergreen.esm.js +89 -28
- package/package.json +2 -2
- package/types/providers/DashProviderNew/baseDashProvider.d.ts +57 -0
- package/types/providers/DashProviderNew/consts.d.ts +3 -0
- package/types/providers/DashProviderNew/index.d.ts +2 -0
- package/types/providers/DashProviderNew/lib/ElementSizeManager.d.ts +19 -0
- package/types/providers/DashProviderNew/lib/LiveTextManager.d.ts +23 -0
- package/types/providers/DashProviderNew/lib/buffer.d.ts +117 -0
- package/types/providers/DashProviderNew/lib/fetcher.d.ts +59 -0
- package/types/providers/DashProviderNew/lib/parsers/ietf/index.d.ts +13 -0
- package/types/providers/DashProviderNew/lib/parsers/index.d.ts +3 -0
- package/types/providers/DashProviderNew/lib/parsers/mpd.d.ts +3 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxModel.d.ts +20 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxParser.d.ts +21 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/BoxTypeEnum.d.ts +30 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/box.d.ts +74 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/avc1.d.ts +8 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/equi.d.ts +21 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/ftyp.d.ts +17 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/index.d.ts +26 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdat.d.ts +15 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mdia.d.ts +8 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mfhd.d.ts +11 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/minf.d.ts +8 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moof.d.ts +8 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/moov.d.ts +8 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/mvhd.d.ts +35 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/prhd.d.ts +16 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/proj.d.ts +8 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sidx.d.ts +48 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/st3d.d.ts +23 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stbl.d.ts +8 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/stsd.d.ts +11 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/sv3d.d.ts +8 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfdt.d.ts +17 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tfhd.d.ts +22 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/tkhd.d.ts +42 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/traf.d.ts +8 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trak.d.ts +8 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/trun.d.ts +31 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/unknown.d.ts +6 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/boxes/uuid.d.ts +11 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/fullBox.d.ts +15 -0
- package/types/providers/DashProviderNew/lib/parsers/mpeg/isobmff.d.ts +12 -0
- package/types/providers/DashProviderNew/lib/parsers/webm/ebml.d.ts +76 -0
- package/types/providers/DashProviderNew/lib/parsers/webm/webm.d.ts +3 -0
- package/types/providers/DashProviderNew/lib/player.d.ts +92 -0
- package/types/providers/DashProviderNew/lib/sourceBufferTaskQueue.d.ts +19 -0
- package/types/providers/DashProviderNew/lib/types.d.ts +186 -0
- package/types/providers/DashProviderNew/lib/utils.d.ts +21 -0
- package/types/providers/DashProviderNew/newDashCmafLiveProvider.d.ts +8 -0
- package/types/providers/DashProviderNew/newDashProvider.d.ts +6 -0
- package/types/providers/utils/StallsManager.d.ts +18 -4
- package/types/utils/ClientChecker/services/BrowserChecker.d.ts +2 -0
- package/types/utils/autoSelectTrack.d.ts +6 -3
- package/types/utils/qualityLimits.d.ts +3 -18
- package/types/utils/tuningConfig.d.ts +27 -7
package/es2018.esm.js
CHANGED
|
@@ -1,73 +1,127 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.131-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.131-dev.c235b295.0
|
|
3
|
+
* Tue, 13 May 2025 09:14:14 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-131/doc/
|
|
5
5
|
*/
|
|
6
|
-
var QT=Object.create;var od=Object.defineProperty;var GT=Object.getOwnPropertyDescriptor;var WT=Object.getOwnPropertyNames;var YT=Object.getPrototypeOf,zT=Object.prototype.hasOwnProperty;var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var KT=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of WT(e))!zT.call(a,r)&&r!==t&&od(a,r,{get:()=>e[r],enumerable:!(i=GT(e,r))||i.enumerable});return a};var C=(a,e,t)=>(t=a!=null?QT(YT(a)):{},KT(e||!a||!a.__esModule?od(t,"default",{value:a,enumerable:!0}):t,a));var ie=f((Jn,ld)=>{"use strict";var pr=function(a){return a&&a.Math===Math&&a};ld.exports=pr(typeof globalThis=="object"&&globalThis)||pr(typeof window=="object"&&window)||pr(typeof self=="object"&&self)||pr(typeof global=="object"&&global)||pr(typeof Jn=="object"&&Jn)||function(){return this}()||Function("return this")()});var de=f((P0,cd)=>{"use strict";cd.exports=function(a){try{return!!a()}catch(e){return!0}}});var hr=f((w0,dd)=>{"use strict";var XT=de();dd.exports=!XT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Zn=f((A0,fd)=>{"use strict";var JT=hr(),md=Function.prototype,pd=md.apply,hd=md.call;fd.exports=typeof Reflect=="object"&&Reflect.apply||(JT?hd.bind(pd):function(){return hd.apply(pd,arguments)})});var ne=f((k0,vd)=>{"use strict";var bd=hr(),gd=Function.prototype,eo=gd.call,ZT=bd&&gd.bind.bind(eo,eo);vd.exports=bd?ZT:function(a){return function(){return eo.apply(a,arguments)}}});var Xt=f((R0,yd)=>{"use strict";var Sd=ne(),eI=Sd({}.toString),tI=Sd("".slice);yd.exports=function(a){return tI(eI(a),8,-1)}});var to=f(($0,Td)=>{"use strict";var iI=Xt(),rI=ne();Td.exports=function(a){if(iI(a)==="Function")return rI(a)}});var ee=f((L0,Id)=>{"use strict";var io=typeof document=="object"&&document.all;Id.exports=typeof io=="undefined"&&io!==void 0?function(a){return typeof a=="function"||a===io}:function(a){return typeof a=="function"}});var Le=f((M0,Ed)=>{"use strict";var aI=de();Ed.exports=!aI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Me=f((C0,xd)=>{"use strict";var sI=hr(),cs=Function.prototype.call;xd.exports=sI?cs.bind(cs):function(){return cs.apply(cs,arguments)}});var ro=f(Ad=>{"use strict";var Pd={}.propertyIsEnumerable,wd=Object.getOwnPropertyDescriptor,nI=wd&&!Pd.call({1:2},1);Ad.f=nI?function(e){var t=wd(this,e);return!!t&&t.enumerable}:Pd});var mr=f((V0,kd)=>{"use strict";kd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var $d=f((O0,Rd)=>{"use strict";var oI=ne(),uI=de(),lI=Xt(),ao=Object,cI=oI("".split);Rd.exports=uI(function(){return!ao("z").propertyIsEnumerable(0)})?function(a){return lI(a)==="String"?cI(a,""):ao(a)}:ao});var xi=f((B0,Ld)=>{"use strict";Ld.exports=function(a){return a==null}});var At=f((_0,Md)=>{"use strict";var dI=xi(),pI=TypeError;Md.exports=function(a){if(dI(a))throw new pI("Can't call method on "+a);return a}});var Jt=f((N0,Cd)=>{"use strict";var hI=$d(),mI=At();Cd.exports=function(a){return hI(mI(a))}});var Ce=f((F0,Dd)=>{"use strict";var fI=ee();Dd.exports=function(a){return typeof a=="object"?a!==null:fI(a)}});var Pi=f((q0,Vd)=>{"use strict";Vd.exports={}});var ct=f((U0,Bd)=>{"use strict";var so=Pi(),no=ie(),bI=ee(),Od=function(a){return bI(a)?a:void 0};Bd.exports=function(a,e){return arguments.length<2?Od(so[a])||Od(no[a]):so[a]&&so[a][e]||no[a]&&no[a][e]}});var fr=f((H0,_d)=>{"use strict";var gI=ne();_d.exports=gI({}.isPrototypeOf)});var Zt=f((j0,qd)=>{"use strict";var vI=ie(),Nd=vI.navigator,Fd=Nd&&Nd.userAgent;qd.exports=Fd?String(Fd):""});var uo=f((Q0,Wd)=>{"use strict";var Gd=ie(),oo=Zt(),Ud=Gd.process,Hd=Gd.Deno,jd=Ud&&Ud.versions||Hd&&Hd.version,Qd=jd&&jd.v8,je,ds;Qd&&(je=Qd.split("."),ds=je[0]>0&&je[0]<4?1:+(je[0]+je[1]));!ds&&oo&&(je=oo.match(/Edge\/(\d+)/),(!je||je[1]>=74)&&(je=oo.match(/Chrome\/(\d+)/),je&&(ds=+je[1])));Wd.exports=ds});var lo=f((G0,zd)=>{"use strict";var Yd=uo(),SI=de(),yI=ie(),TI=yI.String;zd.exports=!!Object.getOwnPropertySymbols&&!SI(function(){var a=Symbol("symbol detection");return!TI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Yd&&Yd<41})});var co=f((W0,Kd)=>{"use strict";var II=lo();Kd.exports=II&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var po=f((Y0,Xd)=>{"use strict";var EI=ct(),xI=ee(),PI=fr(),wI=co(),AI=Object;Xd.exports=wI?function(a){return typeof a=="symbol"}:function(a){var e=EI("Symbol");return xI(e)&&PI(e.prototype,AI(a))}});var br=f((z0,Jd)=>{"use strict";var kI=String;Jd.exports=function(a){try{return kI(a)}catch(e){return"Object"}}});var et=f((K0,Zd)=>{"use strict";var RI=ee(),$I=br(),LI=TypeError;Zd.exports=function(a){if(RI(a))return a;throw new LI($I(a)+" is not a function")}});var gr=f((X0,ep)=>{"use strict";var MI=et(),CI=xi();ep.exports=function(a,e){var t=a[e];return CI(t)?void 0:MI(t)}});var ip=f((J0,tp)=>{"use strict";var ho=Me(),mo=ee(),fo=Ce(),DI=TypeError;tp.exports=function(a,e){var t,i;if(e==="string"&&mo(t=a.toString)&&!fo(i=ho(t,a))||mo(t=a.valueOf)&&!fo(i=ho(t,a))||e!=="string"&&mo(t=a.toString)&&!fo(i=ho(t,a)))return i;throw new DI("Can't convert object to primitive value")}});var Qe=f((Z0,rp)=>{"use strict";rp.exports=!0});var np=f((eV,sp)=>{"use strict";var ap=ie(),VI=Object.defineProperty;sp.exports=function(a,e){try{VI(ap,a,{value:e,configurable:!0,writable:!0})}catch(t){ap[a]=e}return e}});var vr=f((tV,lp)=>{"use strict";var OI=Qe(),BI=ie(),_I=np(),op="__core-js_shared__",up=lp.exports=BI[op]||_I(op,{});(up.versions||(up.versions=[])).push({version:"3.38.0",mode:OI?"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 bo=f((iV,dp)=>{"use strict";var cp=vr();dp.exports=function(a,e){return cp[a]||(cp[a]=e||{})}});var wi=f((rV,pp)=>{"use strict";var NI=At(),FI=Object;pp.exports=function(a){return FI(NI(a))}});var Ge=f((aV,hp)=>{"use strict";var qI=ne(),UI=wi(),HI=qI({}.hasOwnProperty);hp.exports=Object.hasOwn||function(e,t){return HI(UI(e),t)}});var go=f((sV,mp)=>{"use strict";var jI=ne(),QI=0,GI=Math.random(),WI=jI(1 .toString);mp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+WI(++QI+GI,36)}});var pe=f((nV,bp)=>{"use strict";var YI=ie(),zI=bo(),fp=Ge(),KI=go(),XI=lo(),JI=co(),Ai=YI.Symbol,vo=zI("wks"),ZI=JI?Ai.for||Ai:Ai&&Ai.withoutSetter||KI;bp.exports=function(a){return fp(vo,a)||(vo[a]=XI&&fp(Ai,a)?Ai[a]:ZI("Symbol."+a)),vo[a]}});var yp=f((oV,Sp)=>{"use strict";var eE=Me(),gp=Ce(),vp=po(),tE=gr(),iE=ip(),rE=pe(),aE=TypeError,sE=rE("toPrimitive");Sp.exports=function(a,e){if(!gp(a)||vp(a))return a;var t=tE(a,sE),i;if(t){if(e===void 0&&(e="default"),i=eE(t,a,e),!gp(i)||vp(i))return i;throw new aE("Can't convert object to primitive value")}return e===void 0&&(e="number"),iE(a,e)}});var So=f((uV,Tp)=>{"use strict";var nE=yp(),oE=po();Tp.exports=function(a){var e=nE(a,"string");return oE(e)?e:e+""}});var ps=f((lV,Ep)=>{"use strict";var uE=ie(),Ip=Ce(),yo=uE.document,lE=Ip(yo)&&Ip(yo.createElement);Ep.exports=function(a){return lE?yo.createElement(a):{}}});var To=f((cV,xp)=>{"use strict";var cE=Le(),dE=de(),pE=ps();xp.exports=!cE&&!dE(function(){return Object.defineProperty(pE("div"),"a",{get:function(){return 7}}).a!==7})});var Ap=f(wp=>{"use strict";var hE=Le(),mE=Me(),fE=ro(),bE=mr(),gE=Jt(),vE=So(),SE=Ge(),yE=To(),Pp=Object.getOwnPropertyDescriptor;wp.f=hE?Pp:function(e,t){if(e=gE(e),t=vE(t),yE)try{return Pp(e,t)}catch(i){}if(SE(e,t))return bE(!mE(fE.f,e,t),e[t])}});var Io=f((pV,kp)=>{"use strict";var TE=de(),IE=ee(),EE=/#|\.prototype\./,Sr=function(a,e){var t=PE[xE(a)];return t===AE?!0:t===wE?!1:IE(e)?TE(e):!!e},xE=Sr.normalize=function(a){return String(a).replace(EE,".").toLowerCase()},PE=Sr.data={},wE=Sr.NATIVE="N",AE=Sr.POLYFILL="P";kp.exports=Sr});var ki=f((hV,$p)=>{"use strict";var Rp=to(),kE=et(),RE=hr(),$E=Rp(Rp.bind);$p.exports=function(a,e){return kE(a),e===void 0?a:RE?$E(a,e):function(){return a.apply(e,arguments)}}});var Eo=f((mV,Lp)=>{"use strict";var LE=Le(),ME=de();Lp.exports=LE&&ME(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var tt=f((fV,Mp)=>{"use strict";var CE=Ce(),DE=String,VE=TypeError;Mp.exports=function(a){if(CE(a))return a;throw new VE(DE(a)+" is not an object")}});var ei=f(Dp=>{"use strict";var OE=Le(),BE=To(),_E=Eo(),hs=tt(),Cp=So(),NE=TypeError,xo=Object.defineProperty,FE=Object.getOwnPropertyDescriptor,Po="enumerable",wo="configurable",Ao="writable";Dp.f=OE?_E?function(e,t,i){if(hs(e),t=Cp(t),hs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Ao in i&&!i[Ao]){var r=FE(e,t);r&&r[Ao]&&(e[t]=i.value,i={configurable:wo in i?i[wo]:r[wo],enumerable:Po in i?i[Po]:r[Po],writable:!1})}return xo(e,t,i)}:xo:function(e,t,i){if(hs(e),t=Cp(t),hs(i),BE)try{return xo(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new NE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ri=f((gV,Vp)=>{"use strict";var qE=Le(),UE=ei(),HE=mr();Vp.exports=qE?function(a,e,t){return UE.f(a,e,HE(1,t))}:function(a,e,t){return a[e]=t,a}});var se=f((vV,Bp)=>{"use strict";var yr=ie(),jE=Zn(),QE=to(),GE=ee(),WE=Ap().f,YE=Io(),$i=Pi(),zE=ki(),Li=Ri(),Op=Ge();vr();var KE=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return jE(a,this,arguments)};return e.prototype=a.prototype,e};Bp.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?yr:r?yr[t]:yr[t]&&yr[t].prototype,o=i?$i:$i[t]||Li($i,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,v;for(h in e)l=YE(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Op(n,h),m=o[h],c&&(a.dontCallGetSet?(v=WE(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?g=zE(p,yr):a.wrap&&c?g=KE(p):s&&GE(p)?g=QE(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&Li(g,"sham",!0),Li(o,h,g),s&&(d=t+"Prototype",Op($i,d)||Li($i,d,{}),Li($i[d],h,p),a.real&&u&&(l||!u[h])&&Li(u,h,p)))}});var Np=f((SV,_p)=>{"use strict";var XE=Math.ceil,JE=Math.floor;_p.exports=Math.trunc||function(e){var t=+e;return(t>0?JE:XE)(t)}});var Tr=f((yV,Fp)=>{"use strict";var ZE=Np();Fp.exports=function(a){var e=+a;return e!==e||e===0?0:ZE(e)}});var Up=f((TV,qp)=>{"use strict";var ex=Tr(),tx=Math.max,ix=Math.min;qp.exports=function(a,e){var t=ex(a);return t<0?tx(t+e,0):ix(t,e)}});var ko=f((IV,Hp)=>{"use strict";var rx=Tr(),ax=Math.min;Hp.exports=function(a){var e=rx(a);return e>0?ax(e,9007199254740991):0}});var Mi=f((EV,jp)=>{"use strict";var sx=ko();jp.exports=function(a){return sx(a.length)}});var Ro=f((xV,Gp)=>{"use strict";var nx=Jt(),ox=Up(),ux=Mi(),Qp=function(a){return function(e,t,i){var r=nx(e),s=ux(r);if(s===0)return!a&&-1;var n=ox(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Gp.exports={includes:Qp(!0),indexOf:Qp(!1)}});var Ir=f((PV,Wp)=>{"use strict";Wp.exports=function(){}});var Yp=f(()=>{"use strict";var lx=se(),cx=Ro().includes,dx=de(),px=Ir(),hx=dx(function(){return!Array(1).includes()});lx({target:"Array",proto:!0,forced:hx},{includes:function(e){return cx(this,e,arguments.length>1?arguments[1]:void 0)}});px("includes")});var kt=f((kV,zp)=>{"use strict";var mx=ct();zp.exports=mx});var Xp=f((RV,Kp)=>{"use strict";Yp();var fx=kt();Kp.exports=fx("Array","includes")});var Zp=f(($V,Jp)=>{"use strict";var bx=Xp();Jp.exports=bx});var Be=f((LV,eh)=>{"use strict";var gx=Zp();eh.exports=gx});var bs=f((HV,uh)=>{"use strict";var Px=bo(),wx=go(),oh=Px("keys");uh.exports=function(a){return oh[a]||(oh[a]=wx(a))}});var ch=f((jV,lh)=>{"use strict";var Ax=de();lh.exports=!Ax(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gs=f((QV,ph)=>{"use strict";var kx=Ge(),Rx=ee(),$x=wi(),Lx=bs(),Mx=ch(),dh=Lx("IE_PROTO"),Mo=Object,Cx=Mo.prototype;ph.exports=Mx?Mo.getPrototypeOf:function(a){var e=$x(a);if(kx(e,dh))return e[dh];var t=e.constructor;return Rx(t)&&e instanceof t?t.prototype:e instanceof Mo?Cx:null}});var vs=f((GV,hh)=>{"use strict";hh.exports={}});var bh=f((WV,fh)=>{"use strict";var Dx=ne(),Co=Ge(),Vx=Jt(),Ox=Ro().indexOf,Bx=vs(),mh=Dx([].push);fh.exports=function(a,e){var t=Vx(a),i=0,r=[],s;for(s in t)!Co(Bx,s)&&Co(t,s)&&mh(r,s);for(;e.length>i;)Co(t,s=e[i++])&&(~Ox(r,s)||mh(r,s));return r}});var Do=f((YV,gh)=>{"use strict";gh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vo=f((zV,vh)=>{"use strict";var _x=bh(),Nx=Do();vh.exports=Object.keys||function(e){return _x(e,Nx)}});var Oo=f((KV,Eh)=>{"use strict";var yh=Le(),Fx=de(),Th=ne(),qx=gs(),Ux=Vo(),Hx=Jt(),jx=ro().f,Ih=Th(jx),Qx=Th([].push),Gx=yh&&Fx(function(){var a=Object.create(null);return a[2]=2,!Ih(a,2)}),Sh=function(a){return function(e){for(var t=Hx(e),i=Ux(t),r=Gx&&qx(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!yh||(r?u in t:Ih(t,u)))&&Qx(o,a?[u,t[u]]:t[u]);return o}};Eh.exports={entries:Sh(!0),values:Sh(!1)}});var xh=f(()=>{"use strict";var Wx=se(),Yx=Oo().entries;Wx({target:"Object",stat:!0},{entries:function(e){return Yx(e)}})});var wh=f((ZV,Ph)=>{"use strict";xh();var zx=Pi();Ph.exports=zx.Object.entries});var kh=f((eO,Ah)=>{"use strict";var Kx=wh();Ah.exports=Kx});var Ci=f((tO,Rh)=>{"use strict";var Xx=kh();Rh.exports=Xx});var ti=f((iO,$h)=>{"use strict";$h.exports={}});var Ch=f((rO,Mh)=>{"use strict";var Jx=ie(),Zx=ee(),Lh=Jx.WeakMap;Mh.exports=Zx(Lh)&&/native code/.test(String(Lh))});var Fo=f((aO,Oh)=>{"use strict";var eP=Ch(),Vh=ie(),tP=Ce(),iP=Ri(),Bo=Ge(),_o=vr(),rP=bs(),aP=vs(),Dh="Object already initialized",No=Vh.TypeError,sP=Vh.WeakMap,Ss,Er,ys,nP=function(a){return ys(a)?Er(a):Ss(a,{})},oP=function(a){return function(e){var t;if(!tP(e)||(t=Er(e)).type!==a)throw new No("Incompatible receiver, "+a+" required");return t}};eP||_o.state?(We=_o.state||(_o.state=new sP),We.get=We.get,We.has=We.has,We.set=We.set,Ss=function(a,e){if(We.has(a))throw new No(Dh);return e.facade=a,We.set(a,e),e},Er=function(a){return We.get(a)||{}},ys=function(a){return We.has(a)}):(ii=rP("state"),aP[ii]=!0,Ss=function(a,e){if(Bo(a,ii))throw new No(Dh);return e.facade=a,iP(a,ii,e),e},Er=function(a){return Bo(a,ii)?a[ii]:{}},ys=function(a){return Bo(a,ii)});var We,ii;Oh.exports={set:Ss,get:Er,has:ys,enforce:nP,getterFor:oP}});var Ho=f((sO,_h)=>{"use strict";var qo=Le(),uP=Ge(),Bh=Function.prototype,lP=qo&&Object.getOwnPropertyDescriptor,Uo=uP(Bh,"name"),cP=Uo&&function(){}.name==="something",dP=Uo&&(!qo||qo&&lP(Bh,"name").configurable);_h.exports={EXISTS:Uo,PROPER:cP,CONFIGURABLE:dP}});var Fh=f(Nh=>{"use strict";var pP=Le(),hP=Eo(),mP=ei(),fP=tt(),bP=Jt(),gP=Vo();Nh.f=pP&&!hP?Object.defineProperties:function(e,t){fP(e);for(var i=bP(t),r=gP(t),s=r.length,n=0,o;s>n;)mP.f(e,o=r[n++],i[o]);return e}});var jo=f((oO,qh)=>{"use strict";var vP=ct();qh.exports=vP("document","documentElement")});var Yo=f((uO,Yh)=>{"use strict";var SP=tt(),yP=Fh(),Uh=Do(),TP=vs(),IP=jo(),EP=ps(),xP=bs(),Hh=">",jh="<",Go="prototype",Wo="script",Gh=xP("IE_PROTO"),Qo=function(){},Wh=function(a){return jh+Wo+Hh+a+jh+"/"+Wo+Hh},Qh=function(a){a.write(Wh("")),a.close();var e=a.parentWindow.Object;return a=null,e},PP=function(){var a=EP("iframe"),e="java"+Wo+":",t;return a.style.display="none",IP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Wh("document.F=Object")),t.close(),t.F},Ts,Is=function(){try{Ts=new ActiveXObject("htmlfile")}catch(e){}Is=typeof document!="undefined"?document.domain&&Ts?Qh(Ts):PP():Qh(Ts);for(var a=Uh.length;a--;)delete Is[Go][Uh[a]];return Is()};TP[Gh]=!0;Yh.exports=Object.create||function(e,t){var i;return e!==null?(Qo[Go]=SP(e),i=new Qo,Qo[Go]=null,i[Gh]=e):i=Is(),t===void 0?i:yP.f(i,t)}});var Di=f((lO,zh)=>{"use strict";var wP=Ri();zh.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:wP(a,e,t),a}});var Jo=f((cO,Jh)=>{"use strict";var AP=de(),kP=ee(),RP=Ce(),$P=Yo(),Kh=gs(),LP=Di(),MP=pe(),CP=Qe(),Xo=MP("iterator"),Xh=!1,dt,zo,Ko;[].keys&&(Ko=[].keys(),"next"in Ko?(zo=Kh(Kh(Ko)),zo!==Object.prototype&&(dt=zo)):Xh=!0);var DP=!RP(dt)||AP(function(){var a={};return dt[Xo].call(a)!==a});DP?dt={}:CP&&(dt=$P(dt));kP(dt[Xo])||LP(dt,Xo,function(){return this});Jh.exports={IteratorPrototype:dt,BUGGY_SAFARI_ITERATORS:Xh}});var Es=f((dO,em)=>{"use strict";var VP=pe(),OP=VP("toStringTag"),Zh={};Zh[OP]="z";em.exports=String(Zh)==="[object z]"});var xr=f((pO,tm)=>{"use strict";var BP=Es(),_P=ee(),xs=Xt(),NP=pe(),FP=NP("toStringTag"),qP=Object,UP=xs(function(){return arguments}())==="Arguments",HP=function(a,e){try{return a[e]}catch(t){}};tm.exports=BP?xs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=HP(e=qP(a),FP))=="string"?t:UP?xs(e):(i=xs(e))==="Object"&&_P(e.callee)?"Arguments":i}});var rm=f((hO,im)=>{"use strict";var jP=Es(),QP=xr();im.exports=jP?{}.toString:function(){return"[object "+QP(this)+"]"}});var Pr=f((mO,sm)=>{"use strict";var GP=Es(),WP=ei().f,YP=Ri(),zP=Ge(),KP=rm(),XP=pe(),am=XP("toStringTag");sm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(zP(r,am)||WP(r,am,{configurable:!0,value:e}),i&&!GP&&YP(r,"toString",KP))}});var om=f((fO,nm)=>{"use strict";var JP=Jo().IteratorPrototype,ZP=Yo(),ew=mr(),tw=Pr(),iw=ti(),rw=function(){return this};nm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=ZP(JP,{next:ew(+!i,t)}),tw(a,r,!1,!0),iw[r]=rw,a}});var lm=f((bO,um)=>{"use strict";var aw=ne(),sw=et();um.exports=function(a,e,t){try{return aw(sw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var dm=f((gO,cm)=>{"use strict";var nw=Ce();cm.exports=function(a){return nw(a)||a===null}});var hm=f((vO,pm)=>{"use strict";var ow=dm(),uw=String,lw=TypeError;pm.exports=function(a){if(ow(a))return a;throw new lw("Can't set "+uw(a)+" as a prototype")}});var Zo=f((SO,mm)=>{"use strict";var cw=lm(),dw=Ce(),pw=At(),hw=hm();mm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=cw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return pw(r),hw(s),dw(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Pm=f((yO,xm)=>{"use strict";var mw=se(),fw=Me(),Ps=Qe(),Im=Ho(),bw=ee(),gw=om(),fm=gs(),bm=Zo(),vw=Pr(),Sw=Ri(),eu=Di(),yw=pe(),gm=ti(),Em=Jo(),Tw=Im.PROPER,Iw=Im.CONFIGURABLE,vm=Em.IteratorPrototype,ws=Em.BUGGY_SAFARI_ITERATORS,wr=yw("iterator"),Sm="keys",Ar="values",ym="entries",Tm=function(){return this};xm.exports=function(a,e,t,i,r,s,n){gw(t,e,i);var o=function(v){if(v===r&&h)return h;if(!ws&&v&&v in c)return c[v];switch(v){case Sm:return function(){return new t(this,v)};case Ar:return function(){return new t(this,v)};case ym:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[wr]||c["@@iterator"]||r&&c[r],h=!ws&&d||o(r),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=fm(p.call(new a)),m!==Object.prototype&&m.next&&(!Ps&&fm(m)!==vm&&(bm?bm(m,vm):bw(m[wr])||eu(m,wr,Tm)),vw(m,u,!0,!0),Ps&&(gm[u]=Tm))),Tw&&r===Ar&&d&&d.name!==Ar&&(!Ps&&Iw?Sw(c,"name",Ar):(l=!0,h=function(){return fw(d,this)})),r)if(b={values:o(Ar),keys:s?h:o(Sm),entries:o(ym)},n)for(g in b)(ws||l||!(g in c))&&eu(c,g,b[g]);else mw({target:e,proto:!0,forced:ws||l},b);return(!Ps||n)&&c[wr]!==h&&eu(c,wr,h,{name:r}),gm[e]=h,b}});var Am=f((TO,wm)=>{"use strict";wm.exports=function(a,e){return{value:a,done:e}}});var iu=f((IO,Mm)=>{"use strict";var Ew=Jt(),tu=Ir(),km=ti(),$m=Fo(),xw=ei().f,Pw=Pm(),As=Am(),ww=Qe(),Aw=Le(),Lm="Array Iterator",kw=$m.set,Rw=$m.getterFor(Lm);Mm.exports=Pw(Array,"Array",function(a,e){kw(this,{type:Lm,target:Ew(a),index:0,kind:e})},function(){var a=Rw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,As(void 0,!0);switch(a.kind){case"keys":return As(t,!1);case"values":return As(e[t],!1)}return As([t,e[t]],!1)},"values");var Rm=km.Arguments=km.Array;tu("keys");tu("values");tu("entries");if(!ww&&Aw&&Rm.name!=="values")try{xw(Rm,"name",{value:"values"})}catch(a){}});var Dm=f((EO,Cm)=>{"use strict";var $w=pe(),Lw=ti(),Mw=$w("iterator"),Cw=Array.prototype;Cm.exports=function(a){return a!==void 0&&(Lw.Array===a||Cw[Mw]===a)}});var ru=f((xO,Om)=>{"use strict";var Dw=xr(),Vm=gr(),Vw=xi(),Ow=ti(),Bw=pe(),_w=Bw("iterator");Om.exports=function(a){if(!Vw(a))return Vm(a,_w)||Vm(a,"@@iterator")||Ow[Dw(a)]}});var _m=f((PO,Bm)=>{"use strict";var Nw=Me(),Fw=et(),qw=tt(),Uw=br(),Hw=ru(),jw=TypeError;Bm.exports=function(a,e){var t=arguments.length<2?Hw(a):e;if(Fw(t))return qw(Nw(t,a));throw new jw(Uw(a)+" is not iterable")}});var qm=f((wO,Fm)=>{"use strict";var Qw=Me(),Nm=tt(),Gw=gr();Fm.exports=function(a,e,t){var i,r;Nm(a);try{if(i=Gw(a,"return"),!i){if(e==="throw")throw t;return t}i=Qw(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Nm(i),t}});var Rs=f((AO,Qm)=>{"use strict";var Ww=ki(),Yw=Me(),zw=tt(),Kw=br(),Xw=Dm(),Jw=Mi(),Um=fr(),Zw=_m(),eA=ru(),Hm=qm(),tA=TypeError,ks=function(a,e){this.stopped=a,this.result=e},jm=ks.prototype;Qm.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Ww(e,i),l,c,d,h,p,m,b,g=function(S){return l&&Hm(l,"normal",S),new ks(!0,S)},v=function(S){return r?(zw(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=eA(a),!c)throw new tA(Kw(a)+" is not iterable");if(Xw(c)){for(d=0,h=Jw(a);h>d;d++)if(p=v(a[d]),p&&Um(jm,p))return p;return new ks(!1)}l=Zw(a,c)}for(m=s?a.next:l.next;!(b=Yw(m,l)).done;){try{p=v(b.value)}catch(S){Hm(l,"throw",S)}if(typeof p=="object"&&p&&Um(jm,p))return p}return new ks(!1)}});var Wm=f((kO,Gm)=>{"use strict";var iA=Le(),rA=ei(),aA=mr();Gm.exports=function(a,e,t){iA?rA.f(a,e,aA(0,t)):a[e]=t}});var Ym=f(()=>{"use strict";var sA=se(),nA=Rs(),oA=Wm();sA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return nA(e,function(i,r){oA(t,i,r)},{AS_ENTRIES:!0}),t}})});var Km=f((LO,zm)=>{"use strict";iu();Ym();var uA=Pi();zm.exports=uA.Object.fromEntries});var Jm=f((MO,Xm)=>{"use strict";Xm.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 ef=f(()=>{"use strict";iu();var lA=Jm(),cA=ie(),dA=Pr(),Zm=ti();for($s in lA)dA(cA[$s],$s),Zm[$s]=Zm.Array;var $s});var rf=f((VO,tf)=>{"use strict";var pA=Km();ef();tf.exports=pA});var au=f((OO,af)=>{"use strict";var hA=rf();af.exports=hA});var sf=f(()=>{"use strict"});var su=f((NO,nf)=>{"use strict";var kr=ie(),mA=Zt(),fA=Xt(),Ls=function(a){return mA.slice(0,a.length)===a};nf.exports=function(){return Ls("Bun/")?"BUN":Ls("Cloudflare-Workers")?"CLOUDFLARE":Ls("Deno/")?"DENO":Ls("Node.js/")?"NODE":kr.Bun&&typeof Bun.version=="string"?"BUN":kr.Deno&&typeof Deno.version=="object"?"DENO":fA(kr.process)==="process"?"NODE":kr.window&&kr.document?"BROWSER":"REST"}()});var Ms=f((FO,of)=>{"use strict";var bA=su();of.exports=bA==="NODE"});var lf=f((qO,uf)=>{"use strict";var gA=ei();uf.exports=function(a,e,t){return gA.f(a,e,t)}});var pf=f((UO,df)=>{"use strict";var vA=ct(),SA=lf(),yA=pe(),TA=Le(),cf=yA("species");df.exports=function(a){var e=vA(a);TA&&e&&!e[cf]&&SA(e,cf,{configurable:!0,get:function(){return this}})}});var mf=f((HO,hf)=>{"use strict";var IA=fr(),EA=TypeError;hf.exports=function(a,e){if(IA(e,a))return a;throw new EA("Incorrect invocation")}});var ou=f((jO,ff)=>{"use strict";var xA=ne(),PA=ee(),nu=vr(),wA=xA(Function.toString);PA(nu.inspectSource)||(nu.inspectSource=function(a){return wA(a)});ff.exports=nu.inspectSource});var lu=f((QO,yf)=>{"use strict";var AA=ne(),kA=de(),bf=ee(),RA=xr(),$A=ct(),LA=ou(),gf=function(){},vf=$A("Reflect","construct"),uu=/^\s*(?:class|function)\b/,MA=AA(uu.exec),CA=!uu.test(gf),Rr=function(e){if(!bf(e))return!1;try{return vf(gf,[],e),!0}catch(t){return!1}},Sf=function(e){if(!bf(e))return!1;switch(RA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return CA||!!MA(uu,LA(e))}catch(t){return!0}};Sf.sham=!0;yf.exports=!vf||kA(function(){var a;return Rr(Rr.call)||!Rr(Object)||!Rr(function(){a=!0})||a})?Sf:Rr});var If=f((GO,Tf)=>{"use strict";var DA=lu(),VA=br(),OA=TypeError;Tf.exports=function(a){if(DA(a))return a;throw new OA(VA(a)+" is not a constructor")}});var cu=f((WO,xf)=>{"use strict";var Ef=tt(),BA=If(),_A=xi(),NA=pe(),FA=NA("species");xf.exports=function(a,e){var t=Ef(a).constructor,i;return t===void 0||_A(i=Ef(t)[FA])?e:BA(i)}});var wf=f((YO,Pf)=>{"use strict";var qA=ne();Pf.exports=qA([].slice)});var kf=f((zO,Af)=>{"use strict";var UA=TypeError;Af.exports=function(a,e){if(a<e)throw new UA("Not enough arguments");return a}});var du=f((KO,Rf)=>{"use strict";var HA=Zt();Rf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(HA)});var yu=f((XO,_f)=>{"use strict";var De=ie(),jA=Zn(),QA=ki(),$f=ee(),GA=Ge(),Bf=de(),Lf=jo(),WA=wf(),Mf=ps(),YA=kf(),zA=du(),KA=Ms(),gu=De.setImmediate,vu=De.clearImmediate,XA=De.process,pu=De.Dispatch,JA=De.Function,Cf=De.MessageChannel,ZA=De.String,hu=0,$r={},Df="onreadystatechange",Lr,ri,mu,fu;Bf(function(){Lr=De.location});var Su=function(a){if(GA($r,a)){var e=$r[a];delete $r[a],e()}},bu=function(a){return function(){Su(a)}},Vf=function(a){Su(a.data)},Of=function(a){De.postMessage(ZA(a),Lr.protocol+"//"+Lr.host)};(!gu||!vu)&&(gu=function(e){YA(arguments.length,1);var t=$f(e)?e:JA(e),i=WA(arguments,1);return $r[++hu]=function(){jA(t,void 0,i)},ri(hu),hu},vu=function(e){delete $r[e]},KA?ri=function(a){XA.nextTick(bu(a))}:pu&&pu.now?ri=function(a){pu.now(bu(a))}:Cf&&!zA?(mu=new Cf,fu=mu.port2,mu.port1.onmessage=Vf,ri=QA(fu.postMessage,fu)):De.addEventListener&&$f(De.postMessage)&&!De.importScripts&&Lr&&Lr.protocol!=="file:"&&!Bf(Of)?(ri=Of,De.addEventListener("message",Vf,!1)):Df in Mf("script")?ri=function(a){Lf.appendChild(Mf("script"))[Df]=function(){Lf.removeChild(this),Su(a)}}:ri=function(a){setTimeout(bu(a),0)});_f.exports={set:gu,clear:vu}});var qf=f((JO,Ff)=>{"use strict";var Nf=ie(),ek=Le(),tk=Object.getOwnPropertyDescriptor;Ff.exports=function(a){if(!ek)return Nf[a];var e=tk(Nf,a);return e&&e.value}});var Tu=f((ZO,Hf)=>{"use strict";var Uf=function(){this.head=null,this.tail=null};Uf.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}}};Hf.exports=Uf});var Qf=f((eB,jf)=>{"use strict";var ik=Zt();jf.exports=/ipad|iphone|ipod/i.test(ik)&&typeof Pebble!="undefined"});var Wf=f((tB,Gf)=>{"use strict";var rk=Zt();Gf.exports=/web0s(?!.*chrome)/i.test(rk)});var eb=f((iB,Zf)=>{"use strict";var Oi=ie(),ak=qf(),Yf=ki(),Iu=yu().set,sk=Tu(),nk=du(),ok=Qf(),uk=Wf(),Eu=Ms(),zf=Oi.MutationObserver||Oi.WebKitMutationObserver,Kf=Oi.document,Xf=Oi.process,Cs=Oi.Promise,wu=ak("queueMicrotask"),Vi,xu,Pu,Ds,Jf;wu||(Mr=new sk,Cr=function(){var a,e;for(Eu&&(a=Xf.domain)&&a.exit();e=Mr.get();)try{e()}catch(t){throw Mr.head&&Vi(),t}a&&a.enter()},!nk&&!Eu&&!uk&&zf&&Kf?(xu=!0,Pu=Kf.createTextNode(""),new zf(Cr).observe(Pu,{characterData:!0}),Vi=function(){Pu.data=xu=!xu}):!ok&&Cs&&Cs.resolve?(Ds=Cs.resolve(void 0),Ds.constructor=Cs,Jf=Yf(Ds.then,Ds),Vi=function(){Jf(Cr)}):Eu?Vi=function(){Xf.nextTick(Cr)}:(Iu=Yf(Iu,Oi),Vi=function(){Iu(Cr)}),wu=function(a){Mr.head||Vi(),Mr.add(a)});var Mr,Cr;Zf.exports=wu});var ib=f((rB,tb)=>{"use strict";tb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Vs=f((aB,rb)=>{"use strict";rb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ai=f((sB,ab)=>{"use strict";var lk=ie();ab.exports=lk.Promise});var Bi=f((nB,ub)=>{"use strict";var ck=ie(),Dr=ai(),dk=ee(),pk=Io(),hk=ou(),mk=pe(),sb=su(),fk=Qe(),Au=uo(),nb=Dr&&Dr.prototype,bk=mk("species"),ku=!1,ob=dk(ck.PromiseRejectionEvent),gk=pk("Promise",function(){var a=hk(Dr),e=a!==String(Dr);if(!e&&Au===66||fk&&!(nb.catch&&nb.finally))return!0;if(!Au||Au<51||!/native code/.test(a)){var t=new Dr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[bk]=i,ku=t.then(function(){})instanceof i,!ku)return!0}return!e&&(sb==="BROWSER"||sb==="DENO")&&!ob});ub.exports={CONSTRUCTOR:gk,REJECTION_EVENT:ob,SUBCLASSING:ku}});var _i=f((oB,cb)=>{"use strict";var lb=et(),vk=TypeError,Sk=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new vk("Bad Promise constructor");e=i,t=r}),this.resolve=lb(e),this.reject=lb(t)};cb.exports.f=function(a){return new Sk(a)}});var Rb=f(()=>{"use strict";var yk=se(),Tk=Qe(),Ns=Ms(),Rt=ie(),Ui=Me(),db=Di(),pb=Zo(),Ik=Pr(),Ek=pf(),xk=et(),_s=ee(),Pk=Ce(),wk=mf(),Ak=cu(),gb=yu().set,Cu=eb(),kk=ib(),Rk=Vs(),$k=Tu(),vb=Fo(),Fs=ai(),Du=Bi(),Sb=_i(),qs="Promise",yb=Du.CONSTRUCTOR,Lk=Du.REJECTION_EVENT,Mk=Du.SUBCLASSING,Ru=vb.getterFor(qs),Ck=vb.set,Ni=Fs&&Fs.prototype,si=Fs,Os=Ni,Tb=Rt.TypeError,$u=Rt.document,Vu=Rt.process,Lu=Sb.f,Dk=Lu,Vk=!!($u&&$u.createEvent&&Rt.dispatchEvent),Ib="unhandledrejection",Ok="rejectionhandled",hb=0,Eb=1,Bk=2,Ou=1,xb=2,Bs,mb,_k,fb,Pb=function(a){var e;return Pk(a)&&_s(e=a.then)?e:!1},wb=function(a,e){var t=e.value,i=e.state===Eb,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===xb&&Fk(e),e.rejection=Ou),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Tb("Promise-chain cycle")):(l=Pb(u))?Ui(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Ab=function(a,e){a.notified||(a.notified=!0,Cu(function(){for(var t=a.reactions,i;i=t.get();)wb(i,a);a.notified=!1,e&&!a.rejection&&Nk(a)}))},kb=function(a,e,t){var i,r;Vk?(i=$u.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Rt.dispatchEvent(i)):i={promise:e,reason:t},!Lk&&(r=Rt["on"+a])?r(i):a===Ib&&kk("Unhandled promise rejection",t)},Nk=function(a){Ui(gb,Rt,function(){var e=a.facade,t=a.value,i=bb(a),r;if(i&&(r=Rk(function(){Ns?Vu.emit("unhandledRejection",t,e):kb(Ib,e,t)}),a.rejection=Ns||bb(a)?xb:Ou,r.error))throw r.value})},bb=function(a){return a.rejection!==Ou&&!a.parent},Fk=function(a){Ui(gb,Rt,function(){var e=a.facade;Ns?Vu.emit("rejectionHandled",e):kb(Ok,e,a.value)})},Fi=function(a,e,t){return function(i){a(e,i,t)}},qi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Bk,Ab(a,!0))},Mu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Tb("Promise can't be resolved itself");var i=Pb(e);i?Cu(function(){var r={done:!1};try{Ui(i,e,Fi(Mu,r,a),Fi(qi,r,a))}catch(s){qi(r,s,a)}}):(a.value=e,a.state=Eb,Ab(a,!1))}catch(r){qi({done:!1},r,a)}}};if(yb&&(si=function(e){wk(this,Os),xk(e),Ui(Bs,this);var t=Ru(this);try{e(Fi(Mu,t),Fi(qi,t))}catch(i){qi(t,i)}},Os=si.prototype,Bs=function(e){Ck(this,{type:qs,done:!1,notified:!1,parent:!1,reactions:new $k,rejection:!1,state:hb,value:void 0})},Bs.prototype=db(Os,"then",function(e,t){var i=Ru(this),r=Lu(Ak(this,si));return i.parent=!0,r.ok=_s(e)?e:!0,r.fail=_s(t)&&t,r.domain=Ns?Vu.domain:void 0,i.state===hb?i.reactions.add(r):Cu(function(){wb(r,i)}),r.promise}),mb=function(){var a=new Bs,e=Ru(a);this.promise=a,this.resolve=Fi(Mu,e),this.reject=Fi(qi,e)},Sb.f=Lu=function(a){return a===si||a===_k?new mb(a):Dk(a)},!Tk&&_s(Fs)&&Ni!==Object.prototype)){fb=Ni.then,Mk||db(Ni,"then",function(e,t){var i=this;return new si(function(r,s){Ui(fb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Ni.constructor}catch(a){}pb&&pb(Ni,Os)}yk({global:!0,constructor:!0,wrap:!0,forced:yb},{Promise:si});Ik(si,qs,!1,!0);Ek(qs)});var Db=f((cB,Cb)=>{"use strict";var qk=pe(),Lb=qk("iterator"),Mb=!1;try{$b=0,Bu={next:function(){return{done:!!$b++}},return:function(){Mb=!0}},Bu[Lb]=function(){return this},Array.from(Bu,function(){throw 2})}catch(a){}var $b,Bu;Cb.exports=function(a,e){try{if(!e&&!Mb)return!1}catch(r){return!1}var t=!1;try{var i={};i[Lb]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var _u=f((dB,Vb)=>{"use strict";var Uk=ai(),Hk=Db(),jk=Bi().CONSTRUCTOR;Vb.exports=jk||!Hk(function(a){Uk.all(a).then(void 0,function(){})})});var Ob=f(()=>{"use strict";var Qk=se(),Gk=Me(),Wk=et(),Yk=_i(),zk=Vs(),Kk=Rs(),Xk=_u();Qk({target:"Promise",stat:!0,forced:Xk},{all:function(e){var t=this,i=Yk.f(t),r=i.resolve,s=i.reject,n=zk(function(){var o=Wk(t.resolve),u=[],l=0,c=1;Kk(e,function(d){var h=l++,p=!1;c++,Gk(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var _b=f(()=>{"use strict";var Jk=se(),Zk=Qe(),eR=Bi().CONSTRUCTOR,Fu=ai(),tR=ct(),iR=ee(),rR=Di(),Bb=Fu&&Fu.prototype;Jk({target:"Promise",proto:!0,forced:eR,real:!0},{catch:function(a){return this.then(void 0,a)}});!Zk&&iR(Fu)&&(Nu=tR("Promise").prototype.catch,Bb.catch!==Nu&&rR(Bb,"catch",Nu,{unsafe:!0}));var Nu});var Nb=f(()=>{"use strict";var aR=se(),sR=Me(),nR=et(),oR=_i(),uR=Vs(),lR=Rs(),cR=_u();aR({target:"Promise",stat:!0,forced:cR},{race:function(e){var t=this,i=oR.f(t),r=i.reject,s=uR(function(){var n=nR(t.resolve);lR(e,function(o){sR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Fb=f(()=>{"use strict";var dR=se(),pR=_i(),hR=Bi().CONSTRUCTOR;dR({target:"Promise",stat:!0,forced:hR},{reject:function(e){var t=pR.f(this),i=t.reject;return i(e),t.promise}})});var qu=f((yB,qb)=>{"use strict";var mR=tt(),fR=Ce(),bR=_i();qb.exports=function(a,e){if(mR(a),fR(e)&&e.constructor===a)return e;var t=bR.f(a),i=t.resolve;return i(e),t.promise}});var jb=f(()=>{"use strict";var gR=se(),vR=ct(),Ub=Qe(),SR=ai(),Hb=Bi().CONSTRUCTOR,yR=qu(),TR=vR("Promise"),IR=Ub&&!Hb;gR({target:"Promise",stat:!0,forced:Ub||Hb},{resolve:function(e){return yR(IR&&this===TR?SR:this,e)}})});var Qb=f(()=>{"use strict";Rb();Ob();_b();Nb();Fb();jb()});var zb=f(()=>{"use strict";var ER=se(),xR=Qe(),Us=ai(),PR=de(),Wb=ct(),Yb=ee(),wR=cu(),Gb=qu(),AR=Di(),Hu=Us&&Us.prototype,kR=!!Us&&PR(function(){Hu.finally.call({then:function(){}},function(){})});ER({target:"Promise",proto:!0,real:!0,forced:kR},{finally:function(a){var e=wR(this,Wb("Promise")),t=Yb(a);return this.then(t?function(i){return Gb(e,a()).then(function(){return i})}:a,t?function(i){return Gb(e,a()).then(function(){throw i})}:a)}});!xR&&Yb(Us)&&(Uu=Wb("Promise").prototype.finally,Hu.finally!==Uu&&AR(Hu,"finally",Uu,{unsafe:!0}));var Uu});var Xb=f((AB,Kb)=>{"use strict";sf();Qb();zb();var RR=kt();Kb.exports=RR("Promise","finally")});var Zb=f((kB,Jb)=>{"use strict";var $R=Xb();Jb.exports=$R});var Hs=f((RB,eg)=>{"use strict";var LR=Zb();eg.exports=LR});var hg=f(()=>{"use strict";var QR=se(),GR=Oo().values;QR({target:"Object",stat:!0},{values:function(e){return GR(e)}})});var fg=f((h_,mg)=>{"use strict";hg();var WR=Pi();mg.exports=WR.Object.values});var gg=f((m_,bg)=>{"use strict";var YR=fg();bg.exports=YR});var ji=f((f_,vg)=>{"use strict";var zR=gg();vg.exports=zR});var Vg=f(()=>{"use strict";var S$=se(),y$=wi(),T$=Mi(),I$=Tr(),E$=Ir();S$({target:"Array",proto:!0},{at:function(e){var t=y$(this),i=T$(t),r=I$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});E$("at")});var Bg=f((xN,Og)=>{"use strict";Vg();var x$=kt();Og.exports=x$("Array","at")});var Ng=f((PN,_g)=>{"use strict";var P$=Bg();_g.exports=P$});var Dt=f((wN,Fg)=>{"use strict";var w$=Ng();Fg.exports=w$});var fl=f((dq,Tv)=>{"use strict";var lL=Xt();Tv.exports=Array.isArray||function(e){return lL(e)==="Array"}});var Ev=f((pq,Iv)=>{"use strict";var cL=TypeError,dL=9007199254740991;Iv.exports=function(a){if(a>dL)throw cL("Maximum allowed index exceeded");return a}});var wv=f((hq,Pv)=>{"use strict";var pL=fl(),hL=Mi(),mL=Ev(),fL=ki(),xv=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?fL(n,o):!1,d,h;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&pL(d)?(h=hL(d),u=xv(a,e,d,h,u,s-1)-1):(mL(u+1),a[u]=d),u++),l++;return u};Pv.exports=xv});var $v=f((mq,Rv)=>{"use strict";var Av=fl(),bL=lu(),gL=Ce(),vL=pe(),SL=vL("species"),kv=Array;Rv.exports=function(a){var e;return Av(a)&&(e=a.constructor,bL(e)&&(e===kv||Av(e.prototype))?e=void 0:gL(e)&&(e=e[SL],e===null&&(e=void 0))),e===void 0?kv:e}});var Mv=f((fq,Lv)=>{"use strict";var yL=$v();Lv.exports=function(a,e){return new(yL(a))(e===0?0:e)}});var Cv=f(()=>{"use strict";var TL=se(),IL=wv(),EL=et(),xL=wi(),PL=Mi(),wL=Mv();TL({target:"Array",proto:!0},{flatMap:function(e){var t=xL(this),i=PL(t),r;return EL(e),r=wL(t,0),r.length=IL(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Dv=f(()=>{"use strict";var AL=Ir();AL("flatMap")});var Ov=f((yq,Vv)=>{"use strict";Cv();Dv();var kL=kt();Vv.exports=kL("Array","flatMap")});var _v=f((Tq,Bv)=>{"use strict";var RL=Ov();Bv.exports=RL});var bl=f((Iq,Nv)=>{"use strict";var $L=_v();Nv.exports=$L});var Xr=f((Eq,Fv)=>{"use strict";var LL=xr(),ML=String;Fv.exports=function(a){if(LL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return ML(a)}});var gl=f((xq,qv)=>{"use strict";qv.exports=`
|
|
7
|
-
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var jv=f((Pq,Hv)=>{"use strict";var CL=ne(),DL=At(),VL=Xr(),Sl=gl(),Uv=CL("".replace),OL=RegExp("^["+Sl+"]+"),BL=RegExp("(^|[^"+Sl+"])["+Sl+"]+$"),vl=function(a){return function(e){var t=VL(DL(e));return a&1&&(t=Uv(t,OL,"")),a&2&&(t=Uv(t,BL,"$1")),t}};Hv.exports={start:vl(1),end:vl(2),trim:vl(3)}});var Yv=f((wq,Wv)=>{"use strict";var _L=Ho().PROPER,NL=de(),Qv=gl(),Gv="\u200B\x85\u180E";Wv.exports=function(a){return NL(function(){return!!Qv[a]()||Gv[a]()!==Gv||_L&&Qv[a].name!==a})}});var yl=f((Aq,zv)=>{"use strict";var FL=jv().start,qL=Yv();zv.exports=qL("trimStart")?function(){return FL(this)}:"".trimStart});var Xv=f(()=>{"use strict";var UL=se(),Kv=yl();UL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Kv},{trimLeft:Kv})});var Zv=f(()=>{"use strict";Xv();var HL=se(),Jv=yl();HL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Jv},{trimStart:Jv})});var tS=f((Mq,eS)=>{"use strict";Zv();var jL=kt();eS.exports=jL("String","trimLeft")});var rS=f((Cq,iS)=>{"use strict";var QL=tS();iS.exports=QL});var sS=f((Dq,aS)=>{"use strict";var GL=rS();aS.exports=GL});var TS=f(()=>{"use strict"});var IS=f(()=>{"use strict"});var xS=f((mH,ES)=>{"use strict";var fM=Ce(),bM=Xt(),gM=pe(),vM=gM("match");ES.exports=function(a){var e;return fM(a)&&((e=a[vM])!==void 0?!!e:bM(a)==="RegExp")}});var wS=f((fH,PS)=>{"use strict";var SM=tt();PS.exports=function(){var a=SM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var RS=f((bH,kS)=>{"use strict";var yM=Me(),TM=Ge(),IM=fr(),EM=wS(),AS=RegExp.prototype;kS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in AS)&&!TM(a,"flags")&&IM(AS,a)?yM(EM,a):e}});var LS=f((gH,$S)=>{"use strict";var kl=ne(),xM=wi(),PM=Math.floor,wl=kl("".charAt),wM=kl("".replace),Al=kl("".slice),AM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,kM=/\$([$&'`]|\d{1,2})/g;$S.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=kM;return r!==void 0&&(r=xM(r),u=AM),wM(s,u,function(l,c){var d;switch(wl(c,0)){case"$":return"$";case"&":return a;case"`":return Al(e,0,t);case"'":return Al(e,n);case"<":d=r[Al(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=PM(h/10);return p===0?l:p<=o?i[p-1]===void 0?wl(c,1):i[p-1]+wl(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var DS=f(()=>{"use strict";var RM=se(),$M=Me(),$l=ne(),MS=At(),LM=ee(),MM=xi(),CM=xS(),Ki=Xr(),DM=gr(),VM=RS(),OM=LS(),BM=pe(),_M=Qe(),NM=BM("replace"),FM=TypeError,Rl=$l("".indexOf),qM=$l("".replace),CS=$l("".slice),UM=Math.max;RM({target:"String",proto:!0},{replaceAll:function(e,t){var i=MS(this),r,s,n,o,u,l,c,d,h,p,m=0,b="";if(!MM(e)){if(r=CM(e),r&&(s=Ki(MS(VM(e))),!~Rl(s,"g")))throw new FM("`.replaceAll` does not allow non-global regexes");if(n=DM(e,NM),n)return $M(n,e,i,t);if(_M&&r)return qM(Ki(i),e,t)}for(o=Ki(i),u=Ki(e),l=LM(t),l||(t=Ki(t)),c=u.length,d=UM(1,c),h=Rl(o,u);h!==-1;)p=l?Ki(t(u,h,o)):OM(u,o,h,[],void 0,t),b+=CS(o,m,h)+p,m=h+c,h=h+d>o.length?-1:Rl(o,u,h+d);return m<o.length&&(b+=CS(o,m)),b}})});var OS=f((yH,VS)=>{"use strict";TS();IS();DS();var HM=kt();VS.exports=HM("String","replaceAll")});var _S=f((TH,BS)=>{"use strict";var jM=OS();BS.exports=jM});var FS=f((IH,NS)=>{"use strict";var QM=_S();NS.exports=QM});var US=f((EH,qS)=>{"use strict";var GM=Tr(),WM=Xr(),YM=At(),zM=RangeError;qS.exports=function(e){var t=WM(YM(this)),i="",r=GM(e);if(r<0||r===1/0)throw new zM("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var WS=f((xH,GS)=>{"use strict";var QS=ne(),KM=ko(),HS=Xr(),XM=US(),JM=At(),ZM=QS(XM),eC=QS("".slice),tC=Math.ceil,jS=function(a){return function(e,t,i){var r=HS(JM(e)),s=KM(t),n=r.length,o=i===void 0?" ":HS(i),u,l;return s<=n||o===""?r:(u=s-n,l=ZM(o,tC(u/o.length)),l.length>u&&(l=eC(l,0,u)),a?r+l:l+r)}};GS.exports={start:jS(!1),end:jS(!0)}});var zS=f((PH,YS)=>{"use strict";var iC=Zt();YS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(iC)});var KS=f(()=>{"use strict";var rC=se(),aC=WS().start,sC=zS();rC({target:"String",proto:!0,forced:sC},{padStart:function(e){return aC(this,e,arguments.length>1?arguments[1]:void 0)}})});var JS=f((kH,XS)=>{"use strict";KS();var nC=kt();XS.exports=nC("String","padStart")});var ey=f((RH,ZS)=>{"use strict";var oC=JS();ZS.exports=oC});var iy=f(($H,ty)=>{"use strict";var uC=ey();ty.exports=uC});var ud="2.0.131-dev.abb2b2b1.0";var $e=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))($e||{}),lt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(lt||{});var us=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(us||{}),Kn=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Kn||{});var Xn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Xn||{}),ls=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(ls||{});var BT=C(Be(),1);import{assertNever as nh,assertNonNullable as vx,isNonNullable as ms,ValueSubject as $o,Subject as Sx,Subscription as yx,merge as Tx,observableFrom as Ix,fromEvent as ih,map as rh,tap as ah,filterChanged as Ex,isNullable as Lo,ErrorCategory as sh}from"@vkontakte/videoplayer-shared/es2018";var th=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var fs=class{constructor(e){this.connection$=new $o(void 0);this.castState$=new $o("NOT_AVAILABLE");this.errorEvent$=new Sx;this.realCastState$=new $o("NOT_AVAILABLE");this.subscription=new yx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=ms((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||th("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:sh.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ms(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),i=cast.framework.CastContext.getInstance();this.subscription.add(ih(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return nh(r.sessionState)}})).add(Tx(ih(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ah(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),rh(r=>r.castState)),Ix([i.getCastState()])).pipe(Ex(),rh(xx),ah(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=ms(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();vx(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(r==="CONNECTED"?ms(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:sh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},xx=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 nh(a)}};var fc=C(Be(),1),vT=C(Ci(),1),ST=C(au(),1);var cg=C(Hs(),1);import{assertNever as tg}from"@vkontakte/videoplayer-shared/es2018";var he=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:tg(t)}return a},js=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:tg(e)}};var P=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as MR,Subject as Qs,merge as ig}from"@vkontakte/videoplayer-shared/es2018";var D=class{constructor(e){this.transitionStarted$=new Qs;this.transitionEnded$=new Qs;this.transitionUpdated$=new Qs;this.forceChanged$=new Qs;this.stateChangeStarted$=ig(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=ig(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||MR(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as CR}from"@vkontakte/videoplayer-shared/es2018";var rg=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 CR(a)}};import{assertNever as Hi,assertNonNullable as ni,debounce as ag,ErrorCategory as sg,fromEvent as oi,isNonNullable as ng,map as og,merge as ug,observableFrom as DR,Subject as VR,Subscription as ju,timeout as OR,getHighestQuality as BR}from"@vkontakte/videoplayer-shared/es2018";var _R=5,NR=5,FR=500,lg=7e3,Vr=class{constructor(e){this.subscription=new ju;this.loadMediaTimeoutSubscription=new ju;this.videoState=new D("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Hi(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:Hi(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:Hi(e)}break}default:Hi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(rg(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 ju;this.subscription.add(e),this.subscription.add(ug(this.videoState.stateChangeStarted$.pipe(og(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(og(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new VR;e.add(r.pipe(ag(FR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(oi(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)>_R)&&r.next(o),s=o})),e.add(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<NR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:Hi(n)}}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(oi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=ug(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,DR(["init"])).pipe(ag(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(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"),P(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"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];ni(c);let d=BR(Object.keys(c));ni(d);let h=c[d];ni(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];ni(c),i=c.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];ni(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];ni(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];ni(c),i=he(c.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:sg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Hi(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return ng(o)&&(n.metadata.title=o),ng(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(OR(lg).subscribe(()=>s(`timeout(${lg})`)))});(0,cg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:sg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var hl=C(Be(),1);import{clearVideoElement as pg}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as qR}from"@vkontakte/videoplayer-shared/es2018";var dg=a=>{try{a.pause(),a.playbackRate=0,qR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as UR,Subscription as HR}from"@vkontakte/videoplayer-shared/es2018";var Qu=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)}},Gu=window.WeakMap?new WeakMap:new Qu,Wu=window.WeakMap?new WeakMap:new Map,jR=(a,e=20)=>{let t=0;return UR(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?pg(i):(i=document.createElement("video"),a.appendChild(i)),Gu.set(i,r);let s=new HR;return s.add(jR(i,e)),Wu.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},xe=a=>{let e=Wu.get(a);e==null||e.unsubscribe(),Wu.delete(a);let t=Gu.get(a);Gu.delete(a),t?pg(a):dg(a)};var zu=C(ji(),1);import{assertNonNullable as Or,isNonNullable as rt,isNullable as JR,fromEvent as Qi,merge as Sg,observableFrom as yg,filterChanged as Tg,map as Br,Subject as Ig,Subscription as ZR,ValueSubject as e$,ErrorCategory as t$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Yu,isNullable as KR,Subscription as XR}from"@vkontakte/videoplayer-shared/es2018";var Gs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=KR(r),l=new XR;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},it=(a,e,t)=>Gs(e,()=>a.loop,i=>{Yu(i)&&(a.loop=i)},{onError:t}),Pe=(a,e,t,i)=>Gs(e,()=>({muted:a.muted,volume:a.volume}),r=>{Yu(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),_e=(a,e,t,i)=>Gs(e,()=>a.playbackRate,r=>{Yu(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),$t=Gs;var i$=a=>["__",a.language,a.label].join("|"),r$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Ku=class a{constructor(e){this.available$=new Ig;this.current$=new e$(void 0);this.error$=new Ig;this.subscription=new ZR;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:t$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add($t(t.internalTextTracks,()=>(0,zu.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(Br(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add($t(t.externalTextTracks,()=>(0,zu.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(Br(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add($t(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add($t(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Or(this.video);let{textTracks:e}=this.video;this.subscription.add(Qi(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Sg(Qi(e,"addtrack"),Qi(e,"removetrack"),yg(["init"])).pipe(Br(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Tg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(Sg(Qi(e,"change"),yg(["init"])).pipe(Br(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Br(i=>i&&this.htmlTextTrackToITextTrack(i).id),Tg()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Qi(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Qi(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;rt(t.align)&&(r.align=t.align),rt(t.position)&&(r.position=t.position),rt(t.size)&&(r.size=t.size),rt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Or(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:i$(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Or(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(JR(e)||!r$(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){Or(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){Or(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ne=Ku;var ui=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 Eg=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},Xu=a=>{let e=Eg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},xg=a=>{let e=Eg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as we,map as Lt,merge as Zu,filterChanged as p$,isNonNullable as Cg,Subject as h$,filter as Nr,mapTo as el,combine as m$,once as f$,throttle as b$,ErrorCategory as g$,ValueSubject as Dg,Subscription as v$}from"@vkontakte/videoplayer-shared/es2018";var a$=3,Pg=(a,e,t=a$)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Ws=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var wg=C(Be(),1);var _r=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Ys=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,wg.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=_r()}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,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var zs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Ye=()=>window.ManagedMediaSource||window.MediaSource,Ks=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ag=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},kg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var s$=document.createElement("video"),n$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',o$='video/mp4; codecs="hev1.1.6.L93.B0"',Rg='video/webm; codecs="vp09.00.10.08"',$g='video/webm; codecs="av01.0.00M.08"',u$='audio/mp4; codecs="mp4a.40.2"',l$='audio/webm; codecs="opus"',Lg,c$=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:$g}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Rg}})]);Lg={DASH_WEBM_AV1:e,DASH_WEBM:t}};c$().catch(a=>{console.log(s$),console.error(a)});var Xs=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Lg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,h,p,m,b,g,v,S,y,I;this._video=document.createElement("video");try{this._protocols={mms:Ks(),mse:Ag(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let T=!!((c=(l=Ye())==null?void 0:l.isTypeSupported)!=null&&c.call(l,n$)),R=!!((h=(d=Ye())==null?void 0:d.isTypeSupported)!=null&&h.call(d,o$)),q=!!((m=(p=Ye())==null?void 0:p.isTypeSupported)!=null&&m.call(p,u$));this._codecs={h264:T,h265:R,vp9:!!((g=(b=Ye())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Rg)),av1:!!((S=(v=Ye())==null?void 0:v.isTypeSupported)!=null&&S.call(v,$g)),aac:q,opus:!!((I=(y=Ye())==null?void 0:y.isTypeSupported)!=null&&I.call(y,l$)),mpeg:(T||R)&&q},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}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 Mg="audio/mpeg",Js=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Mg))},this._codecs={mp3:!!((r=(i=Ye())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Mg))}}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 d$}from"@vkontakte/videoplayer-shared/es2018";var Ju=class{constructor(){this.isInited$=new d$(!1);this._displayChecker=new zs,this._deviceChecker=new Ys(this._displayChecker),this._browserChecker=new Ws,this._videoChecker=new Xs(this._deviceChecker,this._browserChecker),this._audioChecker=new Js,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},N=new Ju;var Ae=a=>{let e=w=>we(a,w).pipe(el(void 0)),t=new v$,i=()=>t.unsubscribe(),s=Zu(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>we(a,w))).pipe(Lt(w=>w.type==="ended"?a.readyState<2:a.readyState<3),p$()),n=Zu(we(a,"progress"),we(a,"timeupdate")).pipe(Lt(()=>Pg(a.buffered,a.currentTime))),o=N.browser.isSafari?m$({play:e("play").pipe(f$()),playing:e("playing")}).pipe(el(void 0)):e("playing"),u=we(a,"volumechange").pipe(Lt(()=>({muted:a.muted,volume:a.volume}))),l=we(a,"ratechange").pipe(Lt(()=>a.playbackRate)),c=we(a,"error").pipe(Nr(()=>!!(a.error||a.played.length)),Lt(()=>{var U;let w=a.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:g$.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(U=a.error)!=null?U:void 0}})),d=we(a,"timeupdate").pipe(Lt(()=>a.currentTime)),h=new h$,p=.3,m;t.add(d.subscribe(w=>{a.loop&&Cg(m)&&Cg(w)&&m>=a.duration-p&&w<=p&&h.next(m),m=w}));let b=e("pause").pipe(Nr(()=>!a.error&&m!==a.duration)),g=we(a,"enterpictureinpicture"),v=we(a,"leavepictureinpicture"),S=new Dg(xg(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new Dg(Xu(a)),I=we(a,"fullscreenchange");t.add(I.pipe(Lt(()=>Xu(a))).subscribe(y));let T=.1,R=1e3,q=we(a,"timeupdate").pipe(Nr(w=>a.duration-a.currentTime<T)),O=Zu(q.pipe(Nr(w=>!a.loop)),we(a,"ended")).pipe(b$(R),el(void 0)),_=q.pipe(Nr(w=>a.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:O,looped$:h,loopExpected$:_,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:we(a,"durationchange").pipe(Lt(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:S,inFullscreen$:y,enterPip$:g,leavePip$:v,destroy:i}};import{VideoQuality as Mt}from"@vkontakte/videoplayer-shared/es2018";var Ct=a=>{switch(a){case"mobile":return Mt.Q_144P;case"lowest":return Mt.Q_240P;case"low":return Mt.Q_360P;case"sd":case"medium":return Mt.Q_480P;case"hd":case"high":return Mt.Q_720P;case"fullhd":case"full":return Mt.Q_1080P;case"quadhd":case"quad":return Mt.Q_1440P;case"ultrahd":case"ultra":return Mt.Q_2160P}};var Vt=C(Dt(),1),Kg=C(Be(),1),tn=C(Ci(),1);import{isNonNullable as Se,isNullable as Gg,now as Xg,isHigher as Wg,isHigherOrEqual as al,isInvariantQuality as Yg,isLowerOrEqual as sl,videoSizeToQuality as R$,assertNotEmptyArray as Jg,assertNonNullable as $$}from"@vkontakte/videoplayer-shared/es2018";var tl=!1,ht={},qg=a=>{tl=a},Ug=()=>{ht={}},Hg=a=>{a(ht)},Fr=(a,e)=>{var t;tl&&(ht.meta=(t=ht.meta)!=null?t:{},ht.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var i,r;if(!tl)return;ht.series=(i=ht.series)!=null?i:{};let t=(r=ht.series[this.name])!=null?r:[];t.push([Date.now(),e]),ht.series[this.name]=t}};import{isHigher as A$,isHigherOrEqual as MN,isLower as jg,isLowerOrEqual as CN,isNonNullable as Zs,isNullable as k$,videoHeightToQuality as en}from"@vkontakte/videoplayer-shared/es2018";function il({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function rl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&il({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function qr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return k$(a)||Zs(a.min)&&Zs(a.max)&&jg(a.max,a.min)||Zs(a.min)&&e&&A$(a.min,e)||Zs(a.max)&&t&&jg(a.max,t)}function Qg({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return qr({limits:{max:a!=null&&a.max?en(a.max):void 0,min:a!=null&&a.min?en(a.min):void 0},highestAvailableQuality:e?en(e):void 0,lowestAvailableQuality:t?en(t):void 0})}var L$=new ve("best_bitrate"),Zg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var nl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Ur=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Xg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},ev='Assertion "ABR Tracks is empty array" failed',rn=(a,e,t,i)=>{var u;let r=[...e].sort(nl(1)),s=[...t].sort(nl(1)),n=s.filter(l=>Se(l.bitrate)&&Se(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Vt.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Vt.default)(s,-1);return o&&(0,Kg.default)(n,o)?o:n.length?(0,Vt.default)(n,-1):(0,Vt.default)(s,0)},zg=a=>"quality"in a,tv=(a,e,t,i)=>{var n;let r=Se((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&Se(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Xg()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=zg(o)?"video":"audio",l=zg(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var BE=Object.create;var Mh=Object.defineProperty;var DE=Object.getOwnPropertyDescriptor;var CE=Object.getOwnPropertyNames;var VE=Object.getPrototypeOf,OE=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var _E=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of CE(e))!OE.call(s,r)&&r!==t&&Mh(s,r,{get:()=>e[r],enumerable:!(i=DE(e,r))||i.enumerable});return s};var N=(s,e,t)=>(t=s!=null?BE(VE(s)):{},_E(e||!s||!s.__esModule?Mh(t,"default",{value:s,enumerable:!0}):t,s));var ve=b((Ul,Bh)=>{"use strict";var ra=function(s){return s&&s.Math===Math&&s};Bh.exports=ra(typeof globalThis=="object"&&globalThis)||ra(typeof window=="object"&&window)||ra(typeof self=="object"&&self)||ra(typeof global=="object"&&global)||ra(typeof Ul=="object"&&Ul)||function(){return this}()||Function("return this")()});var _e=b((a_,Dh)=>{"use strict";Dh.exports=function(s){try{return!!s()}catch(e){return!0}}});var sa=b((n_,Ch)=>{"use strict";var FE=_e();Ch.exports=!FE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var ql=b((o_,Fh)=>{"use strict";var NE=sa(),_h=Function.prototype,Vh=_h.apply,Oh=_h.call;Fh.exports=typeof Reflect=="object"&&Reflect.apply||(NE?Oh.bind(Vh):function(){return Oh.apply(Vh,arguments)})});var $e=b((u_,qh)=>{"use strict";var Nh=sa(),Uh=Function.prototype,jl=Uh.call,UE=Nh&&Uh.bind.bind(jl,jl);qh.exports=Nh?UE:function(s){return function(){return jl.apply(s,arguments)}}});var Xi=b((l_,Hh)=>{"use strict";var jh=$e(),qE=jh({}.toString),jE=jh("".slice);Hh.exports=function(s){return jE(qE(s),8,-1)}});var Hl=b((c_,Gh)=>{"use strict";var HE=Xi(),GE=$e();Gh.exports=function(s){if(HE(s)==="Function")return GE(s)}});var ge=b((d_,zh)=>{"use strict";var Gl=typeof document=="object"&&document.all;zh.exports=typeof Gl=="undefined"&&Gl!==void 0?function(s){return typeof s=="function"||s===Gl}:function(s){return typeof s=="function"}});var gt=b((p_,Qh)=>{"use strict";var zE=_e();Qh.exports=!zE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var St=b((h_,Wh)=>{"use strict";var QE=sa(),Ao=Function.prototype.call;Wh.exports=QE?Ao.bind(Ao):function(){return Ao.apply(Ao,arguments)}});var zl=b(Xh=>{"use strict";var Yh={}.propertyIsEnumerable,Kh=Object.getOwnPropertyDescriptor,WE=Kh&&!Yh.call({1:2},1);Xh.f=WE?function(e){var t=Kh(this,e);return!!t&&t.enumerable}:Yh});var aa=b((m_,Jh)=>{"use strict";Jh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var ef=b((b_,Zh)=>{"use strict";var YE=$e(),KE=_e(),XE=Xi(),Ql=Object,JE=YE("".split);Zh.exports=KE(function(){return!Ql("z").propertyIsEnumerable(0)})?function(s){return XE(s)==="String"?JE(s,""):Ql(s)}:Ql});var xr=b((g_,tf)=>{"use strict";tf.exports=function(s){return s==null}});var Ri=b((S_,rf)=>{"use strict";var ZE=xr(),ew=TypeError;rf.exports=function(s){if(ZE(s))throw new ew("Can't call method on "+s);return s}});var Ji=b((v_,sf)=>{"use strict";var tw=ef(),iw=Ri();sf.exports=function(s){return tw(iw(s))}});var vt=b((y_,af)=>{"use strict";var rw=ge();af.exports=function(s){return typeof s=="object"?s!==null:rw(s)}});var Er=b((T_,nf)=>{"use strict";nf.exports={}});var hi=b((I_,uf)=>{"use strict";var Wl=Er(),Yl=ve(),sw=ge(),of=function(s){return sw(s)?s:void 0};uf.exports=function(s,e){return arguments.length<2?of(Wl[s])||of(Yl[s]):Wl[s]&&Wl[s][e]||Yl[s]&&Yl[s][e]}});var na=b((x_,lf)=>{"use strict";var aw=$e();lf.exports=aw({}.isPrototypeOf)});var Zi=b((E_,pf)=>{"use strict";var nw=ve(),cf=nw.navigator,df=cf&&cf.userAgent;pf.exports=df?String(df):""});var Xl=b((w_,Sf)=>{"use strict";var gf=ve(),Kl=Zi(),hf=gf.process,ff=gf.Deno,mf=hf&&hf.versions||ff&&ff.version,bf=mf&&mf.v8,Dt,ko;bf&&(Dt=bf.split("."),ko=Dt[0]>0&&Dt[0]<4?1:+(Dt[0]+Dt[1]));!ko&&Kl&&(Dt=Kl.match(/Edge\/(\d+)/),(!Dt||Dt[1]>=74)&&(Dt=Kl.match(/Chrome\/(\d+)/),Dt&&(ko=+Dt[1])));Sf.exports=ko});var Jl=b((P_,yf)=>{"use strict";var vf=Xl(),ow=_e(),uw=ve(),lw=uw.String;yf.exports=!!Object.getOwnPropertySymbols&&!ow(function(){var s=Symbol("symbol detection");return!lw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&vf&&vf<41})});var Zl=b((A_,Tf)=>{"use strict";var cw=Jl();Tf.exports=cw&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ec=b((k_,If)=>{"use strict";var dw=hi(),pw=ge(),hw=na(),fw=Zl(),mw=Object;If.exports=fw?function(s){return typeof s=="symbol"}:function(s){var e=dw("Symbol");return pw(e)&&hw(e.prototype,mw(s))}});var oa=b((R_,xf)=>{"use strict";var bw=String;xf.exports=function(s){try{return bw(s)}catch(e){return"Object"}}});var jt=b((L_,Ef)=>{"use strict";var gw=ge(),Sw=oa(),vw=TypeError;Ef.exports=function(s){if(gw(s))return s;throw new vw(Sw(s)+" is not a function")}});var ua=b((M_,wf)=>{"use strict";var yw=jt(),Tw=xr();wf.exports=function(s,e){var t=s[e];return Tw(t)?void 0:yw(t)}});var Af=b(($_,Pf)=>{"use strict";var tc=St(),ic=ge(),rc=vt(),Iw=TypeError;Pf.exports=function(s,e){var t,i;if(e==="string"&&ic(t=s.toString)&&!rc(i=tc(t,s))||ic(t=s.valueOf)&&!rc(i=tc(t,s))||e!=="string"&&ic(t=s.toString)&&!rc(i=tc(t,s)))return i;throw new Iw("Can't convert object to primitive value")}});var Ct=b((B_,kf)=>{"use strict";kf.exports=!0});var Mf=b((D_,Lf)=>{"use strict";var Rf=ve(),xw=Object.defineProperty;Lf.exports=function(s,e){try{xw(Rf,s,{value:e,configurable:!0,writable:!0})}catch(t){Rf[s]=e}return e}});var la=b((C_,Df)=>{"use strict";var Ew=Ct(),ww=ve(),Pw=Mf(),$f="__core-js_shared__",Bf=Df.exports=ww[$f]||Pw($f,{});(Bf.versions||(Bf.versions=[])).push({version:"3.38.0",mode:Ew?"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 sc=b((V_,Vf)=>{"use strict";var Cf=la();Vf.exports=function(s,e){return Cf[s]||(Cf[s]=e||{})}});var wr=b((O_,Of)=>{"use strict";var Aw=Ri(),kw=Object;Of.exports=function(s){return kw(Aw(s))}});var Vt=b((__,_f)=>{"use strict";var Rw=$e(),Lw=wr(),Mw=Rw({}.hasOwnProperty);_f.exports=Object.hasOwn||function(e,t){return Mw(Lw(e),t)}});var ac=b((F_,Ff)=>{"use strict";var $w=$e(),Bw=0,Dw=Math.random(),Cw=$w(1 .toString);Ff.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Cw(++Bw+Dw,36)}});var Fe=b((N_,Uf)=>{"use strict";var Vw=ve(),Ow=sc(),Nf=Vt(),_w=ac(),Fw=Jl(),Nw=Zl(),Pr=Vw.Symbol,nc=Ow("wks"),Uw=Nw?Pr.for||Pr:Pr&&Pr.withoutSetter||_w;Uf.exports=function(s){return Nf(nc,s)||(nc[s]=Fw&&Nf(Pr,s)?Pr[s]:Uw("Symbol."+s)),nc[s]}});var Gf=b((U_,Hf)=>{"use strict";var qw=St(),qf=vt(),jf=ec(),jw=ua(),Hw=Af(),Gw=Fe(),zw=TypeError,Qw=Gw("toPrimitive");Hf.exports=function(s,e){if(!qf(s)||jf(s))return s;var t=jw(s,Qw),i;if(t){if(e===void 0&&(e="default"),i=qw(t,s,e),!qf(i)||jf(i))return i;throw new zw("Can't convert object to primitive value")}return e===void 0&&(e="number"),Hw(s,e)}});var oc=b((q_,zf)=>{"use strict";var Ww=Gf(),Yw=ec();zf.exports=function(s){var e=Ww(s,"string");return Yw(e)?e:e+""}});var Ro=b((j_,Wf)=>{"use strict";var Kw=ve(),Qf=vt(),uc=Kw.document,Xw=Qf(uc)&&Qf(uc.createElement);Wf.exports=function(s){return Xw?uc.createElement(s):{}}});var lc=b((H_,Yf)=>{"use strict";var Jw=gt(),Zw=_e(),eP=Ro();Yf.exports=!Jw&&!Zw(function(){return Object.defineProperty(eP("div"),"a",{get:function(){return 7}}).a!==7})});var Jf=b(Xf=>{"use strict";var tP=gt(),iP=St(),rP=zl(),sP=aa(),aP=Ji(),nP=oc(),oP=Vt(),uP=lc(),Kf=Object.getOwnPropertyDescriptor;Xf.f=tP?Kf:function(e,t){if(e=aP(e),t=nP(t),uP)try{return Kf(e,t)}catch(i){}if(oP(e,t))return sP(!iP(rP.f,e,t),e[t])}});var cc=b((z_,Zf)=>{"use strict";var lP=_e(),cP=ge(),dP=/#|\.prototype\./,ca=function(s,e){var t=hP[pP(s)];return t===mP?!0:t===fP?!1:cP(e)?lP(e):!!e},pP=ca.normalize=function(s){return String(s).replace(dP,".").toLowerCase()},hP=ca.data={},fP=ca.NATIVE="N",mP=ca.POLYFILL="P";Zf.exports=ca});var Ar=b((Q_,tm)=>{"use strict";var em=Hl(),bP=jt(),gP=sa(),SP=em(em.bind);tm.exports=function(s,e){return bP(s),e===void 0?s:gP?SP(s,e):function(){return s.apply(e,arguments)}}});var dc=b((W_,im)=>{"use strict";var vP=gt(),yP=_e();im.exports=vP&&yP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ht=b((Y_,rm)=>{"use strict";var TP=vt(),IP=String,xP=TypeError;rm.exports=function(s){if(TP(s))return s;throw new xP(IP(s)+" is not an object")}});var er=b(am=>{"use strict";var EP=gt(),wP=lc(),PP=dc(),Lo=Ht(),sm=oc(),AP=TypeError,pc=Object.defineProperty,kP=Object.getOwnPropertyDescriptor,hc="enumerable",fc="configurable",mc="writable";am.f=EP?PP?function(e,t,i){if(Lo(e),t=sm(t),Lo(i),typeof e=="function"&&t==="prototype"&&"value"in i&&mc in i&&!i[mc]){var r=kP(e,t);r&&r[mc]&&(e[t]=i.value,i={configurable:fc in i?i[fc]:r[fc],enumerable:hc in i?i[hc]:r[hc],writable:!1})}return pc(e,t,i)}:pc:function(e,t,i){if(Lo(e),t=sm(t),Lo(i),wP)try{return pc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new AP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var kr=b((X_,nm)=>{"use strict";var RP=gt(),LP=er(),MP=aa();nm.exports=RP?function(s,e,t){return LP.f(s,e,MP(1,t))}:function(s,e,t){return s[e]=t,s}});var Ee=b((J_,um)=>{"use strict";var da=ve(),$P=ql(),BP=Hl(),DP=ge(),CP=Jf().f,VP=cc(),Rr=Er(),OP=Ar(),Lr=kr(),om=Vt();la();var _P=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return $P(s,this,arguments)};return e.prototype=s.prototype,e};um.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?da:r?da[t]:da[t]&&da[t].prototype,o=i?Rr:Rr[t]||Lr(Rr,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=VP(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&om(n,h),f=o[h],d&&(s.dontCallGetSet?(S=CP(n,h),m=S&&S.value):m=n[h]),p=d&&m?m:e[h],!(!l&&!a&&typeof f==typeof p)&&(s.bind&&d?g=OP(p,da):s.wrap&&d?g=_P(p):a&&DP(p)?g=BP(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&Lr(g,"sham",!0),Lr(o,h,g),a&&(c=t+"Prototype",om(Rr,c)||Lr(Rr,c,{}),Lr(Rr[c],h,p),s.real&&u&&(l||!u[h])&&Lr(u,h,p)))}});var cm=b((Z_,lm)=>{"use strict";var FP=Math.ceil,NP=Math.floor;lm.exports=Math.trunc||function(e){var t=+e;return(t>0?NP:FP)(t)}});var pa=b((eF,dm)=>{"use strict";var UP=cm();dm.exports=function(s){var e=+s;return e!==e||e===0?0:UP(e)}});var hm=b((tF,pm)=>{"use strict";var qP=pa(),jP=Math.max,HP=Math.min;pm.exports=function(s,e){var t=qP(s);return t<0?jP(t+e,0):HP(t,e)}});var bc=b((iF,fm)=>{"use strict";var GP=pa(),zP=Math.min;fm.exports=function(s){var e=GP(s);return e>0?zP(e,9007199254740991):0}});var Mr=b((rF,mm)=>{"use strict";var QP=bc();mm.exports=function(s){return QP(s.length)}});var gc=b((sF,gm)=>{"use strict";var WP=Ji(),YP=hm(),KP=Mr(),bm=function(s){return function(e,t,i){var r=WP(e),a=KP(r);if(a===0)return!s&&-1;var n=YP(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};gm.exports={includes:bm(!0),indexOf:bm(!1)}});var ha=b((aF,Sm)=>{"use strict";Sm.exports=function(){}});var vm=b(()=>{"use strict";var XP=Ee(),JP=gc().includes,ZP=_e(),eA=ha(),tA=ZP(function(){return!Array(1).includes()});XP({target:"Array",proto:!0,forced:tA},{includes:function(e){return JP(this,e,arguments.length>1?arguments[1]:void 0)}});eA("includes")});var Li=b((uF,ym)=>{"use strict";var iA=hi();ym.exports=iA});var Im=b((lF,Tm)=>{"use strict";vm();var rA=Li();Tm.exports=rA("Array","includes")});var Em=b((cF,xm)=>{"use strict";var sA=Im();xm.exports=sA});var yt=b((dF,wm)=>{"use strict";var aA=Em();wm.exports=aA});var Bo=b((xF,Bm)=>{"use strict";var hA=sc(),fA=ac(),$m=hA("keys");Bm.exports=function(s){return $m[s]||($m[s]=fA(s))}});var Cm=b((EF,Dm)=>{"use strict";var mA=_e();Dm.exports=!mA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Do=b((wF,Om)=>{"use strict";var bA=Vt(),gA=ge(),SA=wr(),vA=Bo(),yA=Cm(),Vm=vA("IE_PROTO"),yc=Object,TA=yc.prototype;Om.exports=yA?yc.getPrototypeOf:function(s){var e=SA(s);if(bA(e,Vm))return e[Vm];var t=e.constructor;return gA(t)&&e instanceof t?t.prototype:e instanceof yc?TA:null}});var Co=b((PF,_m)=>{"use strict";_m.exports={}});var Um=b((AF,Nm)=>{"use strict";var IA=$e(),Tc=Vt(),xA=Ji(),EA=gc().indexOf,wA=Co(),Fm=IA([].push);Nm.exports=function(s,e){var t=xA(s),i=0,r=[],a;for(a in t)!Tc(wA,a)&&Tc(t,a)&&Fm(r,a);for(;e.length>i;)Tc(t,a=e[i++])&&(~EA(r,a)||Fm(r,a));return r}});var Ic=b((kF,qm)=>{"use strict";qm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var xc=b((RF,jm)=>{"use strict";var PA=Um(),AA=Ic();jm.exports=Object.keys||function(e){return PA(e,AA)}});var Ec=b((LF,Wm)=>{"use strict";var Gm=gt(),kA=_e(),zm=$e(),RA=Do(),LA=xc(),MA=Ji(),$A=zl().f,Qm=zm($A),BA=zm([].push),DA=Gm&&kA(function(){var s=Object.create(null);return s[2]=2,!Qm(s,2)}),Hm=function(s){return function(e){for(var t=MA(e),i=LA(t),r=DA&&RA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Gm||(r?u in t:Qm(t,u)))&&BA(o,s?[u,t[u]]:t[u]);return o}};Wm.exports={entries:Hm(!0),values:Hm(!1)}});var Ym=b(()=>{"use strict";var CA=Ee(),VA=Ec().entries;CA({target:"Object",stat:!0},{entries:function(e){return VA(e)}})});var Xm=b((BF,Km)=>{"use strict";Ym();var OA=Er();Km.exports=OA.Object.entries});var Zm=b((DF,Jm)=>{"use strict";var _A=Xm();Jm.exports=_A});var tr=b((CF,eb)=>{"use strict";var FA=Zm();eb.exports=FA});var ir=b((VF,tb)=>{"use strict";tb.exports={}});var sb=b((OF,rb)=>{"use strict";var NA=ve(),UA=ge(),ib=NA.WeakMap;rb.exports=UA(ib)&&/native code/.test(String(ib))});var kc=b((_F,ob)=>{"use strict";var qA=sb(),nb=ve(),jA=vt(),HA=kr(),wc=Vt(),Pc=la(),GA=Bo(),zA=Co(),ab="Object already initialized",Ac=nb.TypeError,QA=nb.WeakMap,Vo,fa,Oo,WA=function(s){return Oo(s)?fa(s):Vo(s,{})},YA=function(s){return function(e){var t;if(!jA(e)||(t=fa(e)).type!==s)throw new Ac("Incompatible receiver, "+s+" required");return t}};qA||Pc.state?(Ot=Pc.state||(Pc.state=new QA),Ot.get=Ot.get,Ot.has=Ot.has,Ot.set=Ot.set,Vo=function(s,e){if(Ot.has(s))throw new Ac(ab);return e.facade=s,Ot.set(s,e),e},fa=function(s){return Ot.get(s)||{}},Oo=function(s){return Ot.has(s)}):(rr=GA("state"),zA[rr]=!0,Vo=function(s,e){if(wc(s,rr))throw new Ac(ab);return e.facade=s,HA(s,rr,e),e},fa=function(s){return wc(s,rr)?s[rr]:{}},Oo=function(s){return wc(s,rr)});var Ot,rr;ob.exports={set:Vo,get:fa,has:Oo,enforce:WA,getterFor:YA}});var Mc=b((FF,lb)=>{"use strict";var Rc=gt(),KA=Vt(),ub=Function.prototype,XA=Rc&&Object.getOwnPropertyDescriptor,Lc=KA(ub,"name"),JA=Lc&&function(){}.name==="something",ZA=Lc&&(!Rc||Rc&&XA(ub,"name").configurable);lb.exports={EXISTS:Lc,PROPER:JA,CONFIGURABLE:ZA}});var db=b(cb=>{"use strict";var ek=gt(),tk=dc(),ik=er(),rk=Ht(),sk=Ji(),ak=xc();cb.f=ek&&!tk?Object.defineProperties:function(e,t){rk(e);for(var i=sk(t),r=ak(t),a=r.length,n=0,o;a>n;)ik.f(e,o=r[n++],i[o]);return e}});var $c=b((UF,pb)=>{"use strict";var nk=hi();pb.exports=nk("document","documentElement")});var Vc=b((qF,vb)=>{"use strict";var ok=Ht(),uk=db(),hb=Ic(),lk=Co(),ck=$c(),dk=Ro(),pk=Bo(),fb=">",mb="<",Dc="prototype",Cc="script",gb=pk("IE_PROTO"),Bc=function(){},Sb=function(s){return mb+Cc+fb+s+mb+"/"+Cc+fb},bb=function(s){s.write(Sb("")),s.close();var e=s.parentWindow.Object;return s=null,e},hk=function(){var s=dk("iframe"),e="java"+Cc+":",t;return s.style.display="none",ck.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Sb("document.F=Object")),t.close(),t.F},_o,Fo=function(){try{_o=new ActiveXObject("htmlfile")}catch(e){}Fo=typeof document!="undefined"?document.domain&&_o?bb(_o):hk():bb(_o);for(var s=hb.length;s--;)delete Fo[Dc][hb[s]];return Fo()};lk[gb]=!0;vb.exports=Object.create||function(e,t){var i;return e!==null?(Bc[Dc]=ok(e),i=new Bc,Bc[Dc]=null,i[gb]=e):i=Fo(),t===void 0?i:uk.f(i,t)}});var $r=b((jF,yb)=>{"use strict";var fk=kr();yb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:fk(s,e,t),s}});var Nc=b((HF,xb)=>{"use strict";var mk=_e(),bk=ge(),gk=vt(),Sk=Vc(),Tb=Do(),vk=$r(),yk=Fe(),Tk=Ct(),Fc=yk("iterator"),Ib=!1,fi,Oc,_c;[].keys&&(_c=[].keys(),"next"in _c?(Oc=Tb(Tb(_c)),Oc!==Object.prototype&&(fi=Oc)):Ib=!0);var Ik=!gk(fi)||mk(function(){var s={};return fi[Fc].call(s)!==s});Ik?fi={}:Tk&&(fi=Sk(fi));bk(fi[Fc])||vk(fi,Fc,function(){return this});xb.exports={IteratorPrototype:fi,BUGGY_SAFARI_ITERATORS:Ib}});var No=b((GF,wb)=>{"use strict";var xk=Fe(),Ek=xk("toStringTag"),Eb={};Eb[Ek]="z";wb.exports=String(Eb)==="[object z]"});var ma=b((zF,Pb)=>{"use strict";var wk=No(),Pk=ge(),Uo=Xi(),Ak=Fe(),kk=Ak("toStringTag"),Rk=Object,Lk=Uo(function(){return arguments}())==="Arguments",Mk=function(s,e){try{return s[e]}catch(t){}};Pb.exports=wk?Uo:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Mk(e=Rk(s),kk))=="string"?t:Lk?Uo(e):(i=Uo(e))==="Object"&&Pk(e.callee)?"Arguments":i}});var kb=b((QF,Ab)=>{"use strict";var $k=No(),Bk=ma();Ab.exports=$k?{}.toString:function(){return"[object "+Bk(this)+"]"}});var ba=b((WF,Lb)=>{"use strict";var Dk=No(),Ck=er().f,Vk=kr(),Ok=Vt(),_k=kb(),Fk=Fe(),Rb=Fk("toStringTag");Lb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(Ok(r,Rb)||Ck(r,Rb,{configurable:!0,value:e}),i&&!Dk&&Vk(r,"toString",_k))}});var $b=b((YF,Mb)=>{"use strict";var Nk=Nc().IteratorPrototype,Uk=Vc(),qk=aa(),jk=ba(),Hk=ir(),Gk=function(){return this};Mb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Uk(Nk,{next:qk(+!i,t)}),jk(s,r,!1,!0),Hk[r]=Gk,s}});var Db=b((KF,Bb)=>{"use strict";var zk=$e(),Qk=jt();Bb.exports=function(s,e,t){try{return zk(Qk(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Vb=b((XF,Cb)=>{"use strict";var Wk=vt();Cb.exports=function(s){return Wk(s)||s===null}});var _b=b((JF,Ob)=>{"use strict";var Yk=Vb(),Kk=String,Xk=TypeError;Ob.exports=function(s){if(Yk(s))return s;throw new Xk("Can't set "+Kk(s)+" as a prototype")}});var Uc=b((ZF,Fb)=>{"use strict";var Jk=Db(),Zk=vt(),eR=Ri(),tR=_b();Fb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=Jk(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return eR(r),tR(a),Zk(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Kb=b((eN,Yb)=>{"use strict";var iR=Ee(),rR=St(),qo=Ct(),Qb=Mc(),sR=ge(),aR=$b(),Nb=Do(),Ub=Uc(),nR=ba(),oR=kr(),qc=$r(),uR=Fe(),qb=ir(),Wb=Nc(),lR=Qb.PROPER,cR=Qb.CONFIGURABLE,jb=Wb.IteratorPrototype,jo=Wb.BUGGY_SAFARI_ITERATORS,ga=uR("iterator"),Hb="keys",Sa="values",Gb="entries",zb=function(){return this};Yb.exports=function(s,e,t,i,r,a,n){aR(t,e,i);var o=function(S){if(S===r&&h)return h;if(!jo&&S&&S in d)return d[S];switch(S){case Hb:return function(){return new t(this,S)};case Sa:return function(){return new t(this,S)};case Gb:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[ga]||d["@@iterator"]||r&&d[r],h=!jo&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=Nb(p.call(new s)),f!==Object.prototype&&f.next&&(!qo&&Nb(f)!==jb&&(Ub?Ub(f,jb):sR(f[ga])||qc(f,ga,zb)),nR(f,u,!0,!0),qo&&(qb[u]=zb))),lR&&r===Sa&&c&&c.name!==Sa&&(!qo&&cR?oR(d,"name",Sa):(l=!0,h=function(){return rR(c,this)})),r)if(m={values:o(Sa),keys:a?h:o(Hb),entries:o(Gb)},n)for(g in m)(jo||l||!(g in d))&&qc(d,g,m[g]);else iR({target:e,proto:!0,forced:jo||l},m);return(!qo||n)&&d[ga]!==h&&qc(d,ga,h,{name:r}),qb[e]=h,m}});var Jb=b((tN,Xb)=>{"use strict";Xb.exports=function(s,e){return{value:s,done:e}}});var Hc=b((iN,rg)=>{"use strict";var dR=Ji(),jc=ha(),Zb=ir(),tg=kc(),pR=er().f,hR=Kb(),Ho=Jb(),fR=Ct(),mR=gt(),ig="Array Iterator",bR=tg.set,gR=tg.getterFor(ig);rg.exports=hR(Array,"Array",function(s,e){bR(this,{type:ig,target:dR(s),index:0,kind:e})},function(){var s=gR(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=void 0,Ho(void 0,!0);switch(s.kind){case"keys":return Ho(t,!1);case"values":return Ho(e[t],!1)}return Ho([t,e[t]],!1)},"values");var eg=Zb.Arguments=Zb.Array;jc("keys");jc("values");jc("entries");if(!fR&&mR&&eg.name!=="values")try{pR(eg,"name",{value:"values"})}catch(s){}});var ag=b((rN,sg)=>{"use strict";var SR=Fe(),vR=ir(),yR=SR("iterator"),TR=Array.prototype;sg.exports=function(s){return s!==void 0&&(vR.Array===s||TR[yR]===s)}});var Gc=b((sN,og)=>{"use strict";var IR=ma(),ng=ua(),xR=xr(),ER=ir(),wR=Fe(),PR=wR("iterator");og.exports=function(s){if(!xR(s))return ng(s,PR)||ng(s,"@@iterator")||ER[IR(s)]}});var lg=b((aN,ug)=>{"use strict";var AR=St(),kR=jt(),RR=Ht(),LR=oa(),MR=Gc(),$R=TypeError;ug.exports=function(s,e){var t=arguments.length<2?MR(s):e;if(kR(t))return RR(AR(t,s));throw new $R(LR(s)+" is not iterable")}});var pg=b((nN,dg)=>{"use strict";var BR=St(),cg=Ht(),DR=ua();dg.exports=function(s,e,t){var i,r;cg(s);try{if(i=DR(s,"return"),!i){if(e==="throw")throw t;return t}i=BR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return cg(i),t}});var zo=b((oN,bg)=>{"use strict";var CR=Ar(),VR=St(),OR=Ht(),_R=oa(),FR=ag(),NR=Mr(),hg=na(),UR=lg(),qR=Gc(),fg=pg(),jR=TypeError,Go=function(s,e){this.stopped=s,this.result=e},mg=Go.prototype;bg.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=CR(e,i),l,d,c,h,p,f,m,g=function(y){return l&&fg(l,"normal",y),new Go(!0,y)},S=function(y){return r?(OR(y),o?u(y[0],y[1],g):u(y[0],y[1])):o?u(y,g):u(y)};if(a)l=s.iterator;else if(n)l=s;else{if(d=qR(s),!d)throw new jR(_R(s)+" is not iterable");if(FR(d)){for(c=0,h=NR(s);h>c;c++)if(p=S(s[c]),p&&hg(mg,p))return p;return new Go(!1)}l=UR(s,d)}for(f=a?s.next:l.next;!(m=VR(f,l)).done;){try{p=S(m.value)}catch(y){fg(l,"throw",y)}if(typeof p=="object"&&p&&hg(mg,p))return p}return new Go(!1)}});var Sg=b((uN,gg)=>{"use strict";var HR=gt(),GR=er(),zR=aa();gg.exports=function(s,e,t){HR?GR.f(s,e,zR(0,t)):s[e]=t}});var vg=b(()=>{"use strict";var QR=Ee(),WR=zo(),YR=Sg();QR({target:"Object",stat:!0},{fromEntries:function(e){var t={};return WR(e,function(i,r){YR(t,i,r)},{AS_ENTRIES:!0}),t}})});var Tg=b((dN,yg)=>{"use strict";Hc();vg();var KR=Er();yg.exports=KR.Object.fromEntries});var xg=b((pN,Ig)=>{"use strict";Ig.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 wg=b(()=>{"use strict";Hc();var XR=xg(),JR=ve(),ZR=ba(),Eg=ir();for(Qo in XR)ZR(JR[Qo],Qo),Eg[Qo]=Eg.Array;var Qo});var Ag=b((mN,Pg)=>{"use strict";var eL=Tg();wg();Pg.exports=eL});var zc=b((bN,kg)=>{"use strict";var tL=Ag();kg.exports=tL});var Rg=b(()=>{"use strict"});var Qc=b((vN,Lg)=>{"use strict";var va=ve(),iL=Zi(),rL=Xi(),Wo=function(s){return iL.slice(0,s.length)===s};Lg.exports=function(){return Wo("Bun/")?"BUN":Wo("Cloudflare-Workers")?"CLOUDFLARE":Wo("Deno/")?"DENO":Wo("Node.js/")?"NODE":va.Bun&&typeof Bun.version=="string"?"BUN":va.Deno&&typeof Deno.version=="object"?"DENO":rL(va.process)==="process"?"NODE":va.window&&va.document?"BROWSER":"REST"}()});var Yo=b((yN,Mg)=>{"use strict";var sL=Qc();Mg.exports=sL==="NODE"});var Bg=b((TN,$g)=>{"use strict";var aL=er();$g.exports=function(s,e,t){return aL.f(s,e,t)}});var Vg=b((IN,Cg)=>{"use strict";var nL=hi(),oL=Bg(),uL=Fe(),lL=gt(),Dg=uL("species");Cg.exports=function(s){var e=nL(s);lL&&e&&!e[Dg]&&oL(e,Dg,{configurable:!0,get:function(){return this}})}});var _g=b((xN,Og)=>{"use strict";var cL=na(),dL=TypeError;Og.exports=function(s,e){if(cL(e,s))return s;throw new dL("Incorrect invocation")}});var Yc=b((EN,Fg)=>{"use strict";var pL=$e(),hL=ge(),Wc=la(),fL=pL(Function.toString);hL(Wc.inspectSource)||(Wc.inspectSource=function(s){return fL(s)});Fg.exports=Wc.inspectSource});var Xc=b((wN,Hg)=>{"use strict";var mL=$e(),bL=_e(),Ng=ge(),gL=ma(),SL=hi(),vL=Yc(),Ug=function(){},qg=SL("Reflect","construct"),Kc=/^\s*(?:class|function)\b/,yL=mL(Kc.exec),TL=!Kc.test(Ug),ya=function(e){if(!Ng(e))return!1;try{return qg(Ug,[],e),!0}catch(t){return!1}},jg=function(e){if(!Ng(e))return!1;switch(gL(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return TL||!!yL(Kc,vL(e))}catch(t){return!0}};jg.sham=!0;Hg.exports=!qg||bL(function(){var s;return ya(ya.call)||!ya(Object)||!ya(function(){s=!0})||s})?jg:ya});var zg=b((PN,Gg)=>{"use strict";var IL=Xc(),xL=oa(),EL=TypeError;Gg.exports=function(s){if(IL(s))return s;throw new EL(xL(s)+" is not a constructor")}});var Jc=b((AN,Wg)=>{"use strict";var Qg=Ht(),wL=zg(),PL=xr(),AL=Fe(),kL=AL("species");Wg.exports=function(s,e){var t=Qg(s).constructor,i;return t===void 0||PL(i=Qg(t)[kL])?e:wL(i)}});var Kg=b((kN,Yg)=>{"use strict";var RL=$e();Yg.exports=RL([].slice)});var Jg=b((RN,Xg)=>{"use strict";var LL=TypeError;Xg.exports=function(s,e){if(s<e)throw new LL("Not enough arguments");return s}});var Zc=b((LN,Zg)=>{"use strict";var ML=Zi();Zg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ML)});var ud=b((MN,uS)=>{"use strict";var Tt=ve(),$L=ql(),BL=Ar(),eS=ge(),DL=Vt(),oS=_e(),tS=$c(),CL=Kg(),iS=Ro(),VL=Jg(),OL=Zc(),_L=Yo(),ad=Tt.setImmediate,nd=Tt.clearImmediate,FL=Tt.process,ed=Tt.Dispatch,NL=Tt.Function,rS=Tt.MessageChannel,UL=Tt.String,td=0,Ta={},sS="onreadystatechange",Ia,sr,id,rd;oS(function(){Ia=Tt.location});var od=function(s){if(DL(Ta,s)){var e=Ta[s];delete Ta[s],e()}},sd=function(s){return function(){od(s)}},aS=function(s){od(s.data)},nS=function(s){Tt.postMessage(UL(s),Ia.protocol+"//"+Ia.host)};(!ad||!nd)&&(ad=function(e){VL(arguments.length,1);var t=eS(e)?e:NL(e),i=CL(arguments,1);return Ta[++td]=function(){$L(t,void 0,i)},sr(td),td},nd=function(e){delete Ta[e]},_L?sr=function(s){FL.nextTick(sd(s))}:ed&&ed.now?sr=function(s){ed.now(sd(s))}:rS&&!OL?(id=new rS,rd=id.port2,id.port1.onmessage=aS,sr=BL(rd.postMessage,rd)):Tt.addEventListener&&eS(Tt.postMessage)&&!Tt.importScripts&&Ia&&Ia.protocol!=="file:"&&!oS(nS)?(sr=nS,Tt.addEventListener("message",aS,!1)):sS in iS("script")?sr=function(s){tS.appendChild(iS("script"))[sS]=function(){tS.removeChild(this),od(s)}}:sr=function(s){setTimeout(sd(s),0)});uS.exports={set:ad,clear:nd}});var dS=b(($N,cS)=>{"use strict";var lS=ve(),qL=gt(),jL=Object.getOwnPropertyDescriptor;cS.exports=function(s){if(!qL)return lS[s];var e=jL(lS,s);return e&&e.value}});var ld=b((BN,hS)=>{"use strict";var pS=function(){this.head=null,this.tail=null};pS.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};hS.exports=pS});var mS=b((DN,fS)=>{"use strict";var HL=Zi();fS.exports=/ipad|iphone|ipod/i.test(HL)&&typeof Pebble!="undefined"});var gS=b((CN,bS)=>{"use strict";var GL=Zi();bS.exports=/web0s(?!.*chrome)/i.test(GL)});var ES=b((VN,xS)=>{"use strict";var Dr=ve(),zL=dS(),SS=Ar(),cd=ud().set,QL=ld(),WL=Zc(),YL=mS(),KL=gS(),dd=Yo(),vS=Dr.MutationObserver||Dr.WebKitMutationObserver,yS=Dr.document,TS=Dr.process,Ko=Dr.Promise,fd=zL("queueMicrotask"),Br,pd,hd,Xo,IS;fd||(xa=new QL,Ea=function(){var s,e;for(dd&&(s=TS.domain)&&s.exit();e=xa.get();)try{e()}catch(t){throw xa.head&&Br(),t}s&&s.enter()},!WL&&!dd&&!KL&&vS&&yS?(pd=!0,hd=yS.createTextNode(""),new vS(Ea).observe(hd,{characterData:!0}),Br=function(){hd.data=pd=!pd}):!YL&&Ko&&Ko.resolve?(Xo=Ko.resolve(void 0),Xo.constructor=Ko,IS=SS(Xo.then,Xo),Br=function(){IS(Ea)}):dd?Br=function(){TS.nextTick(Ea)}:(cd=SS(cd,Dr),Br=function(){cd(Ea)}),fd=function(s){xa.head||Br(),xa.add(s)});var xa,Ea;xS.exports=fd});var PS=b((ON,wS)=>{"use strict";wS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Jo=b((_N,AS)=>{"use strict";AS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var ar=b((FN,kS)=>{"use strict";var XL=ve();kS.exports=XL.Promise});var Cr=b((NN,$S)=>{"use strict";var JL=ve(),wa=ar(),ZL=ge(),eM=cc(),tM=Yc(),iM=Fe(),RS=Qc(),rM=Ct(),md=Xl(),LS=wa&&wa.prototype,sM=iM("species"),bd=!1,MS=ZL(JL.PromiseRejectionEvent),aM=eM("Promise",function(){var s=tM(wa),e=s!==String(wa);if(!e&&md===66||rM&&!(LS.catch&&LS.finally))return!0;if(!md||md<51||!/native code/.test(s)){var t=new wa(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[sM]=i,bd=t.then(function(){})instanceof i,!bd)return!0}return!e&&(RS==="BROWSER"||RS==="DENO")&&!MS});$S.exports={CONSTRUCTOR:aM,REJECTION_EVENT:MS,SUBCLASSING:bd}});var Vr=b((UN,DS)=>{"use strict";var BS=jt(),nM=TypeError,oM=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new nM("Bad Promise constructor");e=i,t=r}),this.resolve=BS(e),this.reject=BS(t)};DS.exports.f=function(s){return new oM(s)}});var ZS=b(()=>{"use strict";var uM=Ee(),lM=Ct(),iu=Yo(),Mi=ve(),Nr=St(),CS=$r(),VS=Uc(),cM=ba(),dM=Vg(),pM=jt(),tu=ge(),hM=vt(),fM=_g(),mM=Jc(),US=ud().set,Td=ES(),bM=PS(),gM=Jo(),SM=ld(),qS=kc(),ru=ar(),Id=Cr(),jS=Vr(),su="Promise",HS=Id.CONSTRUCTOR,vM=Id.REJECTION_EVENT,yM=Id.SUBCLASSING,gd=qS.getterFor(su),TM=qS.set,Or=ru&&ru.prototype,nr=ru,Zo=Or,GS=Mi.TypeError,Sd=Mi.document,xd=Mi.process,vd=jS.f,IM=vd,xM=!!(Sd&&Sd.createEvent&&Mi.dispatchEvent),zS="unhandledrejection",EM="rejectionhandled",OS=0,QS=1,wM=2,Ed=1,WS=2,eu,_S,PM,FS,YS=function(s){var e;return hM(s)&&tu(e=s.then)?e:!1},KS=function(s,e){var t=e.value,i=e.state===QS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===WS&&kM(e),e.rejection=Ed),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new GS("Promise-chain cycle")):(l=YS(u))?Nr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},XS=function(s,e){s.notified||(s.notified=!0,Td(function(){for(var t=s.reactions,i;i=t.get();)KS(i,s);s.notified=!1,e&&!s.rejection&&AM(s)}))},JS=function(s,e,t){var i,r;xM?(i=Sd.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Mi.dispatchEvent(i)):i={promise:e,reason:t},!vM&&(r=Mi["on"+s])?r(i):s===zS&&bM("Unhandled promise rejection",t)},AM=function(s){Nr(US,Mi,function(){var e=s.facade,t=s.value,i=NS(s),r;if(i&&(r=gM(function(){iu?xd.emit("unhandledRejection",t,e):JS(zS,e,t)}),s.rejection=iu||NS(s)?WS:Ed,r.error))throw r.value})},NS=function(s){return s.rejection!==Ed&&!s.parent},kM=function(s){Nr(US,Mi,function(){var e=s.facade;iu?xd.emit("rejectionHandled",e):JS(EM,e,s.value)})},_r=function(s,e,t){return function(i){s(e,i,t)}},Fr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=wM,XS(s,!0))},yd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new GS("Promise can't be resolved itself");var i=YS(e);i?Td(function(){var r={done:!1};try{Nr(i,e,_r(yd,r,s),_r(Fr,r,s))}catch(a){Fr(r,a,s)}}):(s.value=e,s.state=QS,XS(s,!1))}catch(r){Fr({done:!1},r,s)}}};if(HS&&(nr=function(e){fM(this,Zo),pM(e),Nr(eu,this);var t=gd(this);try{e(_r(yd,t),_r(Fr,t))}catch(i){Fr(t,i)}},Zo=nr.prototype,eu=function(e){TM(this,{type:su,done:!1,notified:!1,parent:!1,reactions:new SM,rejection:!1,state:OS,value:void 0})},eu.prototype=CS(Zo,"then",function(e,t){var i=gd(this),r=vd(mM(this,nr));return i.parent=!0,r.ok=tu(e)?e:!0,r.fail=tu(t)&&t,r.domain=iu?xd.domain:void 0,i.state===OS?i.reactions.add(r):Td(function(){KS(r,i)}),r.promise}),_S=function(){var s=new eu,e=gd(s);this.promise=s,this.resolve=_r(yd,e),this.reject=_r(Fr,e)},jS.f=vd=function(s){return s===nr||s===PM?new _S(s):IM(s)},!lM&&tu(ru)&&Or!==Object.prototype)){FS=Or.then,yM||CS(Or,"then",function(e,t){var i=this;return new nr(function(r,a){Nr(FS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Or.constructor}catch(s){}VS&&VS(Or,Zo)}uM({global:!0,constructor:!0,wrap:!0,forced:HS},{Promise:nr});cM(nr,su,!1,!0);dM(su)});var sv=b((HN,rv)=>{"use strict";var RM=Fe(),tv=RM("iterator"),iv=!1;try{ev=0,wd={next:function(){return{done:!!ev++}},return:function(){iv=!0}},wd[tv]=function(){return this},Array.from(wd,function(){throw 2})}catch(s){}var ev,wd;rv.exports=function(s,e){try{if(!e&&!iv)return!1}catch(r){return!1}var t=!1;try{var i={};i[tv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Pd=b((GN,av)=>{"use strict";var LM=ar(),MM=sv(),$M=Cr().CONSTRUCTOR;av.exports=$M||!MM(function(s){LM.all(s).then(void 0,function(){})})});var nv=b(()=>{"use strict";var BM=Ee(),DM=St(),CM=jt(),VM=Vr(),OM=Jo(),_M=zo(),FM=Pd();BM({target:"Promise",stat:!0,forced:FM},{all:function(e){var t=this,i=VM.f(t),r=i.resolve,a=i.reject,n=OM(function(){var o=CM(t.resolve),u=[],l=0,d=1;_M(e,function(c){var h=l++,p=!1;d++,DM(o,t,c).then(function(f){p||(p=!0,u[h]=f,--d||r(u))},a)}),--d||r(u)});return n.error&&a(n.value),i.promise}})});var uv=b(()=>{"use strict";var NM=Ee(),UM=Ct(),qM=Cr().CONSTRUCTOR,kd=ar(),jM=hi(),HM=ge(),GM=$r(),ov=kd&&kd.prototype;NM({target:"Promise",proto:!0,forced:qM,real:!0},{catch:function(s){return this.then(void 0,s)}});!UM&&HM(kd)&&(Ad=jM("Promise").prototype.catch,ov.catch!==Ad&&GM(ov,"catch",Ad,{unsafe:!0}));var Ad});var lv=b(()=>{"use strict";var zM=Ee(),QM=St(),WM=jt(),YM=Vr(),KM=Jo(),XM=zo(),JM=Pd();zM({target:"Promise",stat:!0,forced:JM},{race:function(e){var t=this,i=YM.f(t),r=i.reject,a=KM(function(){var n=WM(t.resolve);XM(e,function(o){QM(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var cv=b(()=>{"use strict";var ZM=Ee(),e$=Vr(),t$=Cr().CONSTRUCTOR;ZM({target:"Promise",stat:!0,forced:t$},{reject:function(e){var t=e$.f(this),i=t.reject;return i(e),t.promise}})});var Rd=b((eU,dv)=>{"use strict";var i$=Ht(),r$=vt(),s$=Vr();dv.exports=function(s,e){if(i$(s),r$(e)&&e.constructor===s)return e;var t=s$.f(s),i=t.resolve;return i(e),t.promise}});var fv=b(()=>{"use strict";var a$=Ee(),n$=hi(),pv=Ct(),o$=ar(),hv=Cr().CONSTRUCTOR,u$=Rd(),l$=n$("Promise"),c$=pv&&!hv;a$({target:"Promise",stat:!0,forced:pv||hv},{resolve:function(e){return u$(c$&&this===l$?o$:this,e)}})});var mv=b(()=>{"use strict";ZS();nv();uv();lv();cv();fv()});var vv=b(()=>{"use strict";var d$=Ee(),p$=Ct(),au=ar(),h$=_e(),gv=hi(),Sv=ge(),f$=Jc(),bv=Rd(),m$=$r(),Md=au&&au.prototype,b$=!!au&&h$(function(){Md.finally.call({then:function(){}},function(){})});d$({target:"Promise",proto:!0,real:!0,forced:b$},{finally:function(s){var e=f$(this,gv("Promise")),t=Sv(s);return this.then(t?function(i){return bv(e,s()).then(function(){return i})}:s,t?function(i){return bv(e,s()).then(function(){throw i})}:s)}});!p$&&Sv(au)&&(Ld=gv("Promise").prototype.finally,Md.finally!==Ld&&m$(Md,"finally",Ld,{unsafe:!0}));var Ld});var Tv=b((oU,yv)=>{"use strict";Rg();mv();vv();var g$=Li();yv.exports=g$("Promise","finally")});var xv=b((uU,Iv)=>{"use strict";var S$=Tv();Iv.exports=S$});var Pa=b((lU,Ev)=>{"use strict";var v$=xv();Ev.exports=v$});var Ov=b(()=>{"use strict";var B$=Ee(),D$=Ec().values;B$({target:"Object",stat:!0},{values:function(e){return D$(e)}})});var Fv=b((QU,_v)=>{"use strict";Ov();var C$=Er();_v.exports=C$.Object.values});var Uv=b((WU,Nv)=>{"use strict";var V$=Fv();Nv.exports=V$});var lr=b((YU,qv)=>{"use strict";var O$=Uv();qv.exports=O$});var sy=b(()=>{"use strict";var o0=Ee(),u0=wr(),l0=Mr(),c0=pa(),d0=ha();o0({target:"Array",proto:!0},{at:function(e){var t=u0(this),i=l0(t),r=c0(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});d0("at")});var ny=b((s1,ay)=>{"use strict";sy();var p0=Li();ay.exports=p0("Array","at")});var uy=b((a1,oy)=>{"use strict";var h0=ny();oy.exports=h0});var _t=b((n1,ly)=>{"use strict";var f0=uy();ly.exports=f0});var ep=b((Gj,qy)=>{"use strict";var Q0=Xi();qy.exports=Array.isArray||function(e){return Q0(e)==="Array"}});var Hy=b((zj,jy)=>{"use strict";var W0=TypeError,Y0=9007199254740991;jy.exports=function(s){if(s>Y0)throw W0("Maximum allowed index exceeded");return s}});var Qy=b((Qj,zy)=>{"use strict";var K0=ep(),X0=Mr(),J0=Hy(),Z0=Ar(),Gy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?Z0(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&K0(c)?(h=X0(c),u=Gy(s,e,c,h,u,a-1)-1):(J0(u+1),s[u]=c),u++),l++;return u};zy.exports=Gy});var Xy=b((Wj,Ky)=>{"use strict";var Wy=ep(),eB=Xc(),tB=vt(),iB=Fe(),rB=iB("species"),Yy=Array;Ky.exports=function(s){var e;return Wy(s)&&(e=s.constructor,eB(e)&&(e===Yy||Wy(e.prototype))?e=void 0:tB(e)&&(e=e[rB],e===null&&(e=void 0))),e===void 0?Yy:e}});var Zy=b((Yj,Jy)=>{"use strict";var sB=Xy();Jy.exports=function(s,e){return new(sB(s))(e===0?0:e)}});var eT=b(()=>{"use strict";var aB=Ee(),nB=Qy(),oB=jt(),uB=wr(),lB=Mr(),cB=Zy();aB({target:"Array",proto:!0},{flatMap:function(e){var t=uB(this),i=lB(t),r;return oB(e),r=cB(t,0),r.length=nB(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var tT=b(()=>{"use strict";var dB=ha();dB("flatMap")});var rT=b((eH,iT)=>{"use strict";eT();tT();var pB=Li();iT.exports=pB("Array","flatMap")});var aT=b((tH,sT)=>{"use strict";var hB=rT();sT.exports=hB});var ja=b((iH,nT)=>{"use strict";var fB=aT();nT.exports=fB});var Ha=b((rH,oT)=>{"use strict";var mB=ma(),bB=String;oT.exports=function(s){if(mB(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return bB(s)}});var tp=b((sH,uT)=>{"use strict";uT.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 dT=b((aH,cT)=>{"use strict";var gB=$e(),SB=Ri(),vB=Ha(),rp=tp(),lT=gB("".replace),yB=RegExp("^["+rp+"]+"),TB=RegExp("(^|[^"+rp+"])["+rp+"]+$"),ip=function(s){return function(e){var t=vB(SB(e));return s&1&&(t=lT(t,yB,"")),s&2&&(t=lT(t,TB,"$1")),t}};cT.exports={start:ip(1),end:ip(2),trim:ip(3)}});var mT=b((nH,fT)=>{"use strict";var IB=Mc().PROPER,xB=_e(),pT=tp(),hT="\u200B\x85\u180E";fT.exports=function(s){return xB(function(){return!!pT[s]()||hT[s]()!==hT||IB&&pT[s].name!==s})}});var sp=b((oH,bT)=>{"use strict";var EB=dT().start,wB=mT();bT.exports=wB("trimStart")?function(){return EB(this)}:"".trimStart});var ST=b(()=>{"use strict";var PB=Ee(),gT=sp();PB({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==gT},{trimLeft:gT})});var yT=b(()=>{"use strict";ST();var AB=Ee(),vT=sp();AB({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==vT},{trimStart:vT})});var IT=b((pH,TT)=>{"use strict";yT();var kB=Li();TT.exports=kB("String","trimLeft")});var ET=b((hH,xT)=>{"use strict";var RB=IT();xT.exports=RB});var PT=b((fH,wT)=>{"use strict";var LB=ET();wT.exports=LB});var UT=b(()=>{"use strict"});var qT=b(()=>{"use strict"});var HT=b((W3,jT)=>{"use strict";var ZB=vt(),eD=Xi(),tD=Fe(),iD=tD("match");jT.exports=function(s){var e;return ZB(s)&&((e=s[iD])!==void 0?!!e:eD(s)==="RegExp")}});var zT=b((Y3,GT)=>{"use strict";var rD=Ht();GT.exports=function(){var s=rD(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var YT=b((K3,WT)=>{"use strict";var sD=St(),aD=Vt(),nD=na(),oD=zT(),QT=RegExp.prototype;WT.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in QT)&&!aD(s,"flags")&&nD(QT,s)?sD(oD,s):e}});var XT=b((X3,KT)=>{"use strict";var cp=$e(),uD=wr(),lD=Math.floor,up=cp("".charAt),cD=cp("".replace),lp=cp("".slice),dD=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,pD=/\$([$&'`]|\d{1,2})/g;KT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=pD;return r!==void 0&&(r=uD(r),u=dD),cD(a,u,function(l,d){var c;switch(up(d,0)){case"$":return"$";case"&":return s;case"`":return lp(e,0,t);case"'":return lp(e,n);case"<":c=r[lp(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=lD(h/10);return p===0?l:p<=o?i[p-1]===void 0?up(d,1):i[p-1]+up(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var eI=b(()=>{"use strict";var hD=Ee(),fD=St(),pp=$e(),JT=Ri(),mD=ge(),bD=xr(),gD=HT(),es=Ha(),SD=ua(),vD=YT(),yD=XT(),TD=Fe(),ID=Ct(),xD=TD("replace"),ED=TypeError,dp=pp("".indexOf),wD=pp("".replace),ZT=pp("".slice),PD=Math.max;hD({target:"String",proto:!0},{replaceAll:function(e,t){var i=JT(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!bD(e)){if(r=gD(e),r&&(a=es(JT(vD(e))),!~dp(a,"g")))throw new ED("`.replaceAll` does not allow non-global regexes");if(n=SD(e,xD),n)return fD(n,e,i,t);if(ID&&r)return wD(es(i),e,t)}for(o=es(i),u=es(e),l=mD(t),l||(t=es(t)),d=u.length,c=PD(1,d),h=dp(o,u);h!==-1;)p=l?es(t(u,h,o)):yD(u,o,h,[],void 0,t),m+=ZT(o,f,h)+p,f=h+d,h=h+c>o.length?-1:dp(o,u,h+c);return f<o.length&&(m+=ZT(o,f)),m}})});var iI=b((eG,tI)=>{"use strict";UT();qT();eI();var AD=Li();tI.exports=AD("String","replaceAll")});var sI=b((tG,rI)=>{"use strict";var kD=iI();rI.exports=kD});var hp=b((iG,aI)=>{"use strict";var RD=sI();aI.exports=RD});var oI=b((rG,nI)=>{"use strict";var LD=pa(),MD=Ha(),$D=Ri(),BD=RangeError;nI.exports=function(e){var t=MD($D(this)),i="",r=LD(e);if(r<0||r===1/0)throw new BD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var pI=b((sG,dI)=>{"use strict";var cI=$e(),DD=bc(),uI=Ha(),CD=oI(),VD=Ri(),OD=cI(CD),_D=cI("".slice),FD=Math.ceil,lI=function(s){return function(e,t,i){var r=uI(VD(e)),a=DD(t),n=r.length,o=i===void 0?" ":uI(i),u,l;return a<=n||o===""?r:(u=a-n,l=OD(o,FD(u/o.length)),l.length>u&&(l=_D(l,0,u)),s?r+l:l+r)}};dI.exports={start:lI(!1),end:lI(!0)}});var fI=b((aG,hI)=>{"use strict";var ND=Zi();hI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ND)});var mI=b(()=>{"use strict";var UD=Ee(),qD=pI().start,jD=fI();UD({target:"String",proto:!0,forced:jD},{padStart:function(e){return qD(this,e,arguments.length>1?arguments[1]:void 0)}})});var gI=b((uG,bI)=>{"use strict";mI();var HD=Li();bI.exports=HD("String","padStart")});var vI=b((lG,SI)=>{"use strict";var GD=gI();SI.exports=GD});var fp=b((cG,yI)=>{"use strict";var zD=vI();yI.exports=zD});var $h="2.0.131-dev.c235b295.0";var st=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(st||{}),pi=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(pi||{});var wo=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(wo||{}),Fl=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(Fl||{});var Nl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Nl||{}),Po=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Po||{});var $E=N(yt(),1);import{assertNever as Mm,assertNonNullable as nA,isNonNullable as Mo,ValueSubject as Sc,Subject as oA,Subscription as uA,merge as lA,observableFrom as cA,fromEvent as Am,map as km,tap as Rm,filterChanged as dA,isNullable as vc,ErrorCategory as Lm}from"@vkontakte/videoplayer-shared/es2018";var Pm=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var $o=class{constructor(e){this.connection$=new Sc(void 0);this.castState$=new Sc("NOT_AVAILABLE");this.errorEvent$=new oA;this.realCastState$=new Sc("NOT_AVAILABLE");this.subscription=new uA;this.isDestroyed=!1;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Mo((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Pm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Lm.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Mo(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();vc(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();vc(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Am(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(a=i.getCurrentSession())==null?void 0:a.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 Mm(r.sessionState)}})).add(lA(Am(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Rm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),km(r=>r.castState)),cA([i.getCastState()])).pipe(dA(),km(pA),Rm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let a=r==="CONNECTED",n=Mo(this.connection$.getValue());if(a&&!n){let l=i.getCurrentSession();nA(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(vc(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Mo(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Lm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},pA=s=>{switch(s){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 Mm(s)}};var xh=N(yt(),1),hE=N(tr(),1),fE=N(zc(),1);var Dv=N(Pa(),1);import{assertNever as wv}from"@vkontakte/videoplayer-shared/es2018";var Se=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:wv(t)}return s},$i=(s,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:wv(e)}};var R=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as y$,Subject as nu,merge as Pv}from"@vkontakte/videoplayer-shared/es2018";var j=class{constructor(e){this.transitionStarted$=new nu;this.transitionEnded$=new nu;this.transitionUpdated$=new nu;this.forceChanged$=new nu;this.stateChangeStarted$=Pv(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Pv(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||y$(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as T$}from"@vkontakte/videoplayer-shared/es2018";var Av=s=>{switch(s){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 T$(s)}};import{assertNever as Ur,assertNonNullable as or,debounce as kv,ErrorCategory as Rv,fromEvent as ur,isNonNullable as Lv,map as Mv,merge as $v,observableFrom as I$,Subject as x$,Subscription as $d,timeout as E$,getHighestQuality as w$}from"@vkontakte/videoplayer-shared/es2018";var P$=5,A$=5,k$=500,Bv=7e3,Aa=class{constructor(e){this.subscription=new $d;this.loadMediaTimeoutSubscription=new $d;this.videoState=new j("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Ur(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:Ur(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:Ur(e)}break}default:Ur(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Av(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new $d;this.subscription.add(e),this.subscription.add($v(this.videoState.stateChangeStarted$.pipe(Mv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Mv(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new x$;e.add(r.pipe(kv(k$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=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-a)>P$)&&r.next(o),a=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),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<A$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Ur(n)}}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(ur(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=$v(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,I$(["init"])).pipe(kv(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&R(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let d=t[e];or(d);let c=w$(Object.keys(d));or(c);let h=d[c];or(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];or(d),i=d.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];or(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];or(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];or(d),i=Se(d.url),r="application/x-mpegurl",a=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Rv.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ur(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=a,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Lv(o)&&(n.metadata.title=o),Lv(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(E$(Bv).subscribe(()=>a(`timeout(${Bv})`)))});(0,Dv.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Rv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Jd=N(yt(),1);import{clearVideoElement as Vv}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as R$}from"@vkontakte/videoplayer-shared/es2018";var Cv=s=>{try{s.pause(),s.playbackRate=0,R$(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as L$,Subscription as M$}from"@vkontakte/videoplayer-shared/es2018";var Bd=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)}},Dd=window.WeakMap?new WeakMap:new Bd,Cd=window.WeakMap?new WeakMap:new Map,$$=(s,e=20)=>{let t=0;return L$(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Ne=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Vv(i):(i=document.createElement("video"),s.appendChild(i)),Dd.set(i,r);let a=new M$;return a.add($$(i,e)),Cd.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Ue=s=>{let e=Cd.get(s);e==null||e.unsubscribe(),Cd.delete(s);let t=Dd.get(s);Dd.delete(s),t?Vv(s):Cv(s)};var Od=N(lr(),1);import{assertNonNullable as ka,isNonNullable as zt,isNullable as N$,fromEvent as qr,merge as jv,observableFrom as Hv,filterChanged as Gv,map as Ra,Subject as zv,Subscription as U$,ValueSubject as q$,ErrorCategory as j$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Vd,isNullable as _$,Subscription as F$}from"@vkontakte/videoplayer-shared/es2018";var ou=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=_$(r),l=new F$;return r&&l.add(r.subscribe(d=>{let c=s.getState();i(d,c)&&s.setState(d)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(d=>{t(d.to),u&&s.setState(d.to)},a)),l},wt=(s,e,t)=>ou(e,()=>s.loop,i=>{Vd(i)&&(s.loop=i)},{onError:t}),qe=(s,e,t,i)=>ou(e,()=>({muted:s.muted,volume:s.volume}),r=>{Vd(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),at=(s,e,t,i)=>ou(e,()=>s.playbackRate,r=>{Vd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Bi=ou;var H$=s=>["__",s.language,s.label].join("|"),G$=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},_d=class s{constructor(e){this.available$=new zv;this.current$=new q$(void 0);this.error$=new zv;this.subscription=new U$;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:j$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Bi(t.internalTextTracks,()=>(0,Od.default)(this.internalTracks),a=>{zt(a)&&this.setInternal(a)},{equal:(a,n)=>zt(a)&&zt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ra(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Bi(t.externalTextTracks,()=>(0,Od.default)(this.externalTracks),a=>{zt(a)&&this.setExternal(a)},{equal:(a,n)=>zt(a)&&zt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ra(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Bi(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Bi(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){ka(this.video);let{textTracks:e}=this.video;this.subscription.add(qr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(jv(qr(e,"addtrack"),qr(e,"removetrack"),Hv(["init"])).pipe(Ra(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Gv((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(jv(qr(e,"change"),Hv(["init"])).pipe(Ra(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ra(i=>i&&this.htmlTextTrackToITextTrack(i).id),Gv()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(qr(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var l,d,c,h,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((h=(c=o.target)==null?void 0:c.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(qr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;zt(t.align)&&(r.align=t.align),zt(t.position)&&(r.position=t.position),zt(t.size)&&(r.size=t.size),zt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ka(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:H$(e),a=this.externalTracks.has(r),n=(l=a?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){ka(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(N$(e)||!G$(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){ka(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){ka(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},nt=_d;var cr=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 Qv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Fd=s=>{let e=Qv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Wv=s=>{let e=Qv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as ot,map as Di,merge as Ud,filterChanged as e0,isNonNullable as iy,Subject as t0,filter as Ma,mapTo as qd,combine as i0,once as r0,throttle as s0,ErrorCategory as a0,ValueSubject as ry,Subscription as n0}from"@vkontakte/videoplayer-shared/es2018";var z$=3,Yv=(s,e,t=z$)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var uu=class{constructor(){this._isMiuiBrowser=!1}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}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/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._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var Kv=N(yt(),1);var La=()=>{var s,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((s=navigator.appVersion)!=null?s:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var lu=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,Kv.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=La()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){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,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let a=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(a);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var cu=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var It=()=>window.ManagedMediaSource||window.MediaSource,jr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Xv=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},du=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Q$=document.createElement("video"),W$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Y$='video/mp4; codecs="hev1.1.6.L93.B0"',Jv='video/webm; codecs="vp09.00.10.08"',Zv='video/webm; codecs="av01.0.00M.08"',K$='audio/mp4; codecs="mp4a.40.2"',X$='audio/webm; codecs="opus"',ey,J$=async()=>{if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Zv}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Jv}})]);ey={DASH_WEBM_AV1:e,DASH_WEBM:t}};J$().catch(s=>{console.log(Q$),console.error(s)});var pu=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 ey}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,a,n,o,u,l,d,c,h,p,f,m,g,S,y,v,I;this._video=document.createElement("video");try{this._protocols={mms:jr(),mse:Xv(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(a=this._video).canPlayType)!=null&&n.call(a,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let T=!!((d=(l=It())==null?void 0:l.isTypeSupported)!=null&&d.call(l,W$)),E=!!((h=(c=It())==null?void 0:c.isTypeSupported)!=null&&h.call(c,Y$)),V=!!((f=(p=It())==null?void 0:p.isTypeSupported)!=null&&f.call(p,K$));this._codecs={h264:T,h265:E,vp9:!!((g=(m=It())==null?void 0:m.isTypeSupported)!=null&&g.call(m,Jv)),av1:!!((y=(S=It())==null?void 0:S.isTypeSupported)!=null&&y.call(S,Zv)),aac:V,opus:!!((I=(v=It())==null?void 0:v.isTypeSupported)!=null&&I.call(v,X$)),mpeg:(T||E)&&V},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}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 ty="audio/mpeg",hu=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,ty))},this._codecs={mp3:!!((r=(i=It())==null?void 0:i.isTypeSupported)!=null&&r.call(i,ty))}}catch(a){console.error(a)}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 Z$}from"@vkontakte/videoplayer-shared/es2018";var Nd=class{constructor(){this.isInited$=new Z$(!1);this._displayChecker=new cu,this._deviceChecker=new lu(this._displayChecker),this._browserChecker=new uu,this._videoChecker=new pu(this._deviceChecker,this._browserChecker),this._audioChecker=new hu,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)}},q=new Nd;var je=s=>{let e=P=>ot(s,P).pipe(qd(void 0)),t=new n0,i=()=>t.unsubscribe(),a=Ud(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>ot(s,P))).pipe(Di(P=>P.type==="ended"?s.readyState<2:s.readyState<3),e0()),n=Ud(ot(s,"progress"),ot(s,"timeupdate")).pipe(Di(()=>Yv(s.buffered,s.currentTime))),o=q.browser.isSafari?i0({play:e("play").pipe(r0()),playing:e("playing")}).pipe(qd(void 0)):e("playing"),u=ot(s,"volumechange").pipe(Di(()=>({muted:s.muted,volume:s.volume}))),l=ot(s,"ratechange").pipe(Di(()=>s.playbackRate)),d=ot(s,"error").pipe(Ma(()=>!!(s.error||s.played.length)),Di(()=>{var O;let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:a0.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(O=s.error)!=null?O:void 0}})),c=ot(s,"timeupdate").pipe(Di(()=>s.currentTime)),h=new t0,p=.3,f;t.add(c.subscribe(P=>{s.loop&&iy(f)&&iy(P)&&f>=s.duration-p&&P<=p&&h.next(f),f=P}));let m=e("pause").pipe(Ma(()=>!s.error&&f!==s.duration)),g=ot(s,"enterpictureinpicture"),S=ot(s,"leavepictureinpicture"),y=new ry(Wv(s));t.add(g.subscribe(()=>y.next(!0))),t.add(S.subscribe(()=>y.next(!1)));let v=new ry(Fd(s)),I=ot(s,"fullscreenchange");t.add(I.pipe(Di(()=>Fd(s))).subscribe(v));let T=.1,E=1e3,V=ot(s,"timeupdate").pipe(Ma(P=>s.duration-s.currentTime<T)),L=Ud(V.pipe(Ma(P=>!s.loop)),ot(s,"ended")).pipe(s0(E),qd(void 0)),k=V.pipe(Ma(P=>s.loop));return{playing$:o,pause$:m,canplay$:e("canplay"),ended$:L,looped$:h,loopExpected$:k,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:ot(s,"durationchange").pipe(Di(()=>s.duration)),isBuffering$:a,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:y,inFullscreen$:v,enterPip$:g,leavePip$:S,destroy:i}};import{VideoQuality as Ci}from"@vkontakte/videoplayer-shared/es2018";var Qt=s=>{switch(s){case"mobile":return Ci.Q_144P;case"lowest":return Ci.Q_240P;case"low":return Ci.Q_360P;case"sd":case"medium":return Ci.Q_480P;case"hd":case"high":return Ci.Q_720P;case"fullhd":case"full":return Ci.Q_1080P;case"quadhd":case"quad":return Ci.Q_1440P;case"ultrahd":case"ultra":return Ci.Q_2160P}};var tt=N(_t(),1),Gd=N(yt(),1),dr=N(tr(),1);import{isNonNullable as ie,isNullable as Su,now as vy,isHigher as vu,isHigherOrEqual as Gr,isInvariantQuality as yu,isLowerOrEqual as zr,videoSizeToQuality as yy,assertNotEmptyArray as Tu,assertNonNullable as Ty}from"@vkontakte/videoplayer-shared/es2018";var jd=!1,mi={},cy=s=>{jd=s},dy=()=>{mi={}},py=s=>{s(mi)},$a=(s,e)=>{var t;jd&&(mi.meta=(t=mi.meta)!=null?t:{},mi.meta[s]=e)},et=class{constructor(e){this.name=e}next(e){var i,r;if(!jd)return;mi.series=(i=mi.series)!=null?i:{};let t=(r=mi.series[this.name])!=null?r:[];t.push([Date.now(),e]),mi.series[this.name]=t}};import{isHigher as m0,isHigherOrEqual as p1,isLower as hy,isLowerOrEqual as h1,isNonNullable as fu,isNullable as b0,videoHeightToQuality as mu}from"@vkontakte/videoplayer-shared/es2018";function Hd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function bu(s,e,t){return!!s&&Hd(s,e,t)==="high_quality"}function Hr(s,e,t){return b0(s)||fu(s.min)&&fu(s.max)&&hy(s.max,s.min)||fu(s.min)&&e&&m0(s.min,e)||fu(s.max)&&t&&hy(s.max,t)}function fy({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Hr({max:s!=null&&s.max?mu(s.max):void 0,min:s!=null&&s.min?mu(s.min):void 0},e?mu(e):void 0,t?mu(t):void 0)}var Iy=new et("best_bitrate"),Iu=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Qr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Vi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=vy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},xu='Assertion "ABR Tracks is empty array" failed',gu=new WeakMap,my=new WeakMap,by=new WeakMap,Ba=(s,e,t,i)=>{var u;let r=[...e].sort(Qr(1)),a=[...t].sort(Qr(1)),n=a.filter(l=>ie(l.bitrate)&&ie(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,tt.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,tt.default)(a,-1);return o&&(0,Gd.default)(n,o)?o:n.length?(0,tt.default)(n,-1):(0,tt.default)(a,0)},Da=(s,e,t,i)=>{var u;let r=gu.get(e);r||(r=[...e].sort(Qr(1)),gu.set(e,r));let a=gu.get(t);a||(a=[...t].sort(Qr(1)),gu.set(t,a));let n=by.get(s);n||(n=a.filter(l=>ie(l.bitrate)&&ie(s.bitrate)?s.bitrate/l.bitrate>i:!0),by.set(s,n));let o=(u=(0,tt.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,tt.default)(a,-1);return o&&(0,Gd.default)(n,o)?o:n.length?(0,tt.default)(n,-1):(0,tt.default)(a,0)},gy=s=>"quality"in s,Eu=(s,e,t,i)=>{var n;let r=ie((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&ie(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&vy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!a&&i.recordSelection(t),a&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=gy(o)?"video":"audio",l=gy(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},
|
|
9
|
+
`}),o}return i==null||i.recordSwitch(t),t},g0=(s,e)=>Math.log(e)/Math.log(s),xy=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&q.display.pixelRatio){let a=q.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,d=g0(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return bu(t,s.highQualityLimit,s.trafficSavingLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Sy=new WeakMap,Wt=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:f,panelSize:m})=>{var M,Q,U,w,F;Tu(s,xu);let{containerSizeFactor:g,containerSizeLimit:S}=xy({container:e,tuning:i,limits:r,panelSize:m}),y=i.considerPlaybackRate&&ie(o)?o:1,v=Sy.get(s);v||(v=s.filter(A=>!yu(A.quality)).sort((A,x)=>vu(A.quality,x.quality)?-1:1),Sy.set(s,v));let I=(M=(0,tt.default)(v,-1))==null?void 0:M.quality,T=(Q=(0,tt.default)(v,0))==null?void 0:Q.quality,E=Hr(r,T,I),V=y*Iu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},k=null;for(let A of v){let x=!0;if(S)if(A.size)x=A.size.width<=S.width&&A.size.height<=S.height;else{let Oe=S&&yy(S);x=Oe?zr(A.quality,Oe):!0}if(!x){L[A.quality]="FitsContainer";continue}let B=p||t,oe=ie(B)&&isFinite(B)&&ie(A.bitrate)?B-a>=A.bitrate*V:!0,Ve=bu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===A.quality;if(!oe&&!Ve){L[A.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&ie(i.minBufferToSwitchUp)&&u&&!yu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&vu(A.quality,u.quality)){L[A.quality]="Buffer";continue}if(!!c&&Gr(A.quality,c)&&!Ve){L[A.quality]="DroppedFramesLimit";continue}if(!!h&&Gr(A.quality,h)&&!Ve){L[A.quality]="StallsLimit";continue}let Te=E||(Su(r==null?void 0:r.max)||zr(A.quality,r.max))&&(Su(r==null?void 0:r.min)||Gr(A.quality,r.min)),Ie=ie(d)&&!d?zr(A.quality,i.backgroundVideoQualityLimit):!0;if(!Te||!Ie){L[A.quality]="FitsQualityLimits";continue}k||(k=A)}k&&k.bitrate&&Iy.next(k.bitrate);let P=(U=k!=null?k:(0,tt.default)(v,-1))!=null?U:s[0],O=l==null?void 0:l.last,$=Eu(i,f,P,l);return ie(l)&&$.quality!==(O==null?void 0:O.quality)&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${
|
|
12
|
+
${s.map(A=>{var x,B;return`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate}, size: ${(x=A.size)==null?void 0:x.width}:${(B=A.size)==null?void 0:B.height} }`}).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,dr.default)(i!=null?i:{}).map(([A,x])=>`${A}: ${x}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
20
|
containerSizeFactor: ${g},
|
|
21
|
-
containerSizeLimit: ${(
|
|
21
|
+
containerSizeLimit: ${(w=S==null?void 0:S.width)!=null?w:0} x ${(F=S==null?void 0:S.height)!=null?F:0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${p},
|
|
24
|
-
reserve: ${
|
|
24
|
+
reserve: ${a},
|
|
25
25
|
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${y},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${V},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${c},
|
|
31
31
|
stallsVideoMaxQualityLimit: ${h},
|
|
32
|
-
limitsAreInvalid: ${
|
|
32
|
+
limitsAreInvalid: ${E},
|
|
33
33
|
maxQualityLimit: ${r==null?void 0:r.max},
|
|
34
34
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,
|
|
37
|
+
${(0,dr.default)(L).map(([A,x])=>`${A}: ${x}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`})
|
|
40
|
+
[best video track] ${k==null?void 0:k.quality}
|
|
41
|
+
[selected video track] ${$==null?void 0:$.quality}
|
|
42
|
+
`}),$},wu=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:f,panelSize:m})=>{var Q,U,w,F,A;Tu(s,xu);let{containerSizeFactor:g,containerSizeLimit:S}=xy({container:e,tuning:i,limits:r,panelSize:m}),y=i.considerPlaybackRate&&ie(o)?o:1,v=s.filter(x=>!yu(x.quality)).sort((x,B)=>vu(x.quality,B.quality)?-1:1),I=(Q=(0,tt.default)(v,-1))==null?void 0:Q.quality,T=(U=(0,tt.default)(v,0))==null?void 0:U.quality,E=Hr(r,I,T),V=y*Iu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},P=v.filter(x=>{let B=!0;if(S)if(x.size)B=x.size.width<=S.width&&x.size.height<=S.height;else{let Et=S&&yy(S);B=Et?zr(x.quality,Et):!0}if(!B)return L[x.quality]="FitsContainer",!1;let oe=p||t,Ve=ie(oe)&&isFinite(oe)&&ie(x.bitrate)?oe-a>=x.bitrate*V:!0,se=bu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===x.quality;if(!Ve&&!se)return L[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&ie(i.minBufferToSwitchUp)&&u&&!yu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&vu(x.quality,u.quality))return L[x.quality]="Buffer",!1;if(!!c&&Gr(x.quality,c)&&!se)return L[x.quality]="DroppedFramesLimit",!1;if(!!h&&Gr(x.quality,h)&&!se)return L[x.quality]="StallsLimit",!1;let Ie=E||(Su(r==null?void 0:r.max)||zr(x.quality,r.max))&&(Su(r==null?void 0:r.min)||Gr(x.quality,r.min)),Oe=ie(d)&&!d?zr(x.quality,i.backgroundVideoQualityLimit):!0;return!Ie||!Oe?(L[x.quality]="FitsQualityLimits",!1):!0})[0];P&&P.bitrate&&Iy.next(P.bitrate);let O=(w=P!=null?P:(0,tt.default)(v,-1))!=null?w:s[0],$=l==null?void 0:l.last,M=Eu(i,f,O,l);return ie(l)&&M.quality!==($==null?void 0:$.quality)&&f({message:`
|
|
43
|
+
[VIDEO TRACKS ABR]
|
|
44
|
+
[available video tracks]
|
|
45
|
+
${s.map(x=>{var B,oe;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(B=x.size)==null?void 0:B.width}:${(oe=x.size)==null?void 0:oe.height} }`}).join(`
|
|
46
|
+
`)}
|
|
47
|
+
|
|
48
|
+
[tuning]
|
|
49
|
+
${(0,dr.default)(i!=null?i:{}).map(([x,B])=>`${x}: ${B}`).join(`
|
|
50
|
+
`)}
|
|
51
|
+
|
|
52
|
+
[limit params]
|
|
53
|
+
containerSizeFactor: ${g},
|
|
54
|
+
containerSizeLimit: ${(F=S==null?void 0:S.width)!=null?F:0} x ${(A=S==null?void 0:S.height)!=null?A:0},
|
|
55
|
+
estimatedThroughput: ${t},
|
|
56
|
+
stallsPredictedThroughput: ${p},
|
|
57
|
+
reserve: ${a},
|
|
58
|
+
playbackRate: ${o},
|
|
59
|
+
playbackRateFactor: ${y},
|
|
60
|
+
forwardBufferHealth: ${n},
|
|
61
|
+
bitrateFactor: ${V},
|
|
62
|
+
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
|
+
droppedVideoMaxQualityLimit: ${c},
|
|
64
|
+
stallsVideoMaxQualityLimit: ${h},
|
|
65
|
+
limitsAreInvalid: ${E},
|
|
66
|
+
maxQualityLimit: ${r==null?void 0:r.max},
|
|
67
|
+
minQualityLimit: ${r==null?void 0:r.min},
|
|
68
|
+
|
|
69
|
+
[limited video tracks]
|
|
70
|
+
${(0,dr.default)(L).map(([x,B])=>`${x}: ${B}`).join(`
|
|
71
|
+
`)||"All tracks are available"}
|
|
72
|
+
|
|
73
|
+
[best video track] ${P==null?void 0:P.quality}
|
|
74
|
+
[selected video track] ${M==null?void 0:M.quality}
|
|
75
|
+
`}),M},Pu=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Tu(t,xu);let d=r.considerPlaybackRate&&ie(a)?a:1,c=[...t].sort(Qr(-1)),h=s.bitrate;Ty(h);let p=d*Iu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Ba(s,e,t,r.minVideoAudioRatio),g=l||i;ie(g)&&isFinite(g)&&(f=c.find(v=>ie(v.bitrate)&&ie(m==null?void 0:m.bitrate)?g-h>=v.bitrate*p&&v.bitrate>=m.bitrate:!1)),f||(f=m);let S=o==null?void 0:o.last,y=f&&Eu(r,u,f,o);return ie(o)&&(y==null?void 0:y.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
43
76
|
[AUDIO TRACKS ABR]
|
|
44
77
|
[available audio tracks]
|
|
45
|
-
${t.map(
|
|
78
|
+
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
46
79
|
`)}
|
|
47
80
|
|
|
48
81
|
[tuning]
|
|
49
|
-
${(0,
|
|
82
|
+
${(0,dr.default)(r!=null?r:{}).map(([v,I])=>`${v}: ${I}`).join(`
|
|
50
83
|
`)}
|
|
51
84
|
|
|
52
85
|
[limit params]
|
|
53
86
|
estimatedThroughput: ${i},
|
|
54
87
|
stallsPredictedThroughput: ${l},
|
|
55
88
|
reserve: ${h},
|
|
56
|
-
playbackRate: ${
|
|
57
|
-
playbackRateFactor: ${
|
|
89
|
+
playbackRate: ${a},
|
|
90
|
+
playbackRateFactor: ${d},
|
|
58
91
|
forwardBufferHealth: ${n},
|
|
59
92
|
bitrateFactor: ${p},
|
|
60
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
61
94
|
|
|
62
|
-
[selected audio track] ${
|
|
63
|
-
`}),S};var oe=a=>new URL(a).hostname;import{assertNever as hv,assertNonNullable as mv,combine as eL,debounce as tL,ErrorCategory as fv,filter as bv,filterChanged as iL,isNonNullable as dl,map as un,merge as gv,observableFrom as rL,once as aL,Subscription as sL,ValueSubject as pl,videoQualityToHeight as vv,videoSizeToQuality as nL}from"@vkontakte/videoplayer-shared/es2018";var lv=C(Dt(),1);var av=C(Be(),1),rv=a=>{if(a instanceof DOMException&&(0,av.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},ke=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!rv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return rv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as sn,isNullable as O$,assertNonNullable as Qr}from"@vkontakte/videoplayer-shared/es2018";var nv=C(ji(),1);import{isNonNullable as sv,assertNonNullable as an,now as D$}from"@vkontakte/videoplayer-shared/es2018";function ue(){return D$()}function ol(a){return ue()-a}function ul(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ov(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Gi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;an(c);let L=ol(c),k;if(L<b){k=b-L,setTimeout(g,k);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,R()},v=L=>(s=L,U),S=L=>(d=L,U),y=()=>(p="json",U),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},T=L=>(h=L,U),R=()=>{c=ue(),n=new r,n.open("get",a);let L=0,k,W=0,ae=()=>(an(c),Math.max(c,Math.max(k||0,W||0)));if(s&&n.addEventListener("progress",A=>{let B=ue();s.updateChunk&&A.loaded>L&&(s.updateChunk(ae(),A.loaded-L),L=A.loaded,k=B)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;an(n);let A=n.status;if(A>=200&&A<300){let{response:B,responseType:Y}=n,E=B==null?void 0:B.byteLength;if(typeof E=="number"&&s){let $=E-L;$&&s.updateChunk&&s.updateChunk(ae(),$)}Y==="json"&&(!B||!(0,nv.default)(B).length)?I():(d&&d(),e(B))}else I()}),n.addEventListener("error",()=>{I()}),h){let A=()=>{an(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(W=ue(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=p,n.send(),U},U={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:L=>(l=L,U),withRetryInterval:(L,k)=>(sv(L)&&(b=L),sv(k)&&(m=k),U),withTimeout:L=>(o=L,U),withFinally:S,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return U}var Hr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var uv=C(ji(),1);var jr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ue(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ue()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Gi(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ue()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ue();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,uv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as B$}from"@vkontakte/videoplayer-shared/es2018";var nn=1e4,ll=3;var _$=6e4,N$=10,F$=1,q$=500,Gr=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.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new B$,this.chunkRateEstimator=new Hr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ul(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ul(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(N.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Qg({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,lv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||sn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ov(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new jr(ll,nn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},h=(I,T,R)=>{u&&u.abort(),u=Gi(this.urlResolver.resolve(I,!1),T,R,()=>this._retryCallback()).withTimeout(nn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ll).withFinally(()=>{u=null}).send()},p=(I,T,R)=>{Qr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let T=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${T}=>${I}`),i.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let R=ue()-1e4,q=0;for(let _=0;_<this.bufferStates.length;_++){let w=this.bufferStates[_];I=Math.min(I,w.buf),w.ts<R&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${I} drop=${q} jitter=${this.sourceJitter}`);let O=I-F$;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},v=I=>{let T,R=()=>T&&T.start?T.start.length:0,q=A=>T.start[A]/1e3,O=A=>T.dur[A]/1e3,_=A=>T.fragIndex+A,w=(A,B)=>({chunkIdx:_(A),startTS:q(A),dur:O(A),discontinuity:B}),U=()=>{let A=0;if(T&&T.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,E=B;this.sourceJitter>1&&(E+=this.sourceJitter-1);let $=T.dur.length-1;for(;$>=0&&(E-=T.dur[$],!(E<=0));--$);A=Math.min($,T.dur.length-1-Y),A=Math.max(A,0)}return w(A,!0)},L=A=>{let B=R();if(!(B<=0)){if(sn(A)){for(let Y=0;Y<B;Y++)if(q(Y)>A)return w(Y)}return U()}},k=A=>{let B=R(),Y=A?A.chunkIdx+1:0,E=Y-T.fragIndex;if(!(B<=0)){if(!A||E<0||E-B>N$)return t(`Resync: offset=${E} bChunks=${B} chunk=`+JSON.stringify(A)),U();if(!(E>=B))return w(Y-T.fragIndex,!1)}},W=(A,B,Y)=>{l&&l.abort(),l=Gi(this.urlResolver.resolve(A,!0,this.lowLatency),B,Y,()=>this._retryCallback()).withTimeout(nn).withRetryCount(ll).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,B)=>{W(I,Y=>{if(!d())return;T=Y;let E=!!T.lowLatency;E!==this.lowLatency&&b(E);let $=0;for(let ce=0;ce<T.dur.length;++ce)$+=T.dur[ce];$>0&&(Qr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration($/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,A(L(B))},()=>this._handleNetworkError())},nextChunk:k}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Qr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:T,logger:R}=this.params,q=v(e.jidxUrl),O,_,w,U,L=0,k,W,ae,A=()=>{k&&(clearTimeout(k),k=void 0);let Q=Math.max(q$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=L+Q,Te=ue(),Ie=Math.min(1e4,be-Te);L=Te;let Xe=()=>{l||d()&&q.seek(()=>{d()&&(L=ue(),B(),A())})};Ie>0?k=window.setTimeout(()=>{this.paused?A():Xe()},Ie):Xe()},B=()=>{let Q;for(;Q=q.nextChunk(U);)U=Q,bi(Q);let be=q.nextChunk(w);if(be){if(w&&be.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?A():(S(),this._initPlayerWith(e));return}ce(be)}else A()},Y=(Q,be)=>{if(!d()||!this.sourceBuffer)return;let Te,Ie,Xe,ot=yt=>{window.setTimeout(()=>{d()&&Y(Q,be)},yt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),ot(100);else{let yt=ue(),jt=T.currentTime;!this.paused&&T.buffered.length>1&&W===jt&&yt-ae>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),W!==jt&&(W=jt,ae=yt);let gi=this._getBufferSizeSec();if(gi>30)R(`Buffered ${gi} seconds; delaying appendBuffer`),ot(2e3);else try{this.sourceBuffer.appendBuffer(Q),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:gi}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(sr){if(sr.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Xe=this.sourceBuffer.buffered.length,Xe!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=jt,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),ot(1e3);else throw sr}}},E=()=>{_&&O&&(R([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(w)]),Y(_,function(){_=null,B()}))},$=Q=>e.fragUrlTemplate.replace("%%id%%",Q.chunkIdx),ce=Q=>{d()&&p($(Q),(be,Te)=>{if(d()){if(Te/=1e3,_=be,w=Q,n=Q.startTS,Te){let Ie=Math.min(10,Q.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}E()}},()=>this._handleNetworkError())},bi=Q=>{d()&&(Qr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve($(Q),!1)))},nt=Q=>{d()&&(e.cachedHeader=Q,Y(Q,()=>{O=!0,E()}))};s=!0,q.seek(Q=>{if(d()){if(L=ue(),!Q){A();return}U=Q,!O$(I)||Q.startTS>I?ce(Q):(w=Q,B())}},I),e.cachedHeader?nt(e.cachedHeader):h(e.headerUrl,nt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),sn(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Qr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return sn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=ue();if(this.chunkRateEstimator.addInterval(h,m,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ol(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ue();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Gi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(nn).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;ke(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},_$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var pv=C(Ci(),1);import{debounce as U$,filter as cv,fromEvent as H$,interval as j$,isHigher as Q$,isInvariantQuality as G$,isLower as W$,merge as Y$,Subject as dv,Subscription as z$}from"@vkontakte/videoplayer-shared/es2018";var cl=class{constructor(){this.onDroopedVideoFramesLimit$=new dv;this.subscription=new z$;this.playing=!1;this.tracks=[];this.forceChecker$=new dv;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!G$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Q$(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(H$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=j$(this.droppedFramesChecker.checkTime).pipe(cv(()=>this.playing),cv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(U$(this.droppedFramesChecker.checkTime)),i=Y$(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,pv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>W$(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},on=cl;import{map as K$,Observable as X$}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as J$}from"@vkontakte/videoplayer-shared/es2018";var Wr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var Z$=(a,e)=>new X$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Wr()))},{...i,...e});r.observe(a);let s=J$(document,"visibilitychange").pipe(K$(n=>!document.hidden||Wr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Fe=Z$;var oL=["paused","playing","ready"],uL=["paused","playing","ready"],Yr=class{constructor(e){this.subscription=new sL;this.videoState=new D("stopped");this.representations$=new pl([]);this.droppedFramesManager=new on;this.maxSeekBackTime$=new pl(1/0);this.zeroTime$=new pl(void 0);this.liveOffset=new ui;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:fv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=Ct(u.name))!=null?i:nL(u.video),d=u.bitrate/1e3,h={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),dl(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,hl.default)(uL,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,hl.default)(oL,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(he(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(he(this.params.source.url,u))}return;default:return hv(e)}};this.textTracksManager=new Ne(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:fv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(gv(this.videoState.stateChangeStarted$.pipe(un(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(un(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ae(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(un(r=>r.map(({track:s})=>s)),bv(r=>!!r.length),aL()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(iL(),un(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(eL({zeroTime:this.zeroTime$.pipe(bv(dl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(it(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(_e(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Fe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&vv(r),min:s&&vv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return hv(r.to)}},t)).add(gv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,rL(["init"])).pipe(tL(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),xe(this.video)}createLiveDashPlayer(){let e=new Gr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&dl(t)?t:Ot(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;mv(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;mv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(he(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Sv=Yr;var qy=C(Be(),1);var Wi=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as HC,assertNonNullable as jC,debounce as QC,ErrorCategory as _y,filter as ec,filterChanged as Oa,fromEvent as GC,isNonNullable as Ny,map as tc,merge as Rn,observableFrom as ic,once as Fy,Subscription as WC}from"@vkontakte/videoplayer-shared/es2018";var ln=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Yi=class extends ln{constructor(){super(),this.listeners||ln.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)}},zr=class{constructor(){Object.defineProperty(this,"signal",{value:new Yi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(zr.prototype[Symbol.toStringTag]="AbortController",Yi.prototype[Symbol.toStringTag]="AbortSignal");function cn(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 ml(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!cn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Kr=cn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),yv=Kr?ml({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,at=Kr?yv.fetch:window.fetch,uq=Kr?yv.Request:window.Request,me=Kr?zr:window.AbortController,lq=Kr?Yi:window.AbortSignal;var Kl=C(bl(),1);var nS=C(sS(),1);import{ErrorCategory as Jr}from"@vkontakte/videoplayer-shared/es2018";var oS=a=>{if(!a)return{id:"EmptyResponse",category:Jr.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Jr.NETWORK,message:`UV Error ${a}`};let e=(0,nS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Jr.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:Jr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Jr.PARSER,message:"Response is valid XML, but parser failed"}};var Bt=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Wl,assertNonNullable as er,combine as tr,ErrorCategory as st,filter as In,filterChanged as Ca,flattenObject as Da,fromEvent as gt,getTraceSubscriptionMethod as PC,interval as Yl,isNonNullable as Va,isNullable as Ly,map as ir,merge as mi,now as zl,Subject as En,Subscription as My,tap as wC,throttle as AC,ValueSubject as Z}from"@vkontakte/videoplayer-shared/es2018";var pn=C(Be(),1),Ji=C(Dt(),1),hn=C(bl(),1);var WL=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},YL=a=>window.clearTimeout(a),uS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),lS=!uS(window.requestIdleCallback)||!uS(window.cancelIdleCallback),Tl=lS?WL:window.requestIdleCallback,Zr=lS?YL:window.cancelIdleCallback;var vy=C(Hs(),1);import{assertNever as zL,ErrorCategory as cS,Subject as dS}from"@vkontakte/videoplayer-shared/es2018";var KL=18,pS=!1;try{pS=N.browser.isSafari&&!!N.browser.safariVersion&&N.browser.safariVersion<=KL}catch(a){console.error(a)}var Il=class{constructor(e){this.bufferFull$=new dS;this.error$=new dS;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:cS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};pS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:cS.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:zL(t)}}},hS=Il;var El=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 Nt,assertNonNullable as Re,ErrorCategory as bt,fromEvent as Fl,getExponentialDelay as ql,isNonNullable as Xi,isNullable as fe,now as dn,once as pC,Subject as hC,Subscription as mC,ValueSubject as di}from"@vkontakte/videoplayer-shared/es2018";var H=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var zi=class extends H{};var ea=class extends H{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ta=class extends H{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var ia=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=class extends H{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&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 aa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var sa=class extends H{constructor(e,t){super(e,t),this.data=this.content}};var li=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 i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var na=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var oa=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ua=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 la=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ca=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 da=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=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 ha=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ma=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ba=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=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 va=class extends J{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Sa=class extends J{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ya=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=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 Ia=class extends H{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var JL={ftyp:ta,moov:ia,mvhd:ra,moof:aa,mdat:sa,sidx:li,trak:na,mdia:da,mfhd:fa,tkhd:pa,traf:ba,tfhd:ga,tfdt:va,trun:Sa,minf:ha,sv3d:oa,st3d:ua,prhd:la,proj:ma,equi:ca,uuid:ea,stbl:ya,stsd:Ta,avc1:Ia,unknown:zi},mt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=JL[e];return i?new i(t,new a):new zi(t,new a)}};var _t=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var eM=new TextDecoder("ascii"),tM=a=>eM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",iM=a=>{let e=new li(a,new mt),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},rM=(a,e)=>{let i=new mt().parse(a),r=new _t(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},aM=a=>{let t=new mt().parse(a),i=new _t(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},sM=a=>{var r;let t=new mt().parse(a);return(r=new _t(t).find("sidx"))==null?void 0:r.timescale},nM=(a,e)=>{let i=new mt().parse(a),s=new _t(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},oM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new mt().parse(a),r=new _t(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},mS={validateData:tM,parseInit:oM,getIndexRange:()=>{},parseSegments:iM,parseFeedableSegmentChunk:rM,getChunkEndTime:nM,getServerLatencyTimestamps:aM,getTimescaleFromIndex:sM};var xa=C(Be(),1);import{assertNonNullable as Pl,isNonNullable as vS,isNullable as lM}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as uM}from"@vkontakte/videoplayer-shared/es2018";var fS={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},bS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Ea(a,t),r=i in fS,s=r?fS[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Ea(u),d=l*2**((o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},Ea=(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 Ea(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:uM(e)}},ci=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=bS(i);if(!e(r))return;r.type==="master"&&ci(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},gS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=bS(a);return ci(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ze(o,n):s===17026?t=ze(o,n):s===17029&&(i=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var SS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],cM=[231,22612,22743,167,171,163,160,175],dM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return ci(a,({tag:h,type:p,value:m,valueSize:b})=>{if(h===21419){let g=ze(m,p);l=Ea(g)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=ze(m,p):h===17545?r=ze(m,p):h===21420&&l===475249515?u=ze(m,p):h===374648427?ci(m,({tag:g,type:v,value:S})=>g===30321?(c=ze(S,v)===1,!1):!0):s&&n&&(0,xa.default)(SS,h)&&(o=!0),!o}),Pl(e,"Failed to parse webm Segment start"),Pl(t,"Failed to parse webm Segment end"),Pl(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},pM=a=>{if(lM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},hM=(a,e)=>{let t=!1,i=!1,r=o=>vS(o.time)&&vS(o.position),s=[],n;return ci(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=ze(l,u));break;case 183:break;case 241:n&&(n.position=ze(l,u));break;default:t&&(0,xa.default)(SS,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},mM=a=>{let e=0,t=!1;try{ci(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,xa.default)(cM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,xa.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},yS={validateData:gS,parseInit:dM,getIndexRange:pM,parseSegments:hM,parseFeedableSegmentChunk:mM};var Pa=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return yS;case"mp4":return mS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Bl=C(FS(),1),py=C(Ci(),1),hy=C(iy(),1),my=C(Dt(),1),_l=C(ji(),1);var ry=C(Be(),1),Ll=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,ry.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as dC,isNullable as cy}from"@vkontakte/videoplayer-shared/es2018";var ay=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var sy=a=>{var e;try{let t=lC(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function lC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
64
|
-
|
|
95
|
+
[selected audio track] ${y==null?void 0:y.id}
|
|
96
|
+
`}),y},Au=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Tu(t,xu);let d=r.considerPlaybackRate&&ie(a)?a:1,c=my.get(t);c||(c=[...t].sort(Qr(-1)),my.set(t,c));let h=s.bitrate;Ty(h);let p=d*Iu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Da(s,e,t,r.minVideoAudioRatio),g=l||i;ie(g)&&isFinite(g)&&(f=c.find(v=>ie(v.bitrate)&&ie(m==null?void 0:m.bitrate)?g-h>=v.bitrate*p&&v.bitrate>=m.bitrate:!1)),f||(f=m);let S=o==null?void 0:o.last,y=f&&Eu(r,u,f,o);return ie(o)&&(y==null?void 0:y.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
|
|
97
|
+
[AUDIO TRACKS ABR]
|
|
98
|
+
[available audio tracks]
|
|
99
|
+
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
100
|
+
`)}
|
|
101
|
+
|
|
102
|
+
[tuning]
|
|
103
|
+
${(0,dr.default)(r!=null?r:{}).map(([v,I])=>`${v}: ${I}`).join(`
|
|
104
|
+
`)}
|
|
105
|
+
|
|
106
|
+
[limit params]
|
|
107
|
+
estimatedThroughput: ${i},
|
|
108
|
+
stallsPredictedThroughput: ${l},
|
|
109
|
+
reserve: ${h},
|
|
110
|
+
playbackRate: ${a},
|
|
111
|
+
playbackRateFactor: ${d},
|
|
112
|
+
forwardBufferHealth: ${n},
|
|
113
|
+
bitrateFactor: ${p},
|
|
114
|
+
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
|
+
|
|
116
|
+
[selected audio track] ${y==null?void 0:y.id}
|
|
117
|
+
`}),y};var we=s=>new URL(s).hostname;import{assertNever as Dy,assertNonNullable as Cy,combine as _0,debounce as F0,ErrorCategory as Vy,filter as Oy,filterChanged as N0,isNonNullable as Kd,map as Mu,merge as _y,observableFrom as U0,once as q0,Subscription as j0,ValueSubject as Xd,videoQualityToHeight as Fy,videoSizeToQuality as H0}from"@vkontakte/videoplayer-shared/es2018";var Ly=N(_t(),1);var wy=N(yt(),1),Ey=s=>{if(s instanceof DOMException&&(0,wy.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},He=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!Ey(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return Ey(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Ru,isNullable as y0,assertNonNullable as Oa}from"@vkontakte/videoplayer-shared/es2018";var Ay=N(lr(),1);import{isNonNullable as Py,assertNonNullable as ku,now as S0}from"@vkontakte/videoplayer-shared/es2018";function Be(){return S0()}function zd(s){return Be()-s}function Qd(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ky(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Wr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,d,c,h=!1,p="arraybuffer",f=7e3,m=2e3,g=()=>{if(u)return;ku(d);let $=zd(d),M;if($<m){M=m-$,setTimeout(g,M);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,E()},S=$=>(a=$,O),y=$=>(c=$,O),v=()=>(p="json",O),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},T=$=>(h=$,O),E=()=>{d=Be(),n=new r,n.open("get",s);let $=0,M,Q=0,U=()=>(ku(d),Math.max(d,Math.max(M||0,Q||0)));if(a&&n.addEventListener("progress",w=>{let F=Be();a.updateChunk&&w.loaded>$&&(a.updateChunk(U(),w.loaded-$),$=w.loaded,M=F)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;ku(n);let w=n.status;if(w>=200&&w<300){let{response:F,responseType:A}=n,x=F==null?void 0:F.byteLength;if(typeof x=="number"&&a){let B=x-$;B&&a.updateChunk&&a.updateChunk(U(),B)}A==="json"&&(!F||!(0,Ay.default)(F).length)?I():(c&&c(),e(F))}else I()}),n.addEventListener("error",()=>{I()}),h){let w=()=>{ku(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=Be(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=p,n.send(),O},O={withBitrateReporting:S,withParallel:T,withJSONResponse:v,withRetryCount:$=>(l=$,O),withRetryInterval:($,M)=>(Py($)&&(m=$),Py(M)&&(f=M),O),withTimeout:$=>(o=$,O),withFinally:y,send:E,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return O}var Ca=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ry=N(lr(),1);var Va=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Be(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Be()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Wr(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Be()}_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=Be();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Ry.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._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(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}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 T0}from"@vkontakte/videoplayer-shared/es2018";var Lu=1e4,Wd=3;var I0=6e4,x0=10,E0=1,w0=500,_a=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.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new T0,this.chunkRateEstimator=new Ca(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Qd(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Qd(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(q.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!fy({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Ly.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ru(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ky(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Va(Wd,Lu,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let I=a&&(!d||d===this.rep);return I||t("Not running!"),I},h=(I,T,E)=>{u&&u.abort(),u=Wr(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withTimeout(Lu).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Wd).withFinally(()=>{u=null}).send()},p=(I,T,E)=>{Oa(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,E,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let T=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${T}=>${I}`),i.playbackRate=I)},m=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let E=Be()-1e4,V=0;for(let k=0;k<this.bufferStates.length;k++){let P=this.bufferStates[k];I=Math.min(I,P.buf),P.ts<E&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${I} drop=${V} jitter=${this.sourceJitter}`);let L=I-E0;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?f(1.15):L>1?f(1.1):L>.3?f(1.05):f(1)}},S=I=>{let T,E=()=>T&&T.start?T.start.length:0,V=w=>T.start[w]/1e3,L=w=>T.dur[w]/1e3,k=w=>T.fragIndex+w,P=(w,F)=>({chunkIdx:k(w),startTS:V(w),dur:L(w),discontinuity:F}),O=()=>{let w=0;if(T&&T.dur){let F=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,A=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=F;this.sourceJitter>1&&(x+=this.sourceJitter-1);let B=T.dur.length-1;for(;B>=0&&(x-=T.dur[B],!(x<=0));--B);w=Math.min(B,T.dur.length-1-A),w=Math.max(w,0)}return P(w,!0)},$=w=>{let F=E();if(!(F<=0)){if(Ru(w)){for(let A=0;A<F;A++)if(V(A)>w)return P(A)}return O()}},M=w=>{let F=E(),A=w?w.chunkIdx+1:0,x=A-T.fragIndex;if(!(F<=0)){if(!w||x<0||x-F>x0)return t(`Resync: offset=${x} bChunks=${F} chunk=`+JSON.stringify(w)),O();if(!(x>=F))return P(A-T.fragIndex,!1)}},Q=(w,F,A)=>{l&&l.abort(),l=Wr(this.urlResolver.resolve(w,!0,this.lowLatency),F,A,()=>this._retryCallback()).withTimeout(Lu).withRetryCount(Wd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,F)=>{Q(I,A=>{if(!c())return;T=A;let x=!!T.lowLatency;x!==this.lowLatency&&m(x);let B=0;for(let oe=0;oe<T.dur.length;++oe)B+=T.dur[oe];B>0&&(Oa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,w($(F))},()=>this._handleNetworkError())},nextChunk:M}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Oa(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:T,logger:E}=this.params,V=S(e.jidxUrl),L,k,P,O,$=0,M,Q,U,w=()=>{M&&(clearTimeout(M),M=void 0);let K=Math.max(w0,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=$+K,Te=Be(),Ie=Math.min(1e4,ye-Te);$=Te;let Oe=()=>{l||c()&&V.seek(()=>{c()&&($=Be(),F(),w())})};Ie>0?M=window.setTimeout(()=>{this.paused?w():Oe()},Ie):Oe()},F=()=>{let K;for(;K=V.nextChunk(O);)O=K,Ve(K);let ye=V.nextChunk(P);if(ye){if(P&&ye.discontinuity){E("Detected discontinuity; restarting playback"),this.paused?w():(y(),this._initPlayerWith(e));return}oe(ye)}else w()},A=(K,ye)=>{if(!c()||!this.sourceBuffer)return;let Te,Ie,Oe,Et=At=>{window.setTimeout(()=>{c()&&A(K,ye)},At)};if(this.sourceBuffer.updating)E("Source buffer is updating; delaying appendBuffer"),Et(100);else{let At=Be(),qt=T.currentTime;!this.paused&&T.buffered.length>1&&Q===qt&&At-U>500&&(E("Stall suspected; trying to fix"),this._fixupStall()),Q!==qt&&(Q=qt,U=At);let Jt=this._getBufferSizeSec();if(Jt>30)E(`Buffered ${Jt} seconds; delaying appendBuffer`),Et(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:At,buf:Jt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(ki){if(ki.name==="QuotaExceededError")E("QuotaExceededError; delaying appendBuffer"),Oe=this.sourceBuffer.buffered.length,Oe!==0&&(Te=this.sourceBuffer.buffered.start(0),Ie=qt,Ie-Te>4&&this.sourceBuffer.remove(Te,Ie-3)),Et(1e3);else throw ki}}},x=()=>{k&&L&&(E([`Appending chunk, sz=${k.byteLength}:`,JSON.stringify(P)]),A(k,function(){k=null,F()}))},B=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),oe=K=>{c()&&p(B(K),(ye,Te)=>{if(c()){if(Te/=1e3,k=ye,P=K,n=K.startTS,Te){let Ie=Math.min(10,K.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ie:Ie}x()}},()=>this._handleNetworkError())},Ve=K=>{c()&&(Oa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(K),!1)))},se=K=>{c()&&(e.cachedHeader=K,A(K,()=>{L=!0,x()}))};a=!0,V.seek(K=>{if(c()){if($=Be(),!K){w();return}O=K,!y0(I)||K.startTS>I?oe(K):(P=K,F())}},I),e.cachedHeader?se(e.cachedHeader):h(e.headerUrl,se,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Ru(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Oa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ru(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),f=c/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(h,p)=>{let f=Be();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&zd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{let p=a.updateChunk(c,h);return p&&l(),p},notifySwitch:c=>{let h=Be();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Wr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Lu).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;He(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},I0))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var By=N(tr(),1);import{debounce as P0,filter as My,fromEvent as A0,interval as k0,isHigher as R0,isInvariantQuality as L0,isLower as M0,merge as $0,Subject as $y,Subscription as B0}from"@vkontakte/videoplayer-shared/es2018";var Yd=class{constructor(){this.onDroopedVideoFramesLimit$=new $y;this.subscription=new B0;this.playing=!1;this.tracks=[];this.forceChecker$=new $y;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&&!L0(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&R0(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(A0(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=k0(this.droppedFramesChecker.checkTime).pipe(My(()=>this.playing),My(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(P0(this.droppedFramesChecker.checkTime)),i=$0(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,By.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>M0(a,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Yr=Yd;import{map as D0,Observable as C0}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as V0}from"@vkontakte/videoplayer-shared/es2018";var Fa=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var O0=(s,e)=>new C0(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Fa()))},{...i,...e});r.observe(s);let a=V0(document,"visibilitychange").pipe(D0(n=>!document.hidden||Fa())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),ut=O0;var G0=["paused","playing","ready"],z0=["paused","playing","ready"],Na=class{constructor(e){this.subscription=new j0;this.videoState=new j("stopped");this.representations$=new Xd([]);this.droppedFramesManager=new Yr;this.maxSeekBackTime$=new Xd(1/0);this.zeroTime$=new Xd(void 0);this.liveOffset=new cr;this._dashCb=e=>{var t,i,r,a;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:Vy.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),d=(i=Qt(u.name))!=null?i:H0(u.video),c=u.bitrate/1e3,h={...u.video};if(!d)continue;let p={id:l,quality:d,bitrate:c,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:a.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Kd(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Jd.default)(z0,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,Jd.default)(G0,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(Se(this.params.source.url,u))}return;default:return Dy(e)}};this.textTracksManager=new nt(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Vy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(_y(this.videoState.stateChangeStarted$.pipe(Mu(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Mu(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=je(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Mu(r=>r.map(({track:a})=>a)),Oy(r=>!!r.length),q0()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(N0(),Mu(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(_0({zeroTime:this.zeroTime$.pipe(Oy(Kd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(wt(this.video,this.params.desiredState.isLooped,t)).add(qe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(at(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ut(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Fy(r),min:a&&Fy(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.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 Dy(r.to)}},t)).add(_y(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U0(["init"])).pipe(F0(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),Ue(this.video)}createLiveDashPlayer(){let e=new _a({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,d,c,h,p,f;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(h=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Kd(t)?t:Wt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,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}),a=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let m=(f=e.find(({track:g})=>g.id===a))==null?void 0:f.representation;Cy(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Cy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Se(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Ny=Na;var ex=N(yt(),1);var De=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as AC,assertNonNullable as kC,debounce as RC,ErrorCategory as XI,filter as Vp,filterChanged as sl,fromEvent as LC,isNonNullable as JI,map as Op,merge as al,observableFrom as _p,once as ZI,Subscription as MC}from"@vkontakte/videoplayer-shared/es2018";var $u=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Kr=class extends $u{constructor(){super(),this.listeners||$u.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)}},Ua=class{constructor(){Object.defineProperty(this,"signal",{value:new Kr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ua.prototype[Symbol.toStringTag]="AbortController",Kr.prototype[Symbol.toStringTag]="AbortSignal");function Bu(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Zd(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Bu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let h=new t(l,d);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let h=new Promise((p,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:a}}var qa=Bu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Uy=qa?Zd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Pt=qa?Uy.fetch:window.fetch,qj=qa?Uy.Request:window.Request,ae=qa?Ua:window.AbortController,jj=qa?Kr:window.AbortSignal;var $p=N(ja(),1);var AT=N(PT(),1);import{ErrorCategory as Ga}from"@vkontakte/videoplayer-shared/es2018";var Du=s=>{if(!s)return{id:"EmptyResponse",category:Ga.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:Ga.NETWORK,message:`UV Error ${s}`};let e=(0,AT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ga.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ga.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ga.PARSER,message:"Response is valid XML, but parser failed"}};var Ge=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as Rp,assertNonNullable as ns,combine as os,ErrorCategory as Kt,filter as Ku,filterChanged as wn,flattenObject as Pn,fromEvent as Ti,getTraceSubscriptionMethod as lC,interval as Lp,isNonNullable as An,isNullable as HI,map as us,merge as mr,now as Mp,Subject as Xu,Subscription as GI,tap as cC,throttle as dC,ValueSubject as he}from"@vkontakte/videoplayer-shared/es2018";var Ou=N(yt(),1),rs=N(_t(),1),_u=N(ja(),1);var MB=(s,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},$B=s=>window.clearTimeout(s),kT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),RT=!kT(window.requestIdleCallback)||!kT(window.cancelIdleCallback),Xr=RT?MB:window.requestIdleCallback,Yt=RT?$B:window.cancelIdleCallback;var DI=N(Pa(),1);import{assertNever as BB,ErrorCategory as LT,Subject as MT}from"@vkontakte/videoplayer-shared/es2018";var DB=18,$T=!1;try{$T=q.browser.isSafari&&!!q.browser.safariVersion&&q.browser.safariVersion<=DB}catch(s){console.error(s)}var ap=class{constructor(e){this.bufferFull$=new MT;this.error$=new MT;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:LT.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(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};$T&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:LT.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:BB(t)}}},BT=ap;var Jr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as _i,assertNonNullable as lt,ErrorCategory as Si,fromEvent as xp,getExponentialDelay as Ep,isNonNullable as is,isNullable as ze,now as Vu,once as XD,Subject as JD,Subscription as ZD,ValueSubject as fr}from"@vkontakte/videoplayer-shared/es2018";var X=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Zr=class extends X{};var za=class extends X{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Qa=class extends X{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Wa=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ue=class extends X{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ya=class extends ue{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 Ka=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends X{constructor(e,t){super(e,t),this.data=this.content}};var pr=class extends ue{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Ja=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var en=class extends ue{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 tn=class extends ue{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var rn=class extends ue{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var sn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var an=class extends ue{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 nn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var on=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var un=class extends ue{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ln=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var cn=class extends ue{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 dn=class extends ue{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var pn=class extends ue{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var hn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fn=class extends ue{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 mn=class extends X{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var VB={ftyp:Qa,moov:Wa,mvhd:Ya,moof:Ka,mdat:Xa,sidx:pr,trak:Ja,mdia:sn,mfhd:un,tkhd:an,traf:ln,tfhd:cn,tfdt:dn,trun:pn,minf:nn,sv3d:Za,st3d:en,prhd:tn,proj:on,equi:rn,uuid:za,stbl:hn,stsd:fn,avc1:mn,unknown:Zr},bi=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=VB[e];return i?new i(t,new s):new Zr(t,new s)}};var Oi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var _B=new TextDecoder("ascii"),FB=s=>_B.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",NB=s=>{let e=new pr(s,new bi),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},UB=(s,e)=>{let i=new bi().parse(s),r=new Oi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},qB=s=>{let t=new bi().parse(s),i=new Oi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},jB=s=>{var r;let t=new bi().parse(s);return(r=new Oi(t).find("sidx"))==null?void 0:r.timescale},HB=(s,e)=>{let i=new bi().parse(s),a=new Oi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},GB=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new bi().parse(s),r=new Oi(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},DT={validateData:FB,parseInit:GB,getIndexRange:()=>{},parseSegments:NB,parseFeedableSegmentChunk:UB,getChunkEndTime:HB,getServerLatencyTimestamps:qB,getTimescaleFromIndex:jB};var gn=N(yt(),1);import{assertNonNullable as op,isNonNullable as _T,isNullable as QB}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as zB}from"@vkontakte/videoplayer-shared/es2018";var CT={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"}},VT=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=bn(s,t),r=i in CT,a=r?CT[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=bn(u),c=l*2**((o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},bn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ft=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return bn(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:zB(e)}},hr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=VT(i);if(!e(r))return;r.type==="master"&&hr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},OT=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=VT(s);return hr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ft(o,n):a===17026?t=Ft(o,n):a===17029&&(i=Ft(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var FT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],WB=[231,22612,22743,167,171,163,160,175],YB=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return hr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Ft(f,p);l=bn(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=Ft(f,p):h===17545?r=Ft(f,p):h===21420&&l===475249515?u=Ft(f,p):h===374648427?hr(f,({tag:g,type:S,value:y})=>g===30321?(d=Ft(y,S)===1,!1):!0):a&&n&&(0,gn.default)(FT,h)&&(o=!0),!o}),op(e,"Failed to parse webm Segment start"),op(t,"Failed to parse webm Segment end"),op(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},KB=s=>{if(QB(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},XB=(s,e)=>{let t=!1,i=!1,r=o=>_T(o.time)&&_T(o.position),a=[],n;return hr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Ft(l,u));break;case 183:break;case 241:n&&(n.position=Ft(l,u));break;default:t&&(0,gn.default)(FT,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},JB=s=>{let e=0,t=!1;try{hr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,gn.default)(WB,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,gn.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},NT={validateData:OT,parseInit:YB,getIndexRange:KB,parseSegments:XB,parseFeedableSegmentChunk:JB};var Sn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return NT;case"mp4":return DT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var yp=N(hp(),1),RI=N(tr(),1),LI=N(fp(),1),MI=N(_t(),1),Tp=N(lr(),1);var TI=N(yt(),1),ts=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,TI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as YD,isNullable as AI}from"@vkontakte/videoplayer-shared/es2018";var Cu=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var II=s=>{var e;try{let t=QD(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,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 QD(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
118
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
65
119
|
(-(?<script>[a-z]{4}))?
|
|
66
120
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
67
121
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
68
122
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
69
123
|
(?:-(?<privateuse>(?:${e})))?
|
|
70
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Cl=C(Dt(),1);import{videoSizeToQuality as cC}from"@vkontakte/videoplayer-shared/es2018";var ny=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Ct(s):void 0)!=null?u:cC({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},oy=({id:a,bitrate:e})=>({id:a,bitrate:e}),uy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),ly=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Dl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Cl.default)(i.split("."),0),isDefault:r}),Vl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Cl.default)(r.split("."),0)}),Ol=a=>"url"in a,ye=a=>a.type==="template",wa=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var dy=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ft=(a,e)=>{let t=a;t=(0,Bl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,py.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Bl.default)(t,n,(o,u)=>cy(s)?o:cy(u)?s:(0,hy.default)(s,parseInt(u,10),"0"))}return t},fy=(a,e)=>{var _,w,U,L,k,W,ae,A,B,Y,E,$,ce,bi,nt,Q,be,Te,Ie,Xe,ot,yt,jt,gi,sr,Ec,xc,Pc,wc,Ac,kc,Rc,$c,Lc,Mc,Cc,Dc,Vc,Oc,Bc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,id,rd,ad;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(qe=>{var X,Qt;return(Qt=(X=qe.textContent)==null?void 0:X.trim())!=null?Qt:""}),o=(_=(0,my.default)(n,0))!=null?_:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],h=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=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:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],I=y.reduce((qe,X)=>({...qe,[X.id]:X.children}),{}),T=y.reduce((qe,X)=>({...qe,[X.id]:X.getAttribute("duration")}),{});S?v=dy(S):(0,_l.default)(T).filter(qe=>qe).length&&!u?v=(0,_l.default)(T).reduce((qe,X)=>{var Qt;return qe+((Qt=dy(X))!=null?Qt:0)},0):b&&(v=parseInt(b,10));let R=0,q=(U=(w=s.getAttribute("profiles"))==null?void 0:w.split(","))!=null?U:[];for(let qe of y.map(X=>X.id))for(let X of I[qe]){let Qt=(L=X.getAttribute("id"))!=null?L:"id"+(R++).toString(10),nr=(k=X.getAttribute("mimeType"))!=null?k:"",Qn=(W=X.getAttribute("codecs"))!=null?W:"",Gn=(ae=X.getAttribute("contentType"))!=null?ae:nr==null?void 0:nr.split("/")[0],_T=(B=(A=X.getAttribute("profiles"))==null?void 0:A.split(","))!=null?B:[],sd=(E=sy((Y=X.getAttribute("lang"))!=null?Y:""))!=null?E:{},za=(bi=(ce=($=X.querySelector("Label"))==null?void 0:$.textContent)==null?void 0:ce.trim())!=null?bi:void 0,NT=X.querySelectorAll("Representation"),FT=X.querySelector("SegmentTemplate"),qT=(Q=(nt=X.querySelector("Role"))==null?void 0:nt.getAttribute("value"))!=null?Q:void 0,vi=Gn,te={id:Qt,language:sd.language,isDefault:qT==="main",label:za,codecs:Qn,hdr:vi==="video"&&Ll(Qn),mime:nr,representations:[]};for(let K of NT){let Tt=(be=K.getAttribute("lang"))!=null?be:void 0,or=(Ie=(Te=za!=null?za:X.getAttribute("label"))!=null?Te:K.getAttribute("label"))!=null?Ie:void 0,Ka=(yt=(ot=(Xe=K.querySelector("BaseURL"))==null?void 0:Xe.textContent)==null?void 0:ot.trim())!=null?yt:"",Gt=new URL(Ka||o,e).toString(),It=(jt=K.getAttribute("mimeType"))!=null?jt:nr,Xa=(sr=(gi=K.getAttribute("codecs"))!=null?gi:Qn)!=null?sr:"",Ja;if(Gn==="text"){let Et=K.getAttribute("id")||"",Za=((Ec=sd.privateuse)==null?void 0:Ec.includes("x-auto"))||Et.includes("_auto"),Wt=K.querySelector("SegmentTemplate");if(Wt){let ur={representationId:(xc=K.getAttribute("id"))!=null?xc:void 0,bandwidth:(Pc=K.getAttribute("bandwidth"))!=null?Pc:void 0},es=parseInt((wc=K.getAttribute("bandwidth"))!=null?wc:"",10)/1e3,ts=(kc=parseInt((Ac=Wt.getAttribute("startNumber"))!=null?Ac:"",10))!=null?kc:1,Si=parseInt((Rc=Wt.getAttribute("timescale"))!=null?Rc:"",10),Wn=($c=Wt.querySelectorAll("SegmentTimeline S"))!=null?$c:[],yi=Wt.getAttribute("media");if(!yi)continue;let is=[],rs=0,as="",Ti=0,lr=ts,ge=0;for(let Ue of Wn){let Yt=parseInt((Lc=Ue.getAttribute("d"))!=null?Lc:"",10),Oe=parseInt((Mc=Ue.getAttribute("r"))!=null?Mc:"",10)||0,xt=parseInt((Cc=Ue.getAttribute("t"))!=null?Cc:"",10);ge=Number.isFinite(xt)?xt:ge;let zt=Yt/Si*1e3,Pt=ge/Si*1e3;for(let Je=0;Je<Oe+1;Je++){let wt=ft(yi,{...ur,segmentNumber:lr.toString(10),segmentTime:(ge+Je*Yt).toString(10)}),Ii=(Pt!=null?Pt:0)+Je*zt,dr=Ii+zt;lr++,is.push({time:{from:Ii,to:dr},url:wt})}ge+=(Oe+1)*Yt,rs+=(Oe+1)*zt}Ti=ge/Si*1e3,as=ft(yi,{...ur,segmentNumber:lr.toString(10),segmentTime:ge.toString(10)});let cr={time:{from:Ti,to:1/0},url:as},ut={type:"template",baseUrl:Gt,segmentTemplateUrl:yi,initUrl:"",totalSegmentsDurationMs:rs,segments:is,nextSegmentBeyondManifest:cr,timescale:Si};Ja={id:Et,kind:"text",segmentReference:ut,profiles:[],duration:v,bitrate:es,mime:"",codecs:"",width:0,height:0,isAuto:Za}}else Ja={id:Et,isAuto:Za,kind:"text",url:Gt}}else{let Et=(Vc=(Dc=K.getAttribute("contentType"))!=null?Dc:It==null?void 0:It.split("/")[0])!=null?Vc:Gn,Za=(Bc=(Oc=X.getAttribute("profiles"))==null?void 0:Oc.split(","))!=null?Bc:[],Wt=parseInt((_c=K.getAttribute("width"))!=null?_c:"",10),ur=parseInt((Nc=K.getAttribute("height"))!=null?Nc:"",10),es=parseInt((Fc=K.getAttribute("bandwidth"))!=null?Fc:"",10)/1e3,ts=(qc=K.getAttribute("frameRate"))!=null?qc:"",Si=(Uc=K.getAttribute("quality"))!=null?Uc:void 0,Wn=ts?ay(ts):void 0,yi=(Hc=K.getAttribute("id"))!=null?Hc:"id"+(R++).toString(10),is=Et==="video"?`${ur}p`:Et==="audio"?`${es}Kbps`:Xa,rs=`${yi}@${is}`,as=[...q,..._T,...Za],Ti,lr=K.querySelector("SegmentBase"),ge=(jc=K.querySelector("SegmentTemplate"))!=null?jc:FT;if(lr){let ut=(Gc=(Qc=K.querySelector("SegmentBase Initialization"))==null?void 0:Qc.getAttribute("range"))!=null?Gc:"",[Ue,Yt]=ut.split("-").map(wt=>parseInt(wt,10)),Oe={from:Ue,to:Yt},xt=(Wc=K.querySelector("SegmentBase"))==null?void 0:Wc.getAttribute("indexRange"),[zt,Pt]=xt?xt.split("-").map(wt=>parseInt(wt,10)):[],Je=xt?{from:zt,to:Pt}:void 0;Ti={type:"byteRange",url:Gt,initRange:Oe,indexRange:Je}}else if(ge){let ut={representationId:(Yc=K.getAttribute("id"))!=null?Yc:void 0,bandwidth:(zc=K.getAttribute("bandwidth"))!=null?zc:void 0},Ue=parseInt((Kc=ge.getAttribute("timescale"))!=null?Kc:"",10),Yt=(Xc=ge.getAttribute("initialization"))!=null?Xc:"",Oe=ge.getAttribute("media"),xt=(Zc=parseInt((Jc=ge.getAttribute("startNumber"))!=null?Jc:"",10))!=null?Zc:1,zt=ft(Yt,ut);if(!Oe)throw new ReferenceError("No media attribute in SegmentTemplate");let Pt=(ed=ge.querySelectorAll("SegmentTimeline S"))!=null?ed:[],Je=[],wt=0,Ii="",dr=0;if(Pt.length){let ss=xt,He=0;for(let Ei of Pt){let Ze=parseInt((td=Ei.getAttribute("d"))!=null?td:"",10),Kt=parseInt((id=Ei.getAttribute("r"))!=null?id:"",10)||0,ns=parseInt((rd=Ei.getAttribute("t"))!=null?rd:"",10);He=Number.isFinite(ns)?ns:He;let Yn=Ze/Ue*1e3,zn=He/Ue*1e3;for(let os=0;os<Kt+1;os++){let HT=ft(Oe,{...ut,segmentNumber:ss.toString(10),segmentTime:(He+os*Ze).toString(10)}),nd=(zn!=null?zn:0)+os*Yn,jT=nd+Yn;ss++,Je.push({time:{from:nd,to:jT},url:HT})}He+=(Kt+1)*Ze,wt+=(Kt+1)*Yn}dr=He/Ue*1e3,Ii=ft(Oe,{...ut,segmentNumber:ss.toString(10),segmentTime:He.toString(10)})}else if(dC(v)){let He=parseInt((ad=ge.getAttribute("duration"))!=null?ad:"",10)/Ue*1e3,Ei=Math.ceil(v/He),Ze=0;for(let Kt=1;Kt<Ei;Kt++){let ns=ft(Oe,{...ut,segmentNumber:Kt.toString(10),segmentTime:Ze.toString(10)});Je.push({time:{from:Ze,to:Ze+He},url:ns}),Ze+=He}dr=Ze,Ii=ft(Oe,{...ut,segmentNumber:Ei.toString(10),segmentTime:Ze.toString(10)})}let UT={time:{from:dr,to:1/0},url:Ii};Ti={type:"template",baseUrl:Gt,segmentTemplateUrl:Oe,initUrl:zt,totalSegmentsDurationMs:wt,segments:Je,nextSegmentBeyondManifest:UT,timescale:Ue}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Et||!It)continue;let cr={video:"video",audio:"audio",text:"text"}[Et];if(!cr)continue;vi||(vi=cr),Ja={id:rs,kind:cr,segmentReference:Ti,profiles:as,duration:v,bitrate:es,mime:It,codecs:Xa,width:Wt,height:ur,fps:Wn,quality:Si}}te.language||(te.language=Tt),te.label||(te.label=or),te.mime||(te.mime=It),te.codecs||(te.codecs=Xa),te.hdr||(te.hdr=vi==="video"&&Ll(Xa)),te.representations.push(Ja)}if(vi){let K=r[vi].find(Tt=>Tt.id===te.id);if(K&&te.representations.every(Tt=>ye(Tt.segmentReference)))for(let Tt of K.representations){let or=te.representations.find(It=>It.id===Tt.id),Ka=or==null?void 0:or.segmentReference,Gt=Tt.segmentReference;Gt.segments.push(...Ka.segments),Gt.nextSegmentBeyondManifest=Ka.nextSegmentBeyondManifest}else r[vi].push(te)}}return{duration:v,streams:r,baseUrls:n,live:g}};var gy=C(Be(),1);import{isNonNullable as by}from"@vkontakte/videoplayer-shared/es2018";var re=(a,e)=>by(a)&&by(e)&&a.readyState==="open"&&(0,gy.default)([...a.activeSourceBuffers],e);var Aa=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new di(0);this.currentLowLatencySegmentLength$=new di(0);this.currentSegmentLength$=new di(0);this.onLastSegment$=new di(!1);this.fullyBuffered$=new di(!1);this.playingRepresentation$=new di(void 0);this.playingRepresentationInit$=new di(void 0);this.error$=new hC;this.gaps=[];this.subscription=new mC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new me;this.switchAbortController=new me;this.destroyAbortController=new me;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Nt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Re(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new hS(this.sourceBuffer),this.subscription.add(Fl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:bt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Fl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:bt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!re(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,El(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Re(i,"No init buffer for starting representation"),Re(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Nt(this.destroyAbortController.signal,async function*(e,t=!1){if(!re(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!re(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();Xi(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=Nt(this.destroyAbortController.signal,async function*(e,t=!1){if(!re(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Re(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(fe(s)||fe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Re(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!re(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();Xi(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=Nt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,hn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!ye(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Re(r);let s=this.segments.get(i);Re(s,"No segments for starting representation");let n=this.initData.get(i);if(Re(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!re(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new me,Nt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Re(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(fe(o)||fe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Re(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Xi(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!fe(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 me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(fe(e)||fe(this.downloadingRepresentationId)||fe(this.playingRepresentationId)||fe(this.sourceBuffer)||!re(this.mediaSource,this.sourceBuffer)||Xi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Re(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Xi(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&El(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,pn.default)(u,r))c="high";else{let d=(0,Ji.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Ji.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Xi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,hn.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,hn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!ye(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,Ji.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Re(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!ye(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=ft(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Zr&&Zr(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Zr&&Zr(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let b=h<=i&&p>=i,g=h>i||b||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+v||p<=i+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&re(this.mediaSource,this.sourceBuffer)&&!(Bt(this.sourceBuffer.buffered,h)&&Bt(this.sourceBuffer.buffered,p)))&&g&&S});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=r;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){ye(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Nt(o,async function*(){let c=ql(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:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=dn(),!c)return;let d=new DataView(c),h=Pa(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),wa(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ye(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="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:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Nt(n,async function*(){let u=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Fl(window,"online").pipe(pC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=dn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),wa(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ye(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ji.default)(e,0).byte.from,to:(0,Ji.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=dn(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ye(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=dn();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:bt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,pn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!re(this.mediaSource,this.sourceBuffer))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){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Pa(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:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!re(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,h=d-c+1,p=c<r,m=d<=r;if(!p)continue;let b=Pa(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,h);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(h,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===h?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===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(fe(this.sourceBuffer)||!re(this.mediaSource,this.sourceBuffer))){!this.isLive&&N.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Bt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Bt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:bt.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",Ol(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tl(()=>(0,vy.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Nt(this.destroyAbortController.signal,async function*(){let o=ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Pa(e.mime),r)).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 h=c;this.isLive&&ye(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:bt.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,i=!1){if(!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||fe(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Ol(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,pn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!re(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||!re(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||fe(e)?0:Wi(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!re(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tl(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:bt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(fe(this.sourceBuffer)||!re(this.mediaSource,this.sourceBuffer)||fe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:bt.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 Sy=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as Ra,assertNever as Ty,fromEvent as Iy,merge as fC,now as $a,Subscription as bC,Subject as Ey,ValueSubject as Ul,flattenObject as Zi,ErrorCategory as La}from"@vkontakte/videoplayer-shared/es2018";var yy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var fn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Ul(void 0);this.lastConnectionReused$=new Ul(void 0);this.lastRequestFirstBytes$=new Ul(void 0);this.recoverableError$=new Ey;this.error$=new Ey;this.abortAllController=new me;this.subscription=new bC;this.fetchManifest=Ra(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ka(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=yy(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(mn);return r?(t.log("success",Zi({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Zi({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ra(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var U,L;let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let k=new URL(l,location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),l=k.toString();break}default:Ty(t)}this.requestQuic&&(l=ka(l));let h=this.abortAllController.signal,p;if(n){let k=new me;if(p=fC(Iy(this.abortAllController.signal,"abort"),Iy(n,"abort")).subscribe(()=>{try{k.abort()}catch(W){mn(W)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(W){mn(W)}h=k.signal}let m=$a();d.log("startRequest",Zi({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:h}),g=$a();if(!b)return d.error("error",{message:"No response in request"}),d.end(),p==null||p.unsubscribe(),null;if((U=this.throughputEstimator)==null||U.addRawRtt(g-m),!b.ok||!b.body){p==null||p.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),!r&&!o){p==null||p.unsubscribe();let k=$a(),W={requestStartedAt:m,requestEndedAt:k,duration:k-m};return d.log("endRequest",Zi(W)),d.end(),b.arrayBuffer()}let[v,S]=b.body.tee(),y=v.getReader();o&&((L=this.throughputEstimator)==null||L.trackStream(S,u));let I=0,T=new Uint8Array(0),R=!1,q=k=>{p==null||p.unsubscribe(),R=!0,mn(k)},O=Ra(h,async function*({done:k,value:W}){if(I===0&&this.lastRequestFirstBytes$.next($a()-m),h.aborted){p==null||p.unsubscribe();return}if(!k&&W){let ae=new Uint8Array(T.length+W.length);ae.set(T),ae.set(W,T.length),T=ae,I+=W.byteLength,r==null||r(new DataView(T.buffer),I),yield y==null?void 0:y.read().then(O,q)}}.bind(this));yield y==null?void 0:y.read().then(O,q),p==null||p.unsubscribe();let _=$a(),w={failed:R,requestStartedAt:m,requestEndedAt:_,duration:_-m};return R?(d.error("endRequest",Zi(w)),d.end(),null):(d.log("endRequest",Zi(w)),d.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ra(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(v=e.indexRange)!=null?v:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,p,m);return{init:p,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ra(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Sy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:Ty(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await at(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:La.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:La.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:La.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:La.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:La.FATAL})}}},mn=a=>{if(!wa(a))throw a};var pi=(a,e,t)=>t*e+(1-t)*a,Hl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,xy=(a,e,t,i)=>{let r=0,s=t,n=Hl(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as gC,ValueSubject as Py}from"@vkontakte/videoplayer-shared/es2018";var Ft=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Py(e.initial),this.debounced$=new Py(e.initial);let t=(i=e.label)!=null?i:"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,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(gC(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var bn=class extends Ft{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=pi(this.slow,e,this.params.emaAlphaSlow),this.fast=pi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var gn=class extends Ft{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Hl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pi(this.emaSmoothed,e,this.params.emaAlpha);let i=xy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var vn=class extends Ft{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?pi(this.smoothed,t,this.params.emaAlpha):t}};var hi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new bn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new gn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new vn({initial:e,label:"liveEdgeDelay",...t})}};var jl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as vC,ValueSubject as SC}from"@vkontakte/videoplayer-shared/es2018";var Ma=class a{constructor(e,t){this.currentRepresentation$=new SC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!vC(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ye(t.segmentReference))}};var yn=C(Dt(),1);import{assertNever as Tn}from"@vkontakte/videoplayer-shared/es2018";var wy=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=N.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(r.mp4||r.webm);default:return Tn(c)}})},Sn=a=>{let{webmDecodingInfo:e}=N.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Tn(a)}return[t,i]},Ay=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Sn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(N.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...Sn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Sn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Sn(a),...r,"HLS","HLS_ONDEMAND"];default:Tn(e)}return N.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},ky=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=N.device.isMac&&N.browser.isSafari;if(N.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Tn(a)}else N.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Ql=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ry=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,yn.default)(t.value.split("."),0)}for(let t of a){let i=(0,yn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,yn.default)(e.value.split("."),0)};var kC=["timeupdate","progress","play","seeked","stalled","waiting"],RC=["timeupdate","progress","loadeddata","playing","seeked"];var xn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new My;this.representationSubscription=new My;this.state$=new D("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new En;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.bufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new En;this.fetcherError$=new En;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new En;this.gapWatchdogActive=!1;this.destroyController=new me;this.initManifest=Wl(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=he(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:st.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Wl(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=fy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oS(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 i=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=Ye())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>i(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Ry(d);if(h&&(r[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=r.video.some(g=>g.hdr),b=r.video.some(g=>!g.hdr);N.display.isHDR&&p&&m?r.video=r.video.filter(g=>g.hdr):b&&(r.video=r.video.filter(g=>!g.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",Da(s)),s}.bind(this));this.initRepresentations=Wl(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",Da({initialVideo:e,initialAudio:t,sourceHls:i})),er(this.manifest),er(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(gt(p,"error").pipe(In(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:st.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?kg():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ks())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new Aa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Va(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new Aa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ma.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ma(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(mi(...RC.map(p=>gt(this.element,p))).pipe(ir(p=>this.element?Wi(this.element.buffered,this.element.currentTime*1e3):0),Ca(),wC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(mi(gt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Ca()).subscribe(m=>this.liveStreamEndTimestamp=zl())),this.subscription.add(gt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Yl(1e3).subscribe(m=>{let b=js(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(gt(this.element,"play").subscribe(m=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add(tr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ir(({isActiveLive:m,isLowLatency:b})=>m&&b),Ca()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||jl(this.element,1)})),this.representationSubscription.add(tr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(In(({bufferLength:m,isActiveLive:b,isLowLatency:g})=>b&&g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(m=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!m)return;let b=this.liveSeekableDuration$.getValue()-m/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+m/1e3)})),this.representationSubscription.add(tr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(In(({isLive:m})=>m),Ca((m,b)=>b.bufferLength<m.bufferLength),ir(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=js(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(tr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:m,isActiveLive:b,isLowLatency:g})=>{if(!g||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=m-v;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>S&&(T=1+Math.sign(I)*y),jl(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let b=0;if(m){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var T,R;return(R=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?R:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(tr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(AC(1e3)).subscribe(async({liveLoadBufferLength:m,bufferLength:b})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=js(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,R=isFinite(m)?m:b,q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let _="none";if(q?_="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),_="active_low_latency"):v!==0&&R<y?_="live_forward_buffering":R<y+T&&(_="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),_==="live_forward_buffering"||_==="live_with_target_offset"){let w=p-(y+I),U=this.normolizeLiveOffset(Math.trunc(v+w/g)),L=Math.abs(U-v),k=0;!m||L<=this.tuning.dashCmafLive.offsetCalculationError?k=v:U>0&&L>this.tuning.dashCmafLive.offsetCalculationError&&(k=U),this.manifestUrlString=he(this.manifestUrlString,k,2)}(_==="live_with_target_offset"||_==="live_forward_buffering")&&(p=0,await this.updateLive())},m=>{this.error$.next({id:"updateLive",category:st.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=mi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ir(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=mi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ir(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=tr({allBuffersFull:l,someBufferEnded:c}).pipe(Ca(),ir(({allBuffersFull:p,someBufferEnded:m})=>p&&m),In(p=>p));if(this.representationSubscription.add(mi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:st.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add(mi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((m,b)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){m();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):m()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),m()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,Kl.default)((0,Kl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let b=[];return m.duration&&b.push(m.duration),ye(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&b.push(m.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Va(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,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Yl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:st.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new fn({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=hi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;er(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?zl()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=he(this.manifestUrlString,i,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((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){er(this.element),this.state$.setState("running"),this.subscription.add(mi(...kC.map(e=>gt(this.element,e)),gt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:st.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(gt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(gt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Bt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,b,g,v,S,y,I,T,R,q;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=zl(),n=100,o=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(y=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?y:0,c=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let O=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(O).catch(_=>{this.error$.next({id:"stallIntervalCallback",category:st.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:_})}),r.liveLastOffset=O}else{let O=this.element.currentTime*1e3;(R=this.videoBufferManager)==null||R.maintain(O),(q=this.audioBufferManager)==null||q.maintain(O),r.position=O}this.tracer.log("stallIntervalCallback",Da(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Yl(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:st.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;er(this.element),er(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Bt(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(Ly(this.element)||Ly(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Da({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Va(this.element)&&Va(this.source)&&Va(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=PC(this.tracer.error.bind(this.tracer));this.subscription.add(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(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={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 r=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<=r&&u.to+n>r&&(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,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Da(i)))}}};var Pn=class{constructor(e,t){this.fov=e,this.orientation=t}};var wn=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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Cy=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var bp=N(_t(),1);import{videoSizeToQuality as WD}from"@vkontakte/videoplayer-shared/es2018";var xI=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Qt(a):void 0)!=null?u:WD({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},EI=({id:s,bitrate:e})=>({id:s,bitrate:e}),wI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),PI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),gp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,bp.default)(i.split("."),0),isDefault:r}),Sp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,bp.default)(r.split("."),0)}),vp=s=>"url"in s,it=s=>s.type==="template",vn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var kI=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},gi=(s,e)=>{let t=s;t=(0,yp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,RI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,yp.default)(t,n,(o,u)=>AI(a)?o:AI(u)?a:(0,LI.default)(a,parseInt(u,10),"0"))}return t},$I=(s,e)=>{var k,P,O,$,M,Q,U,w,F,A,x,B,oe,Ve,se,K,ye,Te,Ie,Oe,Et,At,qt,Jt,ki,vs,ys,Ts,Is,xs,Es,ws,Ps,As,ks,Rs,Ls,Ms,$s,Bs,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Gs,zs,Qs,Ws,Ys,Ks,Xs,Js,Zs,ea;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(ce=>{var _,We;return(We=(_=ce.textContent)==null?void 0:_.trim())!=null?We:""}),o=(k=(0,MI.default)(n,0))!=null?k:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,y=a.getAttribute("mediaPresentationDuration"),v=[...a.getElementsByTagName("Period")],I=v.reduce((ce,_)=>({...ce,[_.id]:_.children}),{}),T=v.reduce((ce,_)=>({...ce,[_.id]:_.getAttribute("duration")}),{});y?S=kI(y):(0,Tp.default)(T).filter(ce=>ce).length&&!u?S=(0,Tp.default)(T).reduce((ce,_)=>{var We;return ce+((We=kI(_))!=null?We:0)},0):m&&(S=parseInt(m,10));let E=0,V=(O=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?O:[];for(let ce of v.map(_=>_.id))for(let _ of I[ce]){let We=($=_.getAttribute("id"))!=null?$:"id"+(E++).toString(10),kt=(M=_.getAttribute("mimeType"))!=null?M:"",zi=(Q=_.getAttribute("codecs"))!=null?Q:"",Qi=(U=_.getAttribute("contentType"))!=null?U:kt==null?void 0:kt.split("/")[0],$l=(F=(w=_.getAttribute("profiles"))==null?void 0:w.split(","))!=null?F:[],ta=(x=II((A=_.getAttribute("lang"))!=null?A:""))!=null?x:{},Zt=(Ve=(oe=(B=_.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:oe.trim())!=null?Ve:void 0,Bl=_.querySelectorAll("Representation"),Dl=_.querySelector("SegmentTemplate"),Cl=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,dt=Qi,H={id:We,language:ta.language,isDefault:Cl==="main",label:Zt,codecs:zi,hdr:dt==="video"&&ts(zi),mime:kt,representations:[]};for(let C of Bl){let Pe=(ye=C.getAttribute("lang"))!=null?ye:void 0,Rt=(Ie=(Te=Zt!=null?Zt:_.getAttribute("label"))!=null?Te:C.getAttribute("label"))!=null?Ie:void 0,ei=(At=(Et=(Oe=C.querySelector("BaseURL"))==null?void 0:Oe.textContent)==null?void 0:Et.trim())!=null?At:"",Ye=new URL(ei||o,e).toString(),Ae=(qt=C.getAttribute("mimeType"))!=null?qt:kt,ti=(ki=(Jt=C.getAttribute("codecs"))!=null?Jt:zi)!=null?ki:"",ii;if(Qi==="text"){let ke=C.getAttribute("id")||"",ri=((vs=ta.privateuse)==null?void 0:vs.includes("x-auto"))||ke.includes("_auto"),Ke=C.querySelector("SegmentTemplate");if(Ke){let Lt={representationId:(ys=C.getAttribute("id"))!=null?ys:void 0,bandwidth:(Ts=C.getAttribute("bandwidth"))!=null?Ts:void 0},si=parseInt((Is=C.getAttribute("bandwidth"))!=null?Is:"",10)/1e3,ai=(Es=parseInt((xs=Ke.getAttribute("startNumber"))!=null?xs:"",10))!=null?Es:1,pt=parseInt((ws=Ke.getAttribute("timescale"))!=null?ws:"",10),Wi=(Ps=Ke.querySelectorAll("SegmentTimeline S"))!=null?Ps:[],ht=Ke.getAttribute("media");if(!ht)continue;let ni=[],oi=0,ui="",ft=0,Mt=ai,ee=0;for(let de of Wi){let Xe=parseInt((As=de.getAttribute("d"))!=null?As:"",10),ne=parseInt((ks=de.getAttribute("r"))!=null?ks:"",10)||0,Re=parseInt((Rs=de.getAttribute("t"))!=null?Rs:"",10);ee=Number.isFinite(Re)?Re:ee;let Je=Xe/pt*1e3,Le=ee/pt*1e3;for(let me=0;me<ne+1;me++){let Me=gi(ht,{...Lt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Xe).toString(10)}),mt=(Le!=null?Le:0)+me*Je,Bt=mt+Je;Mt++,ni.push({time:{from:mt,to:Bt},url:Me})}ee+=(ne+1)*Xe,oi+=(ne+1)*Je}ft=ee/pt*1e3,ui=gi(ht,{...Lt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let $t={time:{from:ft,to:1/0},url:ui},xe={type:"template",baseUrl:Ye,segmentTemplateUrl:ht,initUrl:"",totalSegmentsDurationMs:oi,segments:ni,nextSegmentBeyondManifest:$t,timescale:pt};ii={id:ke,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:si,mime:"",codecs:"",width:0,height:0,isAuto:ri}}else ii={id:ke,isAuto:ri,kind:"text",url:Ye}}else{let ke=(Ms=(Ls=C.getAttribute("contentType"))!=null?Ls:Ae==null?void 0:Ae.split("/")[0])!=null?Ms:Qi,ri=(Bs=($s=_.getAttribute("profiles"))==null?void 0:$s.split(","))!=null?Bs:[],Ke=parseInt((Ds=C.getAttribute("width"))!=null?Ds:"",10),Lt=parseInt((Cs=C.getAttribute("height"))!=null?Cs:"",10),si=parseInt((Vs=C.getAttribute("bandwidth"))!=null?Vs:"",10)/1e3,ai=(Os=C.getAttribute("frameRate"))!=null?Os:"",pt=(_s=C.getAttribute("quality"))!=null?_s:void 0,Wi=ai?Cu(ai):void 0,ht=(Fs=C.getAttribute("id"))!=null?Fs:"id"+(E++).toString(10),ni=ke==="video"?`${Lt}p`:ke==="audio"?`${si}Kbps`:ti,oi=`${ht}@${ni}`,ui=[...V,...$l,...ri],ft,Mt=C.querySelector("SegmentBase"),ee=(Ns=C.querySelector("SegmentTemplate"))!=null?Ns:Dl;if(Mt){let xe=(qs=(Us=C.querySelector("SegmentBase Initialization"))==null?void 0:Us.getAttribute("range"))!=null?qs:"",[de,Xe]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Xe},Re=(js=C.querySelector("SegmentBase"))==null?void 0:js.getAttribute("indexRange"),[Je,Le]=Re?Re.split("-").map(Me=>parseInt(Me,10)):[],me=Re?{from:Je,to:Le}:void 0;ft={type:"byteRange",url:Ye,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Hs=C.getAttribute("id"))!=null?Hs:void 0,bandwidth:(Gs=C.getAttribute("bandwidth"))!=null?Gs:void 0},de=parseInt((zs=ee.getAttribute("timescale"))!=null?zs:"",10),Xe=(Qs=ee.getAttribute("initialization"))!=null?Qs:"",ne=ee.getAttribute("media"),Re=(Ys=parseInt((Ws=ee.getAttribute("startNumber"))!=null?Ws:"",10))!=null?Ys:1,Je=gi(Xe,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Le=(Ks=ee.querySelectorAll("SegmentTimeline S"))!=null?Ks:[],me=[],Me=0,mt="",Bt=0;if(Le.length){let li=Re,pe=0;for(let bt of Le){let be=parseInt((Xs=bt.getAttribute("d"))!=null?Xs:"",10),Ze=parseInt((Js=bt.getAttribute("r"))!=null?Js:"",10)||0,ci=parseInt((Zs=bt.getAttribute("t"))!=null?Zs:"",10);pe=Number.isFinite(ci)?ci:pe;let Yi=be/de*1e3,Ki=pe/de*1e3;for(let di=0;di<Ze+1;di++){let Ol=gi(ne,{...xe,segmentNumber:li.toString(10),segmentTime:(pe+di*be).toString(10)}),ia=(Ki!=null?Ki:0)+di*Yi,_l=ia+Yi;li++,me.push({time:{from:ia,to:_l},url:Ol})}pe+=(Ze+1)*be,Me+=(Ze+1)*Yi}Bt=pe/de*1e3,mt=gi(ne,{...xe,segmentNumber:li.toString(10),segmentTime:pe.toString(10)})}else if(YD(S)){let pe=parseInt((ea=ee.getAttribute("duration"))!=null?ea:"",10)/de*1e3,bt=Math.ceil(S/pe),be=0;for(let Ze=1;Ze<bt;Ze++){let ci=gi(ne,{...xe,segmentNumber:Ze.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:ci}),be+=pe}Bt=be,mt=gi(ne,{...xe,segmentNumber:bt.toString(10),segmentTime:be.toString(10)})}let Vl={time:{from:Bt,to:1/0},url:mt};ft={type:"template",baseUrl:Ye,segmentTemplateUrl:ne,initUrl:Je,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:Vl,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!Ae)continue;let $t={video:"video",audio:"audio",text:"text"}[ke];if(!$t)continue;dt||(dt=$t),ii={id:oi,kind:$t,segmentReference:ft,profiles:ui,duration:S,bitrate:si,mime:Ae,codecs:ti,width:Ke,height:Lt,fps:Wi,quality:pt}}H.language||(H.language=Pe),H.label||(H.label=Rt),H.mime||(H.mime=Ae),H.codecs||(H.codecs=ti),H.hdr||(H.hdr=dt==="video"&&ts(ti)),H.representations.push(ii)}if(dt){let C=r[dt].find(Pe=>Pe.id===H.id);if(C&&H.representations.every(Pe=>it(Pe.segmentReference)))for(let Pe of C.representations){let Rt=H.representations.find(Ae=>Ae.id===Pe.id),ei=Rt==null?void 0:Rt.segmentReference,Ye=Pe.segmentReference;Ye.segments.push(...ei.segments),Ye.nextSegmentBeyondManifest=ei.nextSegmentBeyondManifest}else r[dt].push(H)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as BI}from"@vkontakte/videoplayer-shared/es2018";var G=(s,e)=>BI(s)&&BI(e)&&s.readyState==="open"&&KD(s,e);function KD(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var yn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new fr(0);this.currentLowLatencySegmentLength$=new fr(0);this.currentSegmentLength$=new fr(0);this.onLastSegment$=new fr(!1);this.fullyBuffered$=new fr(!1);this.playingRepresentation$=new fr(void 0);this.playingRepresentationInit$=new fr(void 0);this.error$=new JD;this.gaps=[];this.subscription=new ZD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ae;this.switchAbortController=new ae;this.destroyAbortController=new ae;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=_i(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);lt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new BT(this.sourceBuffer),this.subscription.add(xp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Si.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Si.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(xp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Si.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!G(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Jr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);lt(i,"No init buffer for starting representation"),lt(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=_i(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);lt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),lt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();is(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=_i(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);lt(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(ze(a)||ze(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),lt(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();is(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=_i(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,_u.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!it(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);lt(r);let a=this.segments.get(i);lt(a,"No segments for starting representation");let n=this.initData.get(i);if(lt(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(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,_i(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);lt(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(ze(o)||ze(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),lt(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();is(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!ze(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 ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ze(e)||ze(this.downloadingRepresentationId)||ze(this.playingRepresentationId)||ze(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||is(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(lt(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);is(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Jr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Ou.default)(u,r))d="high";else{let c=(0,rs.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,rs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;is(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,_u.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,_u.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!it(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,rs.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;lt(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!it(a))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*a.timescale/1e3).toString(10),d=gi(a.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Yt&&Yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yt&&Yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&y&&this.sourceBuffer&&G(this.mediaSource,this.sourceBuffer)&&!(Ge(this.sourceBuffer.buffered,h)&&Ge(this.sourceBuffer.buffered,p)))&&g&&y});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){it(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await _i(o,async function*(){let d=Ep(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Vu(),!d)return;let c=new DataView(d),h=Sn(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),vn(d)||(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())it(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="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:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await _i(n,async function*(){let u=Ep(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),xp(window,"online").pipe(XD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Vu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),vn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,rs.default)(e,0).byte.from,to:(0,rs.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Vu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Si.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=Vu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Si.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Ou.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Sn(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,f=c<=r;if(!p)continue;let m=Sn(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===h?g:m.parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(ze(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer))){!this.isLive&&q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ge(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ge(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Si.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",vp(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Xr(()=>(0,DI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?_i(this.destroyAbortController.signal,async function*(){let o=Ep(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Sn(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&it(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Si.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,i=!1){if(!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ze(e))return!1;let r=[],a=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:h}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,h):l.push(u[d])}return l},o=u=>{var d;if(a>=t)return r;r.push({...u.time}),r=n(r);let l=vp(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let h of this.segments.values())for(let p of h)(0,Ou.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let h={time:{from:l,to:d},url:"",status:"none"};o(h)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!G(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||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ze(e)?0:De(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Xr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Si.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ze(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||ze(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Si.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Fi=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Fu=s=>{var a;let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as Tn,assertNever as CI,fromEvent as VI,merge as eC,now as In,Subscription as tC,Subject as OI,ValueSubject as wp,flattenObject as ss,ErrorCategory as xn}from"@vkontakte/videoplayer-shared/es2018";var Nu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var qu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new wp(void 0);this.lastConnectionReused$=new wp(void 0);this.lastRequestFirstBytes$=new wp(void 0);this.recoverableError$=new OI;this.error$=new OI;this.abortAllController=new ae;this.subscription=new tC;this.fetchManifest=Tn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Fi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Nu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Uu);return r?(t.log("success",ss({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ss({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Tn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,$;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let M=new URL(l,location.href);M.searchParams.append("bytes",`${i.from}-${i.to}`),l=M.toString();break}default:CI(t)}this.requestQuic&&(l=Fi(l));let h=this.abortAllController.signal,p;if(n){let M=new ae;if(p=eC(VI(this.abortAllController.signal,"abort"),VI(n,"abort")).subscribe(()=>{try{M.abort()}catch(Q){Uu(Q)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{M.abort()}catch(Q){Uu(Q)}h=M.signal}let f=In();c.log("startRequest",ss({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let m=yield this.doFetch(l,{priority:a,headers:d,signal:h}),g=In();if(!m)return c.error("error",{message:"No response in request"}),c.end(),p==null||p.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!m.ok||!m.body){p==null||p.unsubscribe();let M=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:M}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){p==null||p.unsubscribe();let M=In(),Q={requestStartedAt:f,requestEndedAt:M,duration:M-f};return c.log("endRequest",ss(Q)),c.end(),m.arrayBuffer()}let[S,y]=m.body.tee(),v=S.getReader();o&&(($=this.throughputEstimator)==null||$.trackStream(y,u));let I=0,T=new Uint8Array(0),E=!1,V=M=>{p==null||p.unsubscribe(),E=!0,Uu(M)},L=Tn(h,async function*({done:M,value:Q}){if(I===0&&this.lastRequestFirstBytes$.next(In()-f),h.aborted){p==null||p.unsubscribe();return}if(!M&&Q){let U=new Uint8Array(T.length+Q.length);U.set(T),U.set(Q,T.length),T=U,I+=Q.byteLength,r==null||r(new DataView(T.buffer),I),yield v==null?void 0:v.read().then(L,V)}}.bind(this));yield v==null?void 0:v.read().then(L,V),p==null||p.unsubscribe();let k=In(),P={failed:E,requestStartedAt:f,requestEndedAt:k,duration:k-f};return E?(c.error("endRequest",ss(P)),c.end(),null):(c.log("endRequest",ss(P)),c.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=Tn(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let y=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!y)return null;m=new DataView(y)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=Tn(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Fu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:CI(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Pt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:xn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:xn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:xn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:xn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:xn.FATAL})}}},Uu=s=>{if(!vn(s))throw s};var vi=(s,e,t)=>t*e+(1-t)*s,Pp=(s,e)=>s.reduce((t,i)=>t+i,0)/e,_I=(s,e,t,i)=>{let r=0,a=t,n=Pp(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};import{isNullable as iC,ValueSubject as FI}from"@vkontakte/videoplayer-shared/es2018";var Ni=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new FI(e.initial),this.debounced$=new FI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new et(`raw_${t}`),this.smoothedSeries$=new et(`smoothed_${t}`),this.reportedSeries$=new et(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(iC(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 ju=class extends Ni{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vi(this.slow,e,this.params.emaAlphaSlow),this.fast=vi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Hu=class extends Ni{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Pp(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vi(this.emaSmoothed,e,this.params.emaAlpha);let i=_I(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Gu=class extends Ni{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?vi(this.smoothed,t,this.params.emaAlpha):t}};var yi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new ju({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Hu({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Gu({initial:e,label:"liveEdgeDelay",...t})}};var as=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as rC,ValueSubject as sC}from"@vkontakte/videoplayer-shared/es2018";var En=class s{constructor(e,t){this.currentRepresentation$=new sC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!rC(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.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({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&it(t.segmentReference))}};var Qu=N(_t(),1);import{assertNever as Wu}from"@vkontakte/videoplayer-shared/es2018";var NI=(s,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:a,codecs:n,nativeHlsSupported:o}=q.video,u=(n.h264||n.h265)&&n.aac,l=a.mse&&(!i||!!window.MediaStreamTrack)||a.mms&&t;return s.filter(d=>{switch(d){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return a.webrtc&&a.ws&&n.h264&&(r.mp4||r.webm);default:return Wu(d)}})},zu=s=>{let{webmDecodingInfo:e}=q.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Wu(s)}return[t,i]},UI=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...zu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(q.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...zu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...zu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...zu(s),...r,"HLS","HLS_ONDEMAND"];default:Wu(e)}return q.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},qI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=q.device.isMac&&q.browser.isSafari;if(q.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:Wu(s)}else q.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=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Ap=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Yu=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Qu.default)(t.value.split("."),0)}for(let t of s){let i=(0,Qu.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Qu.default)(e.value.split("."),0)};var pC=["timeupdate","progress","play","seeked","stalled","waiting"],hC=["timeupdate","progress","loadeddata","playing","seeked"];var Ju=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new GI;this.representationSubscription=new GI;this.state$=new j("none");this.currentVideoRepresentation$=new he(void 0);this.currentVideoRepresentationInit$=new he(void 0);this.currentAudioRepresentation$=new he(void 0);this.currentVideoSegmentLength$=new he(0);this.currentAudioSegmentLength$=new he(0);this.error$=new Xu;this.lastConnectionType$=new he(void 0);this.lastConnectionReused$=new he(void 0);this.lastRequestFirstBytes$=new he(void 0);this.currentLiveTextRepresentation$=new he(null);this.isLive$=new he(!1);this.isActiveLive$=new he(!1);this.isLowLatency$=new he(!1);this.liveDuration$=new he(0);this.liveSeekableDuration$=new he(0);this.liveAvailabilityStartTime$=new he(0);this.liveStreamStatus$=new he(void 0);this.bufferLength$=new he(0);this.liveLatency$=new he(void 0);this.liveLoadBufferLength$=new he(0);this.livePositionFromPlayer$=new he(0);this.currentStallDuration$=new he(0);this.videoLastDataObtainedTimestamp$=new he(0);this.fetcherRecoverableError$=new Xu;this.fetcherError$=new Xu;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Xu;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=Rp(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Kt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Rp(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:Kt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=$I(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Du(e))!=null?n:{id:"ManifestParsing",category:Kt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=It())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=Yu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);q.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",Pn(a)),a}.bind(this));this.initRepresentations=Rp(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",Pn({initialVideo:e,initialAudio:t,sourceHls:i})),ns(this.manifest),ns(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ti(p,"error").pipe(Ku(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Kt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?du():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&jr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new yn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],An(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new yn("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}En.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new En(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(mr(...hC.map(p=>Ti(this.element,p))).pipe(us(p=>this.element?De(this.element.buffered,this.element.currentTime*1e3):0),wn(),cC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(mr(Ti(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(wn()).subscribe(f=>this.liveStreamEndTimestamp=Mp())),this.subscription.add(Ti(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Lp(1e3).subscribe(f=>{let m=$i(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ti(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(os({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(us(({isActiveLive:f,isLowLatency:m})=>f&&m),wn()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||as(this.element,1)})),this.representationSubscription.add(os({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ku(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(os({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ku(({isLive:f})=>f),wn((f,m)=>m.bufferLength<f.bufferLength),us(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=$i(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(os({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=f-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>y&&(T=1+Math.sign(I)*v),as(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let y=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,E;return(E=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?E:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(os({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(dC(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=$i(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(f)?f:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let k="none";if(V?k="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),k="active_low_latency"):S!==0&&E<v?k="live_forward_buffering":E<v+T&&(k="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),k==="live_forward_buffering"||k==="live_with_target_offset"){let P=p-(v+I),O=this.normolizeLiveOffset(Math.trunc(S+P/g)),$=Math.abs(O-S),M=0;!f||$<=this.tuning.dashCmafLive.offsetCalculationError?M=S:O>0&&$>this.tuning.dashCmafLive.offsetCalculationError&&(M=O),this.manifestUrlString=Se(this.manifestUrlString,M,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Kt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=mr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(us(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=mr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(us(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=os({allBuffersFull:l,someBufferEnded:d}).pipe(wn(),us(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Ku(p=>p));if(this.representationSubscription.add(mr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Kt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(mr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((f,m)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){f();return}this.tuning.dash.rejectOnSourceOpenTimeout?m(new Error("Timeout reject when wait sourceopen event")):f()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,$p.default)((0,$p.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),it(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&An(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,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Lp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Kt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new qu({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=yi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;ns(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Mp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Se(this.manifestUrlString,i,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((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){ns(this.element),this.state$.setState("running"),this.subscription.add(mr(...pC.map(e=>Ti(this.element,e)),Ti(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Kt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ti(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ti(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ge(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,y,v,I,T,E,V;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Mp(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(v=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?v:0,d=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(k=>{this.error$.next({id:"stallIntervalCallback",category:Kt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:k})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(L),(V=this.audioBufferManager)==null||V.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",Pn(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Lp(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Kt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;ns(this.element),ns(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ge(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(HI(this.element)||HI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Pn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;An(this.element)&&An(this.source)&&An(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=lC(this.tracer.error.bind(this.tracer));this.subscription.add(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(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={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 r=this.element.currentTime*1e3,a=[],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<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?a.push(1/0):a.push(u.to));if(a.length){let o=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:a,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Pn(i)))}}};var Zu=class{constructor(e,t){this.fov=e,this.orientation=t}};var el=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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var QI=`attribute vec2 a_vertex;
|
|
71
125
|
attribute vec2 a_texel;
|
|
72
126
|
|
|
73
127
|
varying vec2 v_texel;
|
|
@@ -78,7 +132,7 @@ void main(void) {
|
|
|
78
132
|
// save texel vector to pass to fragment shader
|
|
79
133
|
v_texel = a_texel;
|
|
80
134
|
}
|
|
81
|
-
`;var
|
|
135
|
+
`;var WI=`#ifdef GL_ES
|
|
82
136
|
precision highp float;
|
|
83
137
|
precision highp int;
|
|
84
138
|
#else
|
|
@@ -121,6 +175,13 @@ void main(void) {
|
|
|
121
175
|
// sample using new coordinates
|
|
122
176
|
gl_FragColor = texture2D(u_texture, tc);
|
|
123
177
|
}
|
|
124
|
-
`;var An=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Pn(this.params.fov,this.params.orientation),this.cameraRotationManager=new wn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Cy,this.gl.VERTEX_SHADER),i=this.createShader(Dy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,h=t+r;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as MC,now as Vy,Subscription as CC,filter as DC,combine as Oy,debounce as VC,ValueSubject as Xl,isNonNullable as OC}from"@vkontakte/videoplayer-shared/es2018";var Jl=class{constructor(){this.isSeeked$=new Xl(!1);this.isBuffering$=new Xl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new CC;this.severeStallOccurred$=new Xl(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(Oy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(VC(this.qualityLimitsOnStall.stallDurationToBeCount),DC(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Oy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(MC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Vy(),d=r&&this.currentStallsCount>=r,h=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,OC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Vy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},By=Jl;import{combine as BC,map as _C,observeElementSize as NC,Subscription as FC,ValueSubject as Zl,noop as qC}from"@vkontakte/videoplayer-shared/es2018";var kn=class{constructor(){this.subscription=new FC;this.pipSize$=new Zl(void 0);this.videoSize$=new Zl(void 0);this.elementSize$=new Zl(void 0);this.pictureInPictureWindowRemoveEventListener=qC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(NC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(BC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(_C(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var fi=class{constructor(e){this.subscription=new WC;this.videoState=new D("stopped");this.droppedFramesManager=new on;this.stallsManager=new By;this.elementSizeManager=new kn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ur;this.audioTrackSwitchHistory=new Ur;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return HC(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new An(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ne(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new xn({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,i=Ae(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:_y.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ec(l=>!!l.length),Fy()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(tc(l=>l.to.state!=="none"),Oa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Oa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$,looped$:i.looped$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ec(Ny),Fy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(tc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(it(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Fe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(jC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of c.audio){h.push(Dl(p));let m=[];for(let b of p.representations){let g=oy(b);m.push(g),this.audioTracksMap.set(g,{stream:p,representation:b})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(Vl(h));let p=[];for(let m of h.representations){let b=ny({...m,streamId:h.id});b&&(p.push(b),this.videoTracksMap.set(b,{stream:h,representation:m}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let p of h.representations){let m=uy(h,p);this.textTracksMap.set(m,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(Rn(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,GC(this.video,"progress")).pipe(ec(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,qy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[h,p]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===h.id});Ny(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(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Oa()).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:h}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Vl(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Oa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Dl(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(tc(({to:l})=>l==="ready"),Oa());this.subscription.add(Rn(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ic(["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(Rn(o,this.player.state$.stateChangeEnded$,ic(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Rn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ic(["init"])).pipe(QC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var q,O,_,w,U,L,k,W,ae,A,B,Y,E;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(q=e.videoTrack.getState())==null?void 0:q.id,n=[...this.videoTracksMap.keys()].find(({id:$})=>$===r),o=t.currentVideoTrack$.getValue(),u=((w=(_=e.videoStream.getState())!=null?_:n&&((O=this.videoTracksMap.get(n))==null?void 0:O.stream))!=null?w:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:$})=>$===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Wi(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let p=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(h,p||1/0),1),b=(U=e.audioStream.getState())!=null?U:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(L=[...this.audioStreamsMap.keys()].find(({id:$})=>$===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!i){let $=rn(n,c,(k=this.audioStreamsMap.get(g))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(W=$==null?void 0:$.bitrate)!=null?W:-1/0)}if(o){let $=rn(o,c,(ae=this.audioStreamsMap.get(g))!=null?ae:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(A=$==null?void 0:$.bitrate)!=null?A:-1/0)}}let S=Ot(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=i?S!=null?S:n:n!=null?n:S,I=g&&iv(y,c,(B=this.audioStreamsMap.get(g))!=null?B:[],{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}),T=(Y=this.videoTracksMap.get(y))==null?void 0:Y.representation,R=I&&((E=this.audioTracksMap.get(I))==null?void 0:E.representation);if(T&&R)return[T,R];if(T&&!R&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_y.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),xe(this.video),this.tracer.end()}};var Ba=class extends fi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as rc,merge as Uy,filter as Hy,filterChanged as YC,isNullable as ac,map as jy,ValueSubject as sc,isNonNullable as zC}from"@vkontakte/videoplayer-shared/es2018";var _a=class extends fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new sc(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(jy(o=>o.to)).subscribe(this.player.isLowLatency$)).add(rc({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jy(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Hy(o=>zC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(rc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Uy(i.playbackRateState$,new sc(1))}).pipe(Hy(({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||ac(l)||(e=o-l)})).add(rc({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Uy(i.playbackRateState$,new sc(1))}).pipe(YC((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||ac(o)||ac(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=ly(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Gy=C(Hs(),1);import{assertNever as Na,assertNonNullable as Qy,debounce as KC,ErrorCategory as $n,filter as XC,isNonNullable as JC,isNullable as ZC,map as Ln,merge as eD,Observable as tD,observableFrom as iD,Subscription as rD,videoSizeToQuality as aD}from"@vkontakte/videoplayer-shared/es2018";var Ke={};var rr=(a,e)=>new tD(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Fa=class{constructor(e){this.subscription=new rD;this.videoState=new D("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Na(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Na(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Na(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Na(e)}break;default:Na(t)}};this.textTracksManager=new Ne(e.source.url),this.video=Ee(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:$n.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Gy.default)(import("hls.js").then(r=>{e||(Ke.Hls=r.default,Ke.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){Qy(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(){Qy(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:$n.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(it(this.video,e.isLooped,i)),this.subscription.add(Pe(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(_e(this.video,e.playbackRate,r.playbackRateState$,i)),s(Fe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Ln(l=>l.to)),this.params.output.playbackState$),this.subscription.add(rr(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:$n.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(rr(this.hls,Ke.Events.MANIFEST_PARSED).pipe(Ln(({levels:l})=>l.reduce((c,d)=>{var S,y;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(y=Ct((S=d.attrs.QUALITY)!=null?S:""))!=null?y:aD({width:p,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(rr(this.hls,Ke.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(rr(this.hls,Ke.Events.LEVEL_LOADING).pipe(Ln(({url:l})=>oe(l))),t.hostname$),s(rr(this.hls,Ke.Events.FRAG_CHANGED),l=>{var h,p,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add($t(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=rr(this.hls,Ke.Events.LEVEL_SWITCHED).pipe(Ln(({level:l})=>n(this.hls.levels[l])));o.pipe(XC(JC)).subscribe(t.currentVideoTrack$,i),this.subscription.add($t(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(ZC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=eD(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,iD(["init"])).pipe(KC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$n.DOM,thrown:t}))||(this.videoState.setState("paused"),P(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"),P(this.params.desiredState.playbackState,"stopped",!0)}};var Wy="X-Playback-Duration",nc=async a=>{var r;let e=await at(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Wy)?parseInt(e.headers.get(Wy),10):void 0};import{assertNever as fD,combine as bD,debounce as gD,ErrorCategory as Dn,filter as vD,filterChanged as SD,isNonNullable as Ky,isNullable as Vn,map as Xy,merge as yD,observableFrom as TD,Subscription as ID,ValueSubject as lc,VideoQuality as ED}from"@vkontakte/videoplayer-shared/es2018";var uc=C(au(),1);import{videoSizeToQuality as sD,getExponentialDelay as nD}from"@vkontakte/videoplayer-shared/es2018";var oD=a=>{let e=null;if(a.QUALITY&&(e=Ct(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=sD({width:t,height:i})}return e!=null?e:null},uD=(a,e)=>{var s,n;let t=a.split(`
|
|
125
|
-
|
|
126
|
-
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(cD(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;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:mD.WTF,thrown:t,message:e})}};var qa=class{constructor(e){this.subscription=new ID;this.videoState=new D("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new lc([]);this.liveOffset=new ui;this.manifestStartTime$=new lc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return fD(t)}};var i;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ED.INVARIANT,url:this.params.source.url};let t=(r,s)=>Mn(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Cn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ne(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Dn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Dn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new lc((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Dn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),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(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(SD(),Xy(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Ky(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(oe(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(bD({startTime:this.manifestStartTime$.pipe(vD(Ky)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(Xy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=yD(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,TD(["init"])).pipe(gD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Vn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=he(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),nc(n).then(c=>{var d;if(!Vn(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Vn(h)||!isFinite(h))&&at(n).then(p=>p.text()).then(p=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();nc(g).then(v=>{Vn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Dn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=he(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as xD,debounce as PD,ErrorCategory as cc,fromEvent as dc,isNonNullable as wD,isNullable as AD,map as Jy,merge as Zy,observableFrom as eT,Subscription as kD,ValueSubject as RD,VideoQuality as $D}from"@vkontakte/videoplayer-shared/es2018";var Ua=class{constructor(e){this.subscription=new kD;this.videoState=new D("stopped");this.manifests$=new RD([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return xD(t)}};this.textTracksManager=new Ne(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:$D.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Mn(he(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:cc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:cc.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Jy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(it(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&wD(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(oe(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(Jy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!N.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Zy(dc(o,"addtrack"),dc(o,"removetrack"),dc(o,"change"),eT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=Zy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,eT(["init"])).pipe(PD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(AD(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var rT=C(Ci(),1),pc=C(ji(),1),aT=C(Dt(),1);import{assertNever as LD,assertNonNullable as tT,debounce as MD,ErrorCategory as iT,isHigherOrEqual as CD,isLowerOrEqual as DD,isNonNullable as VD,merge as OD,observableFrom as BD,Subscription as _D,map as ND}from"@vkontakte/videoplayer-shared/es2018";var Ha=class{constructor(e){this.subscription=new _D;this.videoState=new D("stopped");this.trackUrls={};this.textTracksManager=new Ne;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return LD(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,rT.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,pc.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:iT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(ND(o=>o.to)),this.params.output.playbackState$),this.subscription.add(it(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),s(Fe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&VD(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=OD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,BD(["init"])).pipe(MD(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),xe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;tT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];tT(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(oe(t))}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:iT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let h=Ot(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,pc.default)(this.trackUrls).map(d=>d.track);if(!r||!s||qr({limits:e,lowestAvailableQuality:(c=(0,aT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?DD(r,e.max):!0,u=e.min?CD(r,e.min):!0;o&&u||i(e)}};import{assertNever as nT,debounce as HD,merge as oT,observableFrom as jD,Subscription as QD,map as uT,ValueSubject as GD,ErrorCategory as mc,VideoQuality as WD}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as FD}from"@vkontakte/videoplayer-shared/es2018";var sT=["stun:videostun.mycdn.me:80"],qD=1e3,UD=3,hc=()=>null,On=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=hc;this.externalStopCallback=hc;this.externalErrorCallback=hc;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}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:FD.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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),qD)}normalizeOptions(e={}){let t={stunServerList:sT,maxRetryNumber:UD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ja=class{constructor(e){this.videoState=new D("stopped");this.maxSeekBackTime$=new GD(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return nT(e)}};this.subscription=new QD,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new On(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:mc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(oT(this.videoState.stateChangeStarted$.pipe(uT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(uT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Ae(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Fe(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Pe(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return nT(n.to)}},i)).add(oT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,jD(["init"])).pipe(HD(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:WD.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:mc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ke(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Wa,assertNonNullable as qt,ErrorCategory as Bn,filter as mT,isNonNullable as fT,isNullable as e0,map as t0,merge as i0,once as r0,Subject as le,Subscription as bT,ValueSubject as V,flattenObject as gT}from"@vkontakte/videoplayer-shared/es2018";import{Observable as YD,map as lT,Subscription as zD,Subject as KD}from"@vkontakte/videoplayer-shared/es2018";var cT=a=>new YD(e=>{let t=new zD,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(lT(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(lT(({type:l})=>l!==void 0)),n=new KD,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as XD,Subscription as JD,combine as ZD,filter as pT,once as hT}from"@vkontakte/videoplayer-shared/es2018";function dT(){return new(window.AudioContext||window.webkitAudioContext)}var Ga=class Ga{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new me;this.subscriptions=new JD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(pT(s=>!!s.type),hT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){N.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(ZD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(pT(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),hT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=dT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ga.errorId,category:XD.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ga.errorId} exception`,thrown:e})}};Ga.errorId="VolumeMultiplierManager";var ar=Ga;var a0={chunkDuration:5e3,maxParallelRequests:5},Ya=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new le;this.noAvailableProvidersError$=new le;this.volumeMultiplierError$=new le;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 le,fetcherError$:new le,fetcherRecoverableError$:new le,warning$:new le,willSeekEvent$:new le,soundProhibitedEvent$:new le,seekedEvent$:new le,loopedEvent$:new le,endedEvent$:new le,firstBytesEvent$:new le,loadedMetadataEvent$:new le,firstFrameEvent$:new le,canplay$:new le,isLive$:new V(void 0),isLiveEnded$:new V(null),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 le,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 bT;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=wy([...ky(this.params.tuning),...Ay(this.params.tuning)],this.params.tuning).filter(l=>fT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,fc.default)(r,l)),...t.filter(l=>(0,fc.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",gT(s)),this.screenFormatsIterator=new Qa(s);let n=[...Ql(!0),...Ql(!1)];this.chromecastFormatsIterator=new Qa(n.filter(l=>fT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ar.isSupported()&&(this.volumeMultiplierManager=new ar(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(e0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Bn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.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,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Wa(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qt(u),new Ba({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qt(u),new _a({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return qt(u),N.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Ua({...o,source:u}):new Fa({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qt(u),new qa({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return qt(u),new Ha({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return qt(u),new Sv({...o,source:u,config:{...a0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return qt(u),new ja({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Wa(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return qt(o),new Vr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Wa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Wa(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 Wa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,ST.default)((0,vT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new bT,t=!1,i=0;return e.add(i0(this.providerOutput.error$.pipe(mT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),cT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(t0(r=>({id:`ProviderHangup:${r}`,category:Bn.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(mT(({to:s})=>s==="playing"),r0()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Bn.NETWORK,u=r.category===Bn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}this.tracer.error("providerError",gT(n))})),e}};import{fromEvent as _n,once as s0,combine as n0,Subscription as yT,ValueSubject as bc,map as o0,filter as u0,isNonNullable as Nn,now as Ve,safeStorage as gc}from"@vkontakte/videoplayer-shared/es2018";var l0=5e3,TT="one_video_throughput",IT="one_video_rtt",vt=window.navigator.connection,ET=()=>{let a=vt==null?void 0:vt.downlink;if(Nn(a)&&a!==10)return a*1e3},xT=()=>{let a=vt==null?void 0:vt.rtt;if(Nn(a)&&a!==3e3)return a},PT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},vc=class a{constructor(e){this.subscription=new yT;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(TT)||(e.useBrowserEstimation?ET():void 0)||l0,i=(s=(r=a.load(IT))!=null?r:e.useBrowserEstimation?xT():void 0)!=null?s:0;if(this.throughput$=new bc(t),this.rtt$=new bc(i),this.rttAdjustedThroughput$=new bc(PT(t,i,e.rttPenaltyRequestSize)),this.throughput=hi.getSmoothedValue(t,-1,e),this.rtt=hi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=ET();u&&this.throughput.next(u);let l=xT();Nn(l)&&this.rtt.next(l)};vt&&"onchange"in vt&&this.subscription.add(_n(vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{gc.set(TT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{gc.set(IT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(n0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(o0(({throughput:n,rtt:o})=>PT(n,o,e.rttPenaltyRequestSize)),u0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Ve(),r=new yT;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(_n(e,"progress").pipe(s0()).subscribe(s=>{t=s.loaded,i=Ve()}));break;case 1:case 0:r.add(_n(e,"loadstart").subscribe(()=>{t=0,i=Ve()}));break}r.add(_n(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ve(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Ve(),n=0,o=Ve(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,Ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Ve();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=Ve()}else n+=d.byteLength;o=Ve()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ve()-o,this.concurrentDownloads.size),n=0,o=Ve());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=gc.get(e);if(Nn(t))return(i=parseInt(t,10))!=null?i:void 0}},wT=vc;import{fillWithDefault as c0,VideoQuality as Fn}from"@vkontakte/videoplayer-shared/es2018";var AT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Fn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Fn.Q_720P,trafficSavingLimit:Fn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Fn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},kT=a=>{var e;return{...c0(a,AT),configName:[...(e=a.configName)!=null?e:[],...AT.configName]}};import{assertNonNullable as qn,combine as St,ErrorCategory as Un,filter as M,filterChanged as G,fromEvent as yc,isNonNullable as MT,isNullable as g0,Logger as v0,map as j,mapTo as CT,merge as Ut,now as Hn,once as F,Subject as z,Subscription as DT,tap as Tc,ValueSubject as x,isHigher as S0,isInvariantQuality as VT,flattenObject as Ht,throttle as Ic,getTraceSubscriptionMethod as OT,Tracer as y0,InternalsExposure as T0}from"@vkontakte/videoplayer-shared/es2018";import{merge as d0,map as p0,filter as RT,isNonNullable as h0}from"@vkontakte/videoplayer-shared/es2018";var Sc=({seekState:a,position$:e})=>d0(a.stateChangeEnded$.pipe(p0(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),RT(h0)),e.pipe(RT(()=>a.getState().state==="none")));import{assertNonNullable as m0}from"@vkontakte/videoplayer-shared/es2018";var $T=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return m0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as f0,once as b0}from"@vkontakte/videoplayer-shared/es2018";var LT=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(f0(r=>r.length>0),b0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var jn=class{constructor(e={configName:[]},t=y0.createRootTracer(!1)){this.subscription=new DT;this.logger=new v0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new x(!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 x(void 0),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableVideoStreams$:new x([]),currentVideoStream$:new x(void 0),availableQualities$:new x([]),availableQualitiesFps$:new x({}),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),predefinedQualityLimitType$:new x("unknown"),availableAudioStreams$:new x([]),currentAudioStream$:new x(void 0),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),isLiveEnded$:new x(null),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),liveLatency$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(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 x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:Hg,getCurrentTime$:new x(null)};if(this.initLogs(),this.tuning=kT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new fs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new wT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new T0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,m)=>{let b=typeof m;return(0,BT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Un.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",Ht(o)),this.domContainer=$T(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Ya({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),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)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?N.isInited$.pipe(M(n=>!!n),F()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),yc(document,"visibilitychange").pipe(F()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),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.subscription.add(this.playerInited.pipe(M(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(M(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(M(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(M(e=>!!e),F()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,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.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),s=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{qn(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(M(i=>i.length>0),F()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Ht(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var i;qn(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.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.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Ht(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{var t;LT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(M(t=>!!t),F()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(M(i=>!!i),F()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(M(e=>e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(M(e=>!!e),F()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(g0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return MT(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(j(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(il({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(M(({from:e})=>e==="stopped"),F()).subscribe(()=>{this.initedAt=Hn(),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",Ht(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Un.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(F()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Ht(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(j(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(j(n=>n.destination),G()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(St({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(j(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>VT(u)?1:VT(l)?-1:S0(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(G()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(M(n=>MT(n))).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(j(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(Tc(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(St({hasLiveOffsetByPaused:Ut(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(j(n=>n.to),G(),j(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(St({atLiveEdge:St({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(j(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),G(),Tc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(j(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(St({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(j(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),G(),Tc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(j(n=>n.muted),G()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(j(n=>n.volume),G()).subscribe(this.info.volume$)).add(Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ut(e.providerOutput.endedEvent$.pipe(CT(!0)),e.providerOutput.seekedEvent$.pipe(CT(!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(j(n=>({id:n?`No${n}`:"NoProviders",category:Un.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(F(),j(n=>n!=null?n:Hn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(F(),j(()=>Hn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(F(),j(()=>Hn()-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 x(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new x(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(M(({to:n})=>n==="playing"),F()).subscribe(()=>i.next(!1)));let r=0,s=Ut(e.providerOutput.isBuffering$,t,i).pipe(j(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),G());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Ut(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(Ut(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(j(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new DT;this.subscription.add(t),this.subscription.add(e.current$.pipe(G((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(M(i=>i.length>0),F()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=Ot(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,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(Ut(this.desiredState.videoTrack.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(j(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(j(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(j(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;qn(this.providerContainer),qn(e),Ug(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>qg(i)),this.providerContainer.current$.subscribe(({type:i})=>Fr("provider",i)),e.duration$.subscribe(i=>Fr("duration",i)),e.availableVideoTracks$.pipe(M(i=>!!i.length),F()).subscribe(i=>Fr("tracks",i)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(j(i=>i==null?void 0:i.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(i=>this.subscription.add(i)),Fr("codecs",N.video.supportedCodecs)}initTracerSubscription(){let e=OT(this.tracer.log.bind(this.tracer)),t=OT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(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(St({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(M(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),G((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(M(i=>i>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(M(i=>i>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(St({currentBuffer:this.info.currentBuffer$.pipe(M(i=>i.end>0),G((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(G())}).pipe(Ic(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(St({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(M(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Ic(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),M(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),M(i=>i===!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(),M(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(St({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(M(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Ic(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),M(i=>i===!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},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Un.DOM,message:String(r)})})};this.subscription.add(Ut(yc(document,"visibilitychange"),yc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Ht({quality:t,availableTracks:Ht(e),track:Ht(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Wr()}};import{Subscription as m6,Observable as f6,Subject as b6,ValueSubject as g6,VideoQuality as v6}from"@vkontakte/videoplayer-shared/es2018";var S6=`@vkontakte/videoplayer-core@${ud}`;export{us as ChromecastState,Kn as HttpConnectionType,f6 as Observable,$e as PlaybackState,jn as Player,ls as PredefinedQualityLimits,S6 as SDK_VERSION,b6 as Subject,m6 as Subscription,Xn as Surface,ud as VERSION,g6 as ValueSubject,lt as VideoFormat,v6 as VideoQuality,N as clientChecker,_r as isMobile};
|
|
178
|
+
`;var ls=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Zu(this.params.fov,this.params.orientation),this.cameraRotationManager=new el(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(QI,this.gl.VERTEX_SHADER),i=this.createShader(WI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,h=t+r;return[a,n,o,u,l,d,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as bC,now as kn,once as gC,Subscription as SC,ValueSubject as Bp,isNonNullable as vC,safeStorage as YI,filterChanged as yC}from"@vkontakte/videoplayer-shared/es2018";var tl="stalls_manager_metrics",KI="stalls_manager_abr_params",Dp=class{constructor(){this.isSeeked$=new Bp(!1);this.isBuffering$=new Bp(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new SC;this.severeStallOccurred$=new Bp(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){return{...this.abrParams,...this.getStoredData(KI)}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=kn(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(kn()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}updateStoredAbrParams(){let e=[],t=this.getStoredData(tl,"[]");if(t.length<this.tuning.stallsMetricsHistoryLength)return;if(this.tuning.useTotalStallsDurationPerTvt){let r=t.reduce((o,u)=>o+u.tvt,0),n=t.reduce((o,u)=>o+u.stallsDuration,0)/r;e.push(this.calculateOptimalAbrParams(n))}if(this.tuning.useAverageStallsDurationPerTvt){let r=t.reduce((a,n)=>a+n.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(r))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed));let i={bitrateFactorAtEmptyBuffer:Math.max(...e.map(r=>r.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(r=>r.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(r=>r.containerSizeFactor))};this.setStoredData(tl,[]),this.setStoredData(KI,i)}calculateOptimalAbrParams(e){let{targetStallsDurationPerTvt:t,deviationStallsDurationPerTvt:i,criticalStallsDurationPerTvt:r,abrAdjustingSpeed:a}=this.tuning,n=this.abrTuningParams;return e<t-i?n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer-a,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer-a,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor+a,this.abrParams.maxContainerSizeFactor)}:e>t+i&&(n={bitrateFactorAtEmptyBuffer:Math.min(n.bitrateFactorAtEmptyBuffer+a,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(n.bitrateFactorAtFullBuffer+a,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(n.containerSizeFactor-a,this.abrParams.minContainerSizeFactor)}),e>r&&(n={bitrateFactorAtEmptyBuffer:Math.max(n.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(n.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(n.containerSizeFactor,this.abrParams.containerSizeFactor)}),n}getStoredData(e,t="{}"){var i;return JSON.parse((i=YI.get(e))!=null?i:t)}setStoredData(e,t){YI.set(e,JSON.stringify(t))}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(tl,"[]"),r=t/e,a=i.length?vi(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(tl,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(gC()).subscribe(t=>this.providerStartWatchingTimestamp=kn())),this.subscription.add(this.currentStallDuration$.pipe(yC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(bC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=kn(),c=r&&this.currentStallsCount>=r,h=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,vC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&kn()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},il=Dp;import{combine as TC,map as IC,observeElementSize as xC,Subscription as EC,ValueSubject as Cp,noop as wC}from"@vkontakte/videoplayer-shared/es2018";var rl=class{constructor(){this.subscription=new EC;this.pipSize$=new Cp(void 0);this.videoSize$=new Cp(void 0);this.elementSize$=new Cp(void 0);this.pictureInPictureWindowRemoveEventListener=wC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(xC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(TC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(IC(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var br=class{constructor(e){this.subscription=new MC;this.videoState=new j("stopped");this.droppedFramesManager=new Yr;this.stallsManager=new il;this.elementSizeManager=new rl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Vi;this.audioTrackSwitchHistory=new Vi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return AC(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ls(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.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 nt(e.source.url),this.params=e,this.video=Ne(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(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 Ju({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,i=je(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:XI.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Vp(l=>!!l.length),ZI()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Op(l=>l.to.state!=="none"),sl());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Vp(JI),ZI()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Op(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(wt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(at(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(kC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(gp(p));let f=[];for(let m of p.representations){let g=EI(m);f.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,f)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(Sp(h));let p=[];for(let f of h.representations){let m=xI({...f,streamId:h.id});m&&(p.push(m),this.videoTracksMap.set(m,{stream:h,representation:f}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let p of h.representations){let f=wI(h,p);this.textTracksMap.set(f,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(al(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,LC(this.video,"progress")).pipe(Vp(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,ex.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[h,p]=c,f=[...this.videoTracksMap.keys()].find(g=>{var S;return((S=this.videoTracksMap.get(g))==null?void 0:S.representation.id)===h.id});JI(f)&&(this.stallsManager.lastVideoTrackSelected=f);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(sl()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Sp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(sl()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(gp(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(Op(({to:l})=>l==="ready"),sl());this.subscription.add(al(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,_p(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(al(o,this.player.state$.stateChangeEnded$,_p(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=al(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_p(["init"])).pipe(RC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,O,$,M,Q,U,w,F,A,x,B,oe,Ve;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Da:Ba,t=this.params.tuning.useNewAutoSelectVideoTrack?Au:Pu,i=this.params.tuning.useNewAutoSelectVideoTrack?Wt:wu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(P=r.videoTrack.getState())==null?void 0:P.id,l=[...this.videoTracksMap.keys()].find(({id:se})=>se===o),d=a.currentVideoTrack$.getValue(),c=((M=($=r.videoStream.getState())!=null?$:l&&((O=this.videoTracksMap.get(l))==null?void 0:O.stream))!=null?M:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let h=[...this.videoStreamsMap.keys()].find(({id:se})=>se===c.id),p=h&&this.videoStreamsMap.get(h);if(!p)return;let f=De(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(f/Math.min(m,g||1/0),1),y=(Q=r.audioStream.getState())!=null?Q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(U=[...this.audioStreamsMap.keys()].find(({id:se})=>se===(y==null?void 0:y.id)))!=null?U:this.audioStreamsMap.keys().next().value,I=0;if(v){if(l&&!n){let se=e(l,p,(w=this.audioStreamsMap.get(v))!=null?w:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(F=se==null?void 0:se.bitrate)!=null?F:-1/0)}if(d){let se=e(d,p,(A=this.audioStreamsMap.get(v))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(x=se==null?void 0:se.bitrate)!=null?x:-1/0)}}let T=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:d,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}),E=n?T!=null?T:l:l!=null?l:T,V=v&&t(E,p,(B=this.audioStreamsMap.get(v))!=null?B:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=(oe=this.videoTracksMap.get(E))==null?void 0:oe.representation,k=V&&((Ve=this.audioTracksMap.get(V))==null?void 0:Ve.representation);if(L&&k)return[L,k];if(L&&!k&&this.audioTracksMap.size===0)return[L,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:XI.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),Ue(this.video),this.tracer.end()}};var Rn=class extends br{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Fp,merge as tx,filter as ix,filterChanged as $C,isNullable as Np,map as rx,ValueSubject as Up,isNonNullable as BC}from"@vkontakte/videoplayer-shared/es2018";var Ln=class extends br{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new Up(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(rx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(Fp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(rx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(ix(o=>BC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(Fp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:tx(i.playbackRateState$,new Up(1))}).pipe(ix(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||Np(l)||(e=o-l)})).add(Fp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:tx(i.playbackRateState$,new Up(1))}).pipe($C((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||Np(o)||Np(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=PI(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as xV,assertNonNullable as EV,debounce as wV,ErrorCategory as Bx,filter as Dx,filterChanged as ml,fromEvent as PV,isNonNullable as Cx,map as lh,merge as bl,observableFrom as ch,once as Vx,Subscription as AV}from"@vkontakte/videoplayer-shared/es2018";var oh=N(ja(),1);import{abortable as rh,assertNonNullable as fs,combine as ms,ErrorCategory as Xt,filter as dl,filterChanged as lo,flattenObject as co,fromEvent as wi,getTraceSubscriptionMethod as pV,interval as sh,isNonNullable as po,isNullable as $x,map as bs,merge as Tr,now as ah,Subject as pl,Subscription as nh,tap as hV,throttle as fV,ValueSubject as fe}from"@vkontakte/videoplayer-shared/es2018";var ol=N(yt(),1),ps=N(_t(),1),ul=N(ja(),1);var Ax=N(Pa(),1);import{assertNever as DC,ErrorCategory as sx,Subject as ax}from"@vkontakte/videoplayer-shared/es2018";var CC=18,nx=!1;try{nx=q.browser.isSafari&&!!q.browser.safariVersion&&q.browser.safariVersion<=CC}catch(s){console.error(s)}var qp=class{constructor(e){this.bufferFull$=new ax;this.error$=new ax;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:sx.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(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};nx&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:sx.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:DC(t)}}},ox=qp;import{abortable as qi,assertNonNullable as ct,ErrorCategory as Ei,fromEvent as Zp,getExponentialDelay as eh,isNonNullable as ds,isNullable as Qe,now as nl,once as rV,Subject as sV,Subscription as aV,ValueSubject as yr}from"@vkontakte/videoplayer-shared/es2018";var J=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var cs=class extends J{};var Mn=class extends J{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,a=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,a)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var $n=class extends J{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var Bn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var le=class extends J{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Dn=class extends le{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Cn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Vn=class extends J{constructor(e,t){super(e,t),this.data=this.content}};var gr=class extends le{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var On=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _n=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Fn=class extends le{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Nn=class extends le{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Un=class extends le{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var qn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var jn=class extends le{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Hn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zn=class extends le{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Qn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wn=class extends le{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Yn=class extends le{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Kn=class extends le{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Xn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Jn=class extends le{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Zn=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var OC={ftyp:$n,moov:Bn,mvhd:Dn,moof:Cn,mdat:Vn,sidx:gr,trak:On,mdia:qn,mfhd:zn,tkhd:jn,traf:Qn,tfhd:Wn,tfdt:Yn,trun:Kn,minf:Hn,sv3d:_n,st3d:Fn,prhd:Nn,proj:Gn,equi:Un,uuid:Mn,stbl:Xn,stsd:Jn,avc1:Zn,unknown:cs},Ii=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=OC[e];return i?new i(t,new s):new cs(t,new s)}};var Ui=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var FC=new TextDecoder("ascii"),NC=s=>FC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",UC=s=>{let e=new gr(s,new Ii),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},qC=(s,e)=>{let i=new Ii().parse(s),r=new Ui(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},jC=s=>{let t=new Ii().parse(s),i=new Ui(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},HC=s=>{var r;let t=new Ii().parse(s);return(r=new Ui(t).find("sidx"))==null?void 0:r.timescale},GC=(s,e)=>{let i=new Ii().parse(s),a=new Ui(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,h)=>c+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},zC=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Ii().parse(s),r=new Ui(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ux={validateData:NC,parseInit:zC,getIndexRange:()=>{},parseSegments:UC,parseFeedableSegmentChunk:qC,getChunkEndTime:GC,getServerLatencyTimestamps:jC,getTimescaleFromIndex:HC};var to=N(yt(),1);import{assertNonNullable as Hp,isNonNullable as px,isNullable as WC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as QC}from"@vkontakte/videoplayer-shared/es2018";var lx={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"}},cx=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=eo(s,t),r=i in lx,a=r?lx[i].type:"binary",n=s.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(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,d=eo(u),c=l*2**((o-1)*8)+d,h=t+o,p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},eo=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Nt=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return eo(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:QC(e)}},Sr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=cx(i);if(!e(r))return;r.type==="master"&&Sr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},dx=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=cx(s);return Sr(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Nt(o,n):a===17026?t=Nt(o,n):a===17029&&(i=Nt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var hx=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],YC=[231,22612,22743,167,171,163,160,175],KC=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return Sr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Nt(f,p);l=eo(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+m):h===357149030?a=!0:h===290298740?n=!0:h===2807729?i=Nt(f,p):h===17545?r=Nt(f,p):h===21420&&l===475249515?u=Nt(f,p):h===374648427?Sr(f,({tag:g,type:S,value:y})=>g===30321?(d=Nt(y,S)===1,!1):!0):a&&n&&(0,to.default)(hx,h)&&(o=!0),!o}),Hp(e,"Failed to parse webm Segment start"),Hp(t,"Failed to parse webm Segment end"),Hp(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},XC=s=>{if(WC(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},JC=(s,e)=>{let t=!1,i=!1,r=o=>px(o.time)&&px(o.position),a=[],n;return Sr(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Nt(l,u));break;case 183:break;case 241:n&&(n.position=Nt(l,u));break;default:t&&(0,to.default)(hx,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:d}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},ZC=s=>{let e=0,t=!1;try{Sr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,to.default)(YC,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,to.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},fx={validateData:dx,parseInit:KC,getIndexRange:XC,parseSegments:JC,parseFeedableSegmentChunk:ZC};var io=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return fx;case"mp4":return ux}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Kp=N(hp(),1),xx=N(tr(),1),Ex=N(fp(),1),wx=N(_t(),1),Xp=N(lr(),1);import{isNonNullable as iV,isNullable as Tx}from"@vkontakte/videoplayer-shared/es2018";var mx=s=>{var e;try{let t=eV(),i=s.match(t),{groups:r}=i!=null?i:{};if(r){let a={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{a[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,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 eV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
179
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
180
|
+
(-(?<script>[a-z]{4}))?
|
|
181
|
+
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
182
|
+
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
183
|
+
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
184
|
+
(?:-(?<privateuse>(?:${e})))?
|
|
185
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var zp=N(_t(),1);import{videoSizeToQuality as tV}from"@vkontakte/videoplayer-shared/es2018";var bx=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{var u;let o=(u=a?Qt(a):void 0)!=null?u:tV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},gx=({id:s,bitrate:e})=>({id:s,bitrate:e}),Sx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),vx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Qp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,zp.default)(i.split("."),0),isDefault:r}),Wp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,zp.default)(r.split("."),0)}),Yp=s=>"url"in s,rt=s=>s.type==="template",ro=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var yx=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},vr=(s,e)=>{for(let t of s)if(e(t))return t;return null};var Ix=s=>{if(!(s!=null&&s.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},xi=(s,e)=>{let t=s;t=(0,Kp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,xx.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Kp.default)(t,n,(o,u)=>Tx(a)?o:Tx(u)?a:(0,Ex.default)(a,parseInt(u,10),"0"))}return t},Px=(s,e)=>{var k,P,O,$,M,Q,U,w,F,A,x,B,oe,Ve,se,K,ye,Te,Ie,Oe,Et,At,qt,Jt,ki,vs,ys,Ts,Is,xs,Es,ws,Ps,As,ks,Rs,Ls,Ms,$s,Bs,Ds,Cs,Vs,Os,_s,Fs,Ns,Us,qs,js,Hs,Gs,zs,Qs,Ws,Ys,Ks,Xs,Js,Zs,ea;let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(ce=>{var _,We;return(We=(_=ce.textContent)==null?void 0:_.trim())!=null?We:""}),o=(k=(0,wx.default)(n,0))!=null?k:"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),d=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],h=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:f==="yes"});let S,y=a.getAttribute("mediaPresentationDuration"),v=[...a.getElementsByTagName("Period")],I=v.reduce((ce,_)=>({...ce,[_.id]:_.children}),{}),T=v.reduce((ce,_)=>({...ce,[_.id]:_.getAttribute("duration")}),{});y?S=Ix(y):(0,Xp.default)(T).filter(ce=>ce).length&&!u?S=(0,Xp.default)(T).reduce((ce,_)=>{var We;return ce+((We=Ix(_))!=null?We:0)},0):m&&(S=parseInt(m,10));let E=0,V=(O=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?O:[];for(let ce of v.map(_=>_.id))for(let _ of I[ce]){let We=($=_.getAttribute("id"))!=null?$:"id"+(E++).toString(10),kt=(M=_.getAttribute("mimeType"))!=null?M:"",zi=(Q=_.getAttribute("codecs"))!=null?Q:"",Qi=(U=_.getAttribute("contentType"))!=null?U:kt==null?void 0:kt.split("/")[0],$l=(F=(w=_.getAttribute("profiles"))==null?void 0:w.split(","))!=null?F:[],ta=(x=mx((A=_.getAttribute("lang"))!=null?A:""))!=null?x:{},Zt=(Ve=(oe=(B=_.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:oe.trim())!=null?Ve:void 0,Bl=_.querySelectorAll("Representation"),Dl=_.querySelector("SegmentTemplate"),Cl=(K=(se=_.querySelector("Role"))==null?void 0:se.getAttribute("value"))!=null?K:void 0,dt=Qi,H={id:We,language:ta.language,isDefault:Cl==="main",label:Zt,codecs:zi,hdr:dt==="video"&&ts(zi),mime:kt,representations:[]};for(let C of Bl){let Pe=(ye=C.getAttribute("lang"))!=null?ye:void 0,Rt=(Ie=(Te=Zt!=null?Zt:_.getAttribute("label"))!=null?Te:C.getAttribute("label"))!=null?Ie:void 0,ei=(At=(Et=(Oe=C.querySelector("BaseURL"))==null?void 0:Oe.textContent)==null?void 0:Et.trim())!=null?At:"",Ye=new URL(ei||o,e).toString(),Ae=(qt=C.getAttribute("mimeType"))!=null?qt:kt,ti=(ki=(Jt=C.getAttribute("codecs"))!=null?Jt:zi)!=null?ki:"",ii;if(Qi==="text"){let ke=C.getAttribute("id")||"",ri=((vs=ta.privateuse)==null?void 0:vs.includes("x-auto"))||ke.includes("_auto"),Ke=C.querySelector("SegmentTemplate");if(Ke){let Lt={representationId:(ys=C.getAttribute("id"))!=null?ys:void 0,bandwidth:(Ts=C.getAttribute("bandwidth"))!=null?Ts:void 0},si=parseInt((Is=C.getAttribute("bandwidth"))!=null?Is:"",10)/1e3,ai=(Es=parseInt((xs=Ke.getAttribute("startNumber"))!=null?xs:"",10))!=null?Es:1,pt=parseInt((ws=Ke.getAttribute("timescale"))!=null?ws:"",10),Wi=(Ps=Ke.querySelectorAll("SegmentTimeline S"))!=null?Ps:[],ht=Ke.getAttribute("media");if(!ht)continue;let ni=[],oi=0,ui="",ft=0,Mt=ai,ee=0;for(let de of Wi){let Xe=parseInt((As=de.getAttribute("d"))!=null?As:"",10),ne=parseInt((ks=de.getAttribute("r"))!=null?ks:"",10)||0,Re=parseInt((Rs=de.getAttribute("t"))!=null?Rs:"",10);ee=Number.isFinite(Re)?Re:ee;let Je=Xe/pt*1e3,Le=ee/pt*1e3;for(let me=0;me<ne+1;me++){let Me=xi(ht,{...Lt,segmentNumber:Mt.toString(10),segmentTime:(ee+me*Xe).toString(10)}),mt=(Le!=null?Le:0)+me*Je,Bt=mt+Je;Mt++,ni.push({time:{from:mt,to:Bt},url:Me})}ee+=(ne+1)*Xe,oi+=(ne+1)*Je}ft=ee/pt*1e3,ui=xi(ht,{...Lt,segmentNumber:Mt.toString(10),segmentTime:ee.toString(10)});let $t={time:{from:ft,to:1/0},url:ui},xe={type:"template",baseUrl:Ye,segmentTemplateUrl:ht,initUrl:"",totalSegmentsDurationMs:oi,segments:ni,nextSegmentBeyondManifest:$t,timescale:pt};ii={id:ke,kind:"text",segmentReference:xe,profiles:[],duration:S,bitrate:si,mime:"",codecs:"",width:0,height:0,isAuto:ri}}else ii={id:ke,isAuto:ri,kind:"text",url:Ye}}else{let ke=(Ms=(Ls=C.getAttribute("contentType"))!=null?Ls:Ae==null?void 0:Ae.split("/")[0])!=null?Ms:Qi,ri=(Bs=($s=_.getAttribute("profiles"))==null?void 0:$s.split(","))!=null?Bs:[],Ke=parseInt((Ds=C.getAttribute("width"))!=null?Ds:"",10),Lt=parseInt((Cs=C.getAttribute("height"))!=null?Cs:"",10),si=parseInt((Vs=C.getAttribute("bandwidth"))!=null?Vs:"",10)/1e3,ai=(Os=C.getAttribute("frameRate"))!=null?Os:"",pt=(_s=C.getAttribute("quality"))!=null?_s:void 0,Wi=ai?Cu(ai):void 0,ht=(Fs=C.getAttribute("id"))!=null?Fs:"id"+(E++).toString(10),ni=ke==="video"?`${Lt}p`:ke==="audio"?`${si}Kbps`:ti,oi=`${ht}@${ni}`,ui=[...V,...$l,...ri],ft,Mt=C.querySelector("SegmentBase"),ee=(Ns=C.querySelector("SegmentTemplate"))!=null?Ns:Dl;if(Mt){let xe=(qs=(Us=C.querySelector("SegmentBase Initialization"))==null?void 0:Us.getAttribute("range"))!=null?qs:"",[de,Xe]=xe.split("-").map(Me=>parseInt(Me,10)),ne={from:de,to:Xe},Re=(js=C.querySelector("SegmentBase"))==null?void 0:js.getAttribute("indexRange"),[Je,Le]=Re?Re.split("-").map(Me=>parseInt(Me,10)):[],me=Re?{from:Je,to:Le}:void 0;ft={type:"byteRange",url:Ye,initRange:ne,indexRange:me}}else if(ee){let xe={representationId:(Hs=C.getAttribute("id"))!=null?Hs:void 0,bandwidth:(Gs=C.getAttribute("bandwidth"))!=null?Gs:void 0},de=parseInt((zs=ee.getAttribute("timescale"))!=null?zs:"",10),Xe=(Qs=ee.getAttribute("initialization"))!=null?Qs:"",ne=ee.getAttribute("media"),Re=(Ys=parseInt((Ws=ee.getAttribute("startNumber"))!=null?Ws:"",10))!=null?Ys:1,Je=xi(Xe,xe);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Le=(Ks=ee.querySelectorAll("SegmentTimeline S"))!=null?Ks:[],me=[],Me=0,mt="",Bt=0;if(Le.length){let li=Re,pe=0;for(let bt of Le){let be=parseInt((Xs=bt.getAttribute("d"))!=null?Xs:"",10),Ze=parseInt((Js=bt.getAttribute("r"))!=null?Js:"",10)||0,ci=parseInt((Zs=bt.getAttribute("t"))!=null?Zs:"",10);pe=Number.isFinite(ci)?ci:pe;let Yi=be/de*1e3,Ki=pe/de*1e3;for(let di=0;di<Ze+1;di++){let Ol=xi(ne,{...xe,segmentNumber:li.toString(10),segmentTime:(pe+di*be).toString(10)}),ia=(Ki!=null?Ki:0)+di*Yi,_l=ia+Yi;li++,me.push({time:{from:ia,to:_l},url:Ol})}pe+=(Ze+1)*be,Me+=(Ze+1)*Yi}Bt=pe/de*1e3,mt=xi(ne,{...xe,segmentNumber:li.toString(10),segmentTime:pe.toString(10)})}else if(iV(S)){let pe=parseInt((ea=ee.getAttribute("duration"))!=null?ea:"",10)/de*1e3,bt=Math.ceil(S/pe),be=0;for(let Ze=1;Ze<bt;Ze++){let ci=xi(ne,{...xe,segmentNumber:Ze.toString(10),segmentTime:be.toString(10)});me.push({time:{from:be,to:be+pe},url:ci}),be+=pe}Bt=be,mt=xi(ne,{...xe,segmentNumber:bt.toString(10),segmentTime:be.toString(10)})}let Vl={time:{from:Bt,to:1/0},url:mt};ft={type:"template",baseUrl:Ye,segmentTemplateUrl:ne,initUrl:Je,totalSegmentsDurationMs:Me,segments:me,nextSegmentBeyondManifest:Vl,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ke||!Ae)continue;let $t={video:"video",audio:"audio",text:"text"}[ke];if(!$t)continue;dt||(dt=$t),ii={id:oi,kind:$t,segmentReference:ft,profiles:ui,duration:S,bitrate:si,mime:Ae,codecs:ti,width:Ke,height:Lt,fps:Wi,quality:pt}}H.language||(H.language=Pe),H.label||(H.label=Rt),H.mime||(H.mime=Ae),H.codecs||(H.codecs=ti),H.hdr||(H.hdr=dt==="video"&&ts(ti)),H.representations.push(ii)}if(dt){let C=r[dt].find(Pe=>Pe.id===H.id);if(C&&H.representations.every(Pe=>rt(Pe.segmentReference)))for(let Pe of C.representations){let Rt=H.representations.find(Ae=>Ae.id===Pe.id),ei=Rt==null?void 0:Rt.segmentReference,Ye=Pe.segmentReference;Ye.segments.push(...ei.segments),Ye.nextSegmentBeyondManifest=ei.nextSegmentBeyondManifest}else r[dt].push(H)}}return{duration:S,streams:r,baseUrls:n,live:g}};var so=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new yr(0);this.currentLowLatencySegmentLength$=new yr(0);this.currentSegmentLength$=new yr(0);this.onLastSegment$=new yr(!1);this.fullyBuffered$=new yr(!1);this.playingRepresentation$=new yr(void 0);this.playingRepresentationInit$=new yr(void 0);this.error$=new sV;this.gaps=[];this.subscription=new aV;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ae;this.switchAbortController=new ae;this.destroyAbortController=new ae;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=qi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);ct(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ox(this.sourceBuffer),this.subscription.add(Zp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ei.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ei.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Zp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ei.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!G(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Jr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=De(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);ct(i,"No init buffer for starting representation"),ct(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=qi(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ct(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Qe(a)||Qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ct(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ds(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=qi(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);ct(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Qe(a)||Qe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),ct(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ds(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=qi(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,ul.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(f=>f.id===d);c&&this.representations.set(d,c);let h=this.representations.get(d);if(!h||!rt(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);ct(r);let a=this.segments.get(i);ct(a,"No segments for starting representation");let n=this.initData.get(i);if(ct(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(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,qi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);ct(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Qe(o)||Qe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),ct(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ds(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Qe(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 ae,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Qe(e)||Qe(this.downloadingRepresentationId)||Qe(this.playingRepresentationId)||Qe(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||ds(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(ct(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);ds(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let a=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=De(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(a=c)}if(isFinite(this.bufferLimit)&&Jr(this.sourceBuffer.buffered)>=this.bufferLimit){let d=De(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,a),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,ol.default)(u,r))d="high";else{let c=(0,ps.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&De(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ps.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-De(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;ds(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,ul.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,a,n;let t=(i=(0,ul.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!rt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,ps.default)(d,-1))==null?void 0:a.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ct(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!rt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=xi(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var a,n,o;let t=(n=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Yt&&Yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yt&&Yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:h,to:p}},f)=>{let m=h<=i&&p>=i,g=h>i||m||f===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+S||p<=i+S;return(c==="none"||c==="partially_ejected"&&g&&y&&this.sourceBuffer&&G(this.mediaSource,this.sourceBuffer)&&!(Ge(this.sourceBuffer.buffered,h)&&Ge(this.sourceBuffer.buffered,p)))&&g&&y});if(r===-1)return null;if(t!=="byteRange")return e.slice(r,r+1);let a=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=l||o<=d);c++){let h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}async loadSegments(e,t,i="auto"){rt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await qi(o,async function*(){let d=eh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=nl(),!d)return;let c=new DataView(d),h=io(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(c);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),ro(d)||(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())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="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:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await qi(n,async function*(){let u=eh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Zp(window,"online").pipe(rV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=nl(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ro(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ps.default)(e,0).byte.from,to:(0,ps.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=nl(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ei.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=nl();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Ei.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,ol.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=io(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,h=c-d+1,p=d<r,f=c<=r;if(p){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+d,h);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(h,r-d),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===h?m:io(o.mime).parseFeedableSegmentChunk(m);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===h&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(Qe(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer))){!this.isLive&&q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ge(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ge(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ei.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",Yp(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Xr(()=>(0,Ax.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?qi(this.destroyAbortController.signal,async function*(){let o=eh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,io(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let h=d;this.isLive&&rt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Ei.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,i=!1){if(!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Qe(e))return!1;let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push({...o.time});let u=Yp(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let h of c)(0,ol.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(u)&&Math.round(h.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=yx(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!G(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||!G(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)}}getBufferedTo(){return!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Qe(e)?0:De(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))return;if(this.tuning.useRefactoredSearchGap)for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));let i={representation:e,from:t.time.from,to:t.time.to};for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=this.sourceBuffer.buffered.start(r)*1e3,n=this.sourceBuffer.buffered.end(r)*1e3;if(!(n<=t.time.from||a>=t.time.to)){if(a<=t.time.from&&n>=t.time.to){i=void 0;break}n>t.time.from&&n<t.time.to&&(i.from=n),a<t.time.to&&a>t.time.from&&(i.to=a)}}i&&i.to-i.from>1&&!this.gaps.some(r=>i&&r.from===i.from&&r.to===i.to)&&this.gaps.push(i)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Xr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Ei.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Qe(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||Qe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Ei.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as ao,assertNever as kx,fromEvent as Rx,merge as nV,now as no,Subject as Lx,ValueSubject as th,flattenObject as hs,ErrorCategory as oo,SubscriptionRemovable as oV}from"@vkontakte/videoplayer-shared/es2018";var cl=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new th(void 0);this.lastConnectionReused$=new th(void 0);this.lastRequestFirstBytes$=new th(void 0);this.recoverableError$=new Lx;this.error$=new Lx;this.abortAllController=new ae;this.subscription=new oV;this.fetchManifest=ao(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Fi(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Nu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ll);return r?(t.log("success",hs({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",hs({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ao(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var $,M,Q;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let U=new URL(l,location.href);U.searchParams.append("bytes",`${i.from}-${i.to}`),l=U.toString();break}default:kx(t)}this.requestQuic&&(l=Fi(l));let h=this.abortAllController.signal,p;if(n){let U=new ae;if(p=nV(Rx(this.abortAllController.signal,"abort"),Rx(n,"abort")).subscribe(()=>{try{U.abort()}catch(w){ll(w)}}),this.abortAllController.signal.aborted||n.aborted)try{U.abort()}catch(w){ll(w)}h=U.signal}let f=no();c.log("startRequest",hs({url:l,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:f}));let m=yield this.doFetch(l,{priority:a,headers:d,signal:h}),g=no();if(!m)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(p),null;if(($=this.throughputEstimator)==null||$.addRawRtt(g-f),!m.ok||!m.body){this.unsubscribeAbortSubscription(p);let U=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:U}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){this.unsubscribeAbortSubscription(p);let U=no(),w={requestStartedAt:f,requestEndedAt:U,duration:U-f};return c.log("endRequest",hs(w)),c.end(),m.arrayBuffer()}let S=m.body;if(o){let U;[S,U]=m.body.tee(),(M=this.throughputEstimator)==null||M.trackStream(U,u)}let y=S.getReader(),v,I=parseInt((Q=m.headers.get("content-length"))!=null?Q:"",10);Number.isFinite(I)&&(v=I),!v&&i&&(v=i.to-i.from+1);let T=0,E=v?new Uint8Array(v):new Uint8Array(0),V=!1,L=U=>{this.unsubscribeAbortSubscription(p),V=!0,ll(U)},k=ao(h,async function*({done:U,value:w}){if(T===0&&this.lastRequestFirstBytes$.next(no()-f),h.aborted){this.unsubscribeAbortSubscription(p);return}if(!U&&w){if(v)E.set(w,T),T+=w.byteLength;else{let F=new Uint8Array(E.length+w.length);F.set(E),F.set(w,E.length),E=F,T+=w.byteLength}r==null||r(new DataView(E.buffer),T),yield y==null?void 0:y.read().then(k,L)}}.bind(this));yield y==null?void 0:y.read().then(k,L),this.unsubscribeAbortSubscription(p);let P=no(),O={failed:V,requestStartedAt:f,requestEndedAt:P,duration:P-f};return V?(c.error("endRequest",hs(O)),c.end(),null):(c.log("endRequest",hs(O)),c.end(),E.buffer)}.bind(this));this.fetchByteRangeRepresentation=ao(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(d,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let h=new DataView(c,r-n,a-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let y=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!y)return null;m=new DataView(y)}let g=t.parseSegments(m,p,f);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=ao(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Fu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:kx(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Pt(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:oo.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:oo.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:oo.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:oo.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:oo.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},ll=s=>{if(!ro(s))throw s};import{isNullable as uV,ValueSubject as lV}from"@vkontakte/videoplayer-shared/es2018";var uo=class s{constructor(e,t){this.currentRepresentation$=new lV(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(!uV(e))for(let i of this.representations)for(let r of i){let a=r.segmentReference,n=a.segments.length,o=a.segments[0].time.from,u=a.segments[n-1].time.to;if(e<o||e>u)continue;let l=a.segments.find(d=>d.time.from<=e&&d.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({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>s.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var mV=["timeupdate","progress","play","seeked","stalled","waiting"],bV=["timeupdate","progress","loadeddata","playing","seeked"];var hl=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new nh;this.representationSubscription=new nh;this.state$=new j("none");this.currentVideoRepresentation$=new fe(void 0);this.currentVideoRepresentationInit$=new fe(void 0);this.currentAudioRepresentation$=new fe(void 0);this.currentVideoSegmentLength$=new fe(0);this.currentAudioSegmentLength$=new fe(0);this.error$=new pl;this.lastConnectionType$=new fe(void 0);this.lastConnectionReused$=new fe(void 0);this.lastRequestFirstBytes$=new fe(void 0);this.currentLiveTextRepresentation$=new fe(null);this.isLive$=new fe(!1);this.isActiveLive$=new fe(!1);this.isLowLatency$=new fe(!1);this.liveDuration$=new fe(0);this.liveSeekableDuration$=new fe(0);this.liveAvailabilityStartTime$=new fe(0);this.liveStreamStatus$=new fe(void 0);this.bufferLength$=new fe(0);this.liveLatency$=new fe(void 0);this.liveLoadBufferLength$=new fe(0);this.livePositionFromPlayer$=new fe(0);this.currentStallDuration$=new fe(0);this.videoLastDataObtainedTimestamp$=new fe(0);this.fetcherRecoverableError$=new pl;this.fetcherError$=new pl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new pl;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=rh(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Se(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Xt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=rh(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:Xt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Px(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Du(e))!=null?n:{id:"ManifestParsing",category:Xt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,h,p,f;return!!((h=(c=this.element)==null?void 0:c.canPlayType)!=null&&h.call(c,l)&&((f=(p=It())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:f})=>i(u,p,f)),c=new Set(d.map(({codecs:p})=>p)),h=Yu(c);if(h&&(r[u]=d.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);q.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a={...t,streams:r};return this.tracer.log("updateManifestEnd",co(a)),a}.bind(this));this.initRepresentations=rh(this.destroyController.signal,async function*(e,t,i){var h;this.tracer.log("initRepresentationsStart",co({initialVideo:e,initialAudio:t,sourceHls:i})),fs(this.manifest),fs(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new nh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(wi(p,"error").pipe(dl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Xt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?du():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&jr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new so("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],po(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new so("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}uo.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new uo(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Tr(...bV.map(p=>wi(this.element,p))).pipe(bs(p=>this.element?De(this.element.buffered,this.element.currentTime*1e3):0),lo(),hV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Tr(wi(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(lo()).subscribe(f=>this.liveStreamEndTimestamp=ah())),this.subscription.add(wi(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=sh(1e3).subscribe(f=>{let m=$i(this.manifestUrlString,2);this.manifestUrlString=Se(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(wi(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(ms({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(bs(({isActiveLive:f,isLowLatency:m})=>f&&m),lo()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||as(this.element,1)})),this.representationSubscription.add(ms({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(dl(({bufferLength:f,isActiveLive:m,isLowLatency:g})=>m&&g&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(f=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!f)return;let m=this.liveSeekableDuration$.getValue()-f/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+f/1e3)})),this.representationSubscription.add(ms({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(dl(({isLive:f})=>f),lo((f,m)=>m.bufferLength<f.bufferLength),bs(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=$i(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ms({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:f,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=f-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>y&&(T=1+Math.sign(I)*v),as(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let m=0;if(f){let y=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,E;return(E=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?E:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(ms({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(fV(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=$i(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,E=isFinite(f)?f:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let k="none";if(V?k="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),k="active_low_latency"):S!==0&&E<v?k="live_forward_buffering":E<v+T&&(k="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),k==="live_forward_buffering"||k==="live_with_target_offset"){let P=p-(v+I),O=this.normolizeLiveOffset(Math.trunc(S+P/g)),$=Math.abs(O-S),M=0;!f||$<=this.tuning.dashCmafLive.offsetCalculationError?M=S:O>0&&$>this.tuning.dashCmafLive.offsetCalculationError&&(M=O),this.manifestUrlString=Se(this.manifestUrlString,M,2)}(k==="live_with_target_offset"||k==="live_forward_buffering")&&(p=0,await this.updateLive())},f=>{this.error$.next({id:"updateLive",category:Xt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=Tr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(bs(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Tr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(bs(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=ms({allBuffersFull:l,someBufferEnded:d}).pipe(lo(),bs(({allBuffersFull:p,someBufferEnded:f})=>p&&f),dl(p=>p));if(this.representationSubscription.add(Tr(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Xt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(Tr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((f,m)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var S;if(((S=this.source)==null?void 0:S.readyState)==="open"){f();return}this.tuning.dash.rejectOnSourceOpenTimeout?m(new Error("Timeout reject when wait sourceopen event")):f()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),f()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,oh.default)((0,oh.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),rt(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&po(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,i,r,a;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(a=this.audioBufferManager)!=null&&a.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=sh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Xt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new cl({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=yi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,a,n;fs(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ah()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Se(this.manifestUrlString,i,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((a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){fs(this.element),this.state$.setState("running"),this.subscription.add(Tr(...mV.map(e=>wi(this.element,e)),wi(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Xt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(wi(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(wi(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ge(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,y,v,I,T,E,V;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=ah(),n=100,o=(m=(f=this.videoBufferManager)==null?void 0:f.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(v=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?v:0,d=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&d<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(k=>{this.error$.next({id:"stallIntervalCallback",category:Xt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:k})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(L),(V=this.audioBufferManager)==null||V.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",co(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=sh(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Xt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,a,n,o,u;fs(this.element),fs(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ge(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!($x(this.element)||$x(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",co({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;po(this.element)&&po(this.source)&&po(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=pV(this.tracer.error.bind(this.tracer));this.subscription.add(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(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue();this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,r=null,a=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-a<=i&&o.to+a>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?r=1/0:(r===null||o.to>r)&&(r=o.to));if(r!==null){let n=r+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,this.tracer.log("jumpGap",co({isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime,jumpTo:n,resultCurrentTime:this.element.currentTime})))}}};import{combine as gV,map as SV,observeElementSize as vV,Subscription as yV,ValueSubject as uh,noop as TV}from"@vkontakte/videoplayer-shared/es2018";var fl=class{constructor(){this.subscription=new yV;this.pipSize$=new uh(void 0);this.videoSize$=new uh(void 0);this.elementSize$=new uh(void 0);this.pictureInPictureWindowRemoveEventListener=TV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(vV(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(gV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(SV(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ir=class{constructor(e){this.subscription=new AV;this.videoState=new j("stopped");this.droppedFramesManager=new Yr;this.stallsManager=new il;this.elementSizeManager=new fl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Vi;this.audioTrackSwitchHistory=new Vi;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return xV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ls(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.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 nt(e.source.url),this.params=e,this.video=Ne(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(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 hl({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,i=je(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Bx.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Dx(l=>!!l.length),Vx()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(lh(l=>l.to.state!=="none"),ml());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Dx(Cx),Vx()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(lh(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(wt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(at(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(EV(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(Qp(p));let f=[];for(let m of p.representations){let g=gx(m);f.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,f)}this.params.output.availableAudioStreams$.next(h)}let c=[];for(let h of d.video){c.push(Wp(h));let p=[];for(let f of h.representations){let m=bx({...f,streamId:h.id});m&&(p.push(m),this.videoTracksMap.set(m,{stream:h,representation:f}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(c);for(let h of d.text)for(let p of h.representations){let f=Sx(h,p);this.textTracksMap.set(f,{stream:h,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(bl(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$,PV(this.video,"progress")).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(l!=="manifest_ready"&&l!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:c,audio:h}=this.selectedRepresentations;if(!c)return;let p=vr(this.videoTracksMap.keys(),m=>{var g;return((g=this.videoTracksMap.get(m))==null?void 0:g.representation.id)===c.id});Cx(p)&&(this.stallsManager.lastVideoTrackSelected=p);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")await this.player.initRepresentations(c.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",c.id),h){let m=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,m)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ml()).subscribe(l=>{let d=vr(this.videoTracksMap.entries(),([,{representation:f}])=>f.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(Wp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ml()).subscribe(l=>{let d=vr(this.audioTracksMap.entries(),([,{representation:f}])=>f.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:h}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Qp(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(lh(({to:l})=>l==="ready"),ml());this.subscription.add(bl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ch(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(bl(o,this.player.state$.stateChangeEnded$,ch(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=bl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ch(["init"])).pipe(wV(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,k,P,O,$,M,Q,U,w,F,A,x;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Da:Ba,t=this.params.tuning.useNewAutoSelectVideoTrack?Au:Pu,i=this.params.tuning.useNewAutoSelectVideoTrack?Wt:wu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=vr(this.videoTracksMap.keys(),B=>B.id===o),l=a.currentVideoTrack$.getValue(),d=((O=(P=r.videoStream.getState())!=null?P:u&&((k=this.videoTracksMap.get(u))==null?void 0:k.stream))!=null?O:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=vr(this.videoStreamsMap.keys(),B=>B.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=De(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(f,m||1/0),1),S=($=r.audioStream.getState())!=null?$:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(S==null?void 0:S.id)&&vr(this.audioStreamsMap.keys(),B=>B.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(y){if(u&&!n){let B=e(u,h,(M=this.audioStreamsMap.get(y))!=null?M:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(Q=B==null?void 0:B.bitrate)!=null?Q:-1/0)}if(l){let B=e(l,h,(U=this.audioStreamsMap.get(y))!=null?U:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(w=B==null?void 0:B.bitrate)!=null?w:-1/0)}}let I=u;(n||!I)&&(I=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:g,current:l,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}));let T=y&&t(I,h,(F=this.audioStreamsMap.get(y))!=null?F:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(A=this.videoTracksMap.get(I))==null?void 0:A.representation,V=T&&((x=this.audioTracksMap.get(T))==null?void 0:x.representation);E&&V?(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=V):E&&!V&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bx.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),Ue(this.video),this.tracer.end()}};var ho=class extends Ir{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as dh,merge as Ox,filter as _x,filterChanged as kV,isNullable as ph,map as Fx,ValueSubject as hh,isNonNullable as RV}from"@vkontakte/videoplayer-shared/es2018";var fo=class extends Ir{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(i.timeUpdate$,t.liveBufferTime$),a(this.player.liveSeekableDuration$,t.duration$),a(this.player.liveLatency$,t.liveLatency$);let n=new hh(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Fx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(dh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Fx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(_x(o=>RV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(dh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Ox(i.playbackRateState$,new hh(1))}).pipe(_x(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||u<1-c||this.video.paused||ph(l)||(e=o-l)})).add(dh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Ox(i.playbackRateState$,new hh(1))}).pipe(kV((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let d=t.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&l>=1-c||ph(o)||ph(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=vx(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var Ux=N(Pa(),1);import{assertNever as mo,assertNonNullable as Nx,debounce as LV,ErrorCategory as gl,filter as MV,isNonNullable as $V,isNullable as BV,map as Sl,merge as DV,Observable as CV,observableFrom as VV,Subscription as OV,videoSizeToQuality as _V}from"@vkontakte/videoplayer-shared/es2018";var Ut={};var gs=(s,e)=>new CV(t=>{let i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)}),bo=class{constructor(e){this.subscription=new OV;this.videoState=new j("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:mo(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:mo(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:mo(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:mo(e)}break;default:mo(t)}};this.textTracksManager=new nt(e.source.url),this.video=Ne(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(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),Ue(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:gl.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Ux.default)(import("hls.js").then(r=>{e||(Ut.Hls=r.default,Ut.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){Nx(Ut.Hls,"hls.js not loaded"),this.hls=new Ut.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Nx(Ut.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:gl.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=je(this.video);this.subscription.add(()=>r.destroy());let a=(l,d)=>this.subscription.add(l.subscribe(d,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.loadedMetadata$,t.loadedMetadataEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(wt(this.video,e.isLooped,i)),this.subscription.add(qe(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(at(this.video,e.playbackRate,r.playbackRateState$,i)),a(ut(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(Sl(l=>l.to)),this.params.output.playbackState$),this.subscription.add(gs(this.hls,Ut.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:gl.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(gs(this.hls,Ut.Events.MANIFEST_PARSED).pipe(Sl(({levels:l})=>l.reduce((d,c)=>{var y,v;let h=c.name||c.height.toString(10),{width:p,height:f}=c,m=(v=Qt((y=c.attrs.QUALITY)!=null?y:""))!=null?v:_V({width:p,height:f});if(!m)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,S={id:h.toString(),quality:m,bitrate:c.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:S,level:c}),d.push(S),d},[]))),t.availableVideoTracks$),a(gs(this.hls,Ut.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let h=c.name,p=c.attrs.URI||"",f=c.lang;d.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),a(gs(this.hls,Ut.Events.LEVEL_LOADING).pipe(Sl(({url:l})=>we(l))),t.hostname$),a(gs(this.hls,Ut.Events.FRAG_CHANGED),l=>{var h,p,f,m;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=d==null?void 0:d.endPTS)!=null?h:0)-((p=d==null?void 0:d.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((m=c==null?void 0:c.startPTS)!=null?m:0))*1e3)}),this.subscription.add(Bi(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=gs(this.hls,Ut.Events.LEVEL_SWITCHED).pipe(Sl(({level:l})=>n(this.hls.levels[l])));o.pipe(MV($V)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Bi(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(BV(l))return;let d=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!d)return;let c=this.hls.levels.indexOf(d),h=this.hls.currentLevel,p=this.hls.levels[h];!p||d.bitrate>p.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=DV(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,VV(["init"])).pipe(LV(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gl.DOM,thrown:t}))||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0)}};var qx="X-Playback-Duration",fh=async s=>{var r;let e=await Pt(s),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(qx)?parseInt(e.headers.get(qx),10):void 0};import{assertNever as YV,combine as KV,debounce as XV,ErrorCategory as Tl,filter as JV,filterChanged as ZV,isNonNullable as Gx,isNullable as Il,map as zx,merge as eO,observableFrom as tO,Subscription as iO,ValueSubject as gh,VideoQuality as rO}from"@vkontakte/videoplayer-shared/es2018";var bh=N(zc(),1);import{videoSizeToQuality as FV,getExponentialDelay as NV}from"@vkontakte/videoplayer-shared/es2018";var UV=s=>{let e=null;if(s.QUALITY&&(e=Qt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=FV({width:t,height:i})}return e!=null?e:null},qV=(s,e)=>{var a,n;let t=s.split(`
|
|
186
|
+
`),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,bh.default)(l[1].split(",").map(y=>y.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=UV(c),f;c.BANDWIDTH&&(f=parseInt(c.BANDWIDTH,10)/1e3||void 0),!f&&c["AVERAGE-BANDWIDTH"]&&(f=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[y,v]=c.RESOLUTION.split("x").map(I=>parseInt(I,10));y&&v&&(g={width:y,height:v})}let S=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:S,bandwidth:f,size:g,fps:m})}if(d){let c=(0,bh.default)(d[1].split(",").map(m=>{let g=m.indexOf("=");return[m.substring(0,g),m.substring(g+1)]}).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),h=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,f=c.NAME;h&&p&&r.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},jV=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),mh=0,jx=async(s,e=s,t,i)=>{let a=await(await Pt(s,i)).text();mh+=1;try{let{qualityManifests:n,textTracks:o}=qV(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(mh<=t.manifestRetryMaxCount)return await jV(NV(mh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),jx(s,e,t)}return{qualityManifests:[],textTracks:[]}},vl=jx;import{isNonNullable as HV,Subscription as GV,throttle as zV,ValueSubject as Hx,Subject as QV,ErrorCategory as WV}from"@vkontakte/videoplayer-shared/es2018";var yl=class{constructor(e,t,i,r,a){this.subscription=new GV;this.abortControllers={destroy:new ae,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Hx(null);this.getCurrentTime$=new Hx(null);this.error$=new QV;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(zV(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:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await Pt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
187
|
+
`),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+d},url:l}),a=a+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(HV(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ae;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:WV.WTF,thrown:t,message:e})}};var go=class{constructor(e){this.subscription=new iO;this.videoState=new j("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new gh([]);this.liveOffset=new cr;this.manifestStartTime$=new gh(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return YV(t)}};var i;this.params=e,this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:rO.INVARIANT,url:this.params.source.url};let t=(r,a)=>vl(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new yl(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new nt(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Tl.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Tl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new gh((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Tl.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=je(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(qe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(at(this.video,t.playbackRate,r.playbackRateState$,i)),a(ut(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(ZV(),zx(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Gx(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(KV({startTime:this.manifestStartTime$.pipe(JV(Gx)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(zx(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=eO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,tO(["init"])).pipe(XV(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Il(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[d,"mq"],[c,"lq"]]){let f=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,f)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=Se(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),fh(n).then(d=>{var c;if(!Il(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(Il(h)||!isFinite(h))&&Pt(n).then(p=>p.text()).then(p=>{var m;let f=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(f){let g=new URL(f,n).toString();fh(g).then(S=>{Il(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=Se(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 sO,debounce as aO,ErrorCategory as Sh,fromEvent as vh,isNonNullable as nO,isNullable as oO,map as Qx,merge as Wx,observableFrom as Yx,Subscription as uO,ValueSubject as lO,VideoQuality as cO}from"@vkontakte/videoplayer-shared/es2018";var So=class{constructor(e){this.subscription=new uO;this.videoState=new j("stopped");this.manifests$=new lO([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return sO(t)}};this.textTracksManager=new nt(e.source.url),this.params=e,this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:cO.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(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),vl(Se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Sh.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Sh.WTF,message:"HlsProvider internal logic error",thrown:o})},r=je(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(Qx(o=>o.to)),this.params.output.playbackState$),this.subscription.add(wt(this.video,t.isLooped,i)),this.subscription.add(qe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(at(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&nO(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===f);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(we(m.url)))}let c=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(Qx(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:h})=>({id:u,quality:l,size:d,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!q.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Wx(vh(o,"addtrack"),vh(o,"removetrack"),vh(o,"change"),Yx(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=Wx(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Yx(["init"])).pipe(aO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){var a,n;let e=this.selectManifest();if(oO(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(a=t==null?void 0:t.to)!=null?a:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Sh.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Jx=N(tr(),1),yh=N(lr(),1),Zx=N(_t(),1);import{assertNever as dO,assertNonNullable as Kx,debounce as pO,ErrorCategory as Xx,isHigherOrEqual as hO,isLowerOrEqual as fO,isNonNullable as mO,merge as bO,observableFrom as gO,Subscription as SO,map as vO}from"@vkontakte/videoplayer-shared/es2018";var vo=class{constructor(e){this.subscription=new SO;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new nt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return dO(e)}};this.params=e,this.video=Ne(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Jx.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,yh.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:Xx.WTF,message:"MpegProvider internal logic error",thrown:o})},r=je(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(vO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(wt(this.video,t.isLooped,i)),this.subscription.add(qe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(at(this.video,t.playbackRate,r.playbackRateState$,i)),a(ut(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&mO(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=bO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,gO(["init"])).pipe(pO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ue(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;Kx(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Kx(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Fi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(we(t))}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xx.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let h=Wt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,yh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||Hr(e,n[0].quality,(d=(0,Zx.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?fO(r,e.max):!0,u=e.min?hO(r,e.min):!0;o&&u||i(e)}};import{assertNever as tE,debounce as xO,merge as iE,observableFrom as EO,Subscription as wO,map as rE,ValueSubject as PO,ErrorCategory as Ih,VideoQuality as AO}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as yO}from"@vkontakte/videoplayer-shared/es2018";var eE=["stun:videostun.mycdn.me:80"],TO=1e3,IO=3,Th=()=>null,xl=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=Th;this.externalStopCallback=Th;this.externalErrorCallback=Th;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}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:eE}]};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:yO.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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),TO)}normalizeOptions(e={}){let t={stunServerList:eE,maxRetryNumber:IO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var yo=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new PO(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return tE(e)}};this.subscription=new wO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ne(e.container,e.tuning),this.liveStreamClient=new xl(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),Ue(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ih.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(iE(this.videoState.stateChangeStarted$.pipe(rE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(rE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=je(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(ut(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(qe(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return tE(n.to)}},i)).add(iE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,EO(["init"])).pipe(xO(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(we(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:AO.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ih.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){He(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ih.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var To=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 xo,assertNonNullable as ji,ErrorCategory as El,filter as lE,isNonNullable as cE,isNullable as DO,map as CO,merge as VO,once as OO,Subject as Ce,Subscription as dE,ValueSubject as W,flattenObject as pE}from"@vkontakte/videoplayer-shared/es2018";import{Observable as kO,map as sE,Subscription as RO,Subject as LO}from"@vkontakte/videoplayer-shared/es2018";var aE=s=>new kO(e=>{let t=new RO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(sE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(sE(({type:l})=>l!==void 0)),n=new LO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as MO,Subscription as $O,combine as BO,filter as oE,once as uE}from"@vkontakte/videoplayer-shared/es2018";function nE(){return new(window.AudioContext||window.webkitAudioContext)}var Io=class Io{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ae;this.subscriptions=new $O;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(oE(a=>!!a.type),uE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){q.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(BO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(oE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),uE()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=nE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Io.errorId,category:MO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Io.errorId} exception`,thrown:e})}};Io.errorId="VolumeMultiplierManager";var Ss=Io;var _O={chunkDuration:5e3,maxParallelRequests:5},Eo=class{constructor(e){this.current$=new W({type:void 0});this.providerError$=new Ce;this.noAvailableProvidersError$=new Ce;this.volumeMultiplierError$=new Ce;this.providerOutput={position$:new W(0),duration$:new W(1/0),volume$:new W({muted:!1,volume:1}),availableVideoStreams$:new W([]),currentVideoStream$:new W(void 0),availableVideoTracks$:new W([]),currentVideoTrack$:new W(void 0),availableAudioStreams$:new W([]),currentAudioStream$:new W(void 0),availableAudioTracks$:new W([]),currentVideoSegmentLength$:new W(0),currentAudioSegmentLength$:new W(0),isAudioAvailable$:new W(!0),autoVideoTrackLimitingAvailable$:new W(!1),autoVideoTrackLimits$:new W(void 0),currentBuffer$:new W(void 0),isBuffering$:new W(!0),error$:new Ce,fetcherError$:new Ce,fetcherRecoverableError$:new Ce,warning$:new Ce,willSeekEvent$:new Ce,soundProhibitedEvent$:new Ce,seekedEvent$:new Ce,loopedEvent$:new Ce,endedEvent$:new Ce,firstBytesEvent$:new Ce,loadedMetadataEvent$:new Ce,firstFrameEvent$:new Ce,canplay$:new Ce,isLive$:new W(void 0),isLiveEnded$:new W(null),isLowLatency$:new W(!1),canChangePlaybackSpeed$:new W(!0),liveTime$:new W(void 0),liveBufferTime$:new W(void 0),liveLatency$:new W(void 0),severeStallOccurred$:new Ce,availableTextTracks$:new W([]),currentTextTrack$:new W(void 0),hostname$:new W(void 0),httpConnectionType$:new W(void 0),httpConnectionReused$:new W(void 0),inPiP$:new W(!1),inFullscreen$:new W(!1),element$:new W(void 0),elementVisible$:new W(!0),availableSources$:new W(void 0),is3DVideo$:new W(!1),playbackState$:new W(""),getCurrentTime$:new W(null)};this.subscription=new dE;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=NI([...qI(this.params.tuning),...UI(this.params.tuning)],this.params.tuning).filter(l=>cE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,xh.default)(r,l)),...t.filter(l=>(0,xh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",pE(a)),this.screenFormatsIterator=new To(a);let n=[...Ap(!0),...Ap(!1)];this.chromecastFormatsIterator=new To(n.filter(l=>cE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Ss.isSupported()&&(this.volumeMultiplierManager=new Ss(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(DO(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:El.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.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"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.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 xo(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ji(u),this.params.tuning.useNewDashProvider?new ho({...o,source:u,sourceHls:l}):new Rn({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ji(u),this.params.tuning.useNewDashProvider?new fo({...o,source:u}):new Ln({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return ji(u),q.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new So({...o,source:u}):new bo({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ji(u),new go({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return ji(u),new vo({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return ji(u),new Ny({...o,source:u,config:{..._O,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return ji(u),new yo({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return xo(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ji(o),new Aa({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return xo(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return xo(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 xo(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,fE.default)((0,hE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new dE,t=!1,i=0;return e.add(VO(this.providerOutput.error$.pipe(lE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),aE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(CO(r=>({id:`ProviderHangup:${r}`,category:El.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(lE(({to:a})=>a==="playing"),OO()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination,n={error:r,currentDestination:a};if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===El.NETWORK,u=r.category===El.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}this.tracer.error("providerError",pE(n))})),e}};import{fromEvent as wl,once as FO,combine as NO,Subscription as mE,ValueSubject as Eh,map as UO,filter as qO,isNonNullable as Pl,now as xt,safeStorage as wh}from"@vkontakte/videoplayer-shared/es2018";var jO=5e3,bE="one_video_throughput",gE="one_video_rtt",Pi=window.navigator.connection,SE=()=>{let s=Pi==null?void 0:Pi.downlink;if(Pl(s)&&s!==10)return s*1e3},vE=()=>{let s=Pi==null?void 0:Pi.rtt;if(Pl(s)&&s!==3e3)return s},yE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Ph=class s{constructor(e){this.subscription=new mE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(bE)||(e.useBrowserEstimation?SE():void 0)||jO,i=(a=(r=s.load(gE))!=null?r:e.useBrowserEstimation?vE():void 0)!=null?a:0;if(this.throughput$=new Eh(t),this.rtt$=new Eh(i),this.rttAdjustedThroughput$=new Eh(yE(t,i,e.rttPenaltyRequestSize)),this.throughput=yi.getSmoothedValue(t,-1,e),this.rtt=yi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=SE();u&&this.throughput.next(u);let l=vE();Pl(l)&&this.rtt.next(l)};Pi&&"onchange"in Pi&&this.subscription.add(wl(Pi,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{wh.set(bE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{wh.set(gE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(NO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(UO(({throughput:n,rtt:o})=>yE(n,o,e.rttPenaltyRequestSize)),qO(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=xt(),r=new mE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(wl(e,"progress").pipe(FO()).subscribe(a=>{t=a.loaded,i=xt()}));break;case 1:case 0:r.add(wl(e,"loadstart").subscribe(()=>{t=0,i=xt()}));break}r.add(wl(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=xt(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=xt(),n=0,o=xt(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(r,xt()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=xt();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=xt()}else n+=c.byteLength;o=xt()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&xt()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,xt()-o,this.concurrentDownloads.size),n=0,o=xt());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=wh.get(e);if(Pl(t))return(i=parseInt(t,10))!=null?i:void 0}},TE=Ph;import{fillWithDefault as HO,VideoQuality as Al}from"@vkontakte/videoplayer-shared/es2018";var IE={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:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Al.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Al.Q_720P,trafficSavingLimit:Al.Q_480P},stallsManager:{stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:0,maxTvtToBeCounted:3*60*60,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Al.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!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,autostartOnlyIfVisible:!1},xE=s=>{var e;return{...HO(s,IE),configName:[...(e=s.configName)!=null?e:[],...IE.configName]}};import{assertNonNullable as kl,combine as Ai,ErrorCategory as Rl,filter as z,filterChanged as te,fromEvent as kh,isNonNullable as AE,isNullable as XO,Logger as JO,map as Z,mapTo as kE,merge as Hi,now as Ll,once as Y,Subject as re,Subscription as RE,tap as Rh,ValueSubject as D,isHigher as ZO,isInvariantQuality as LE,flattenObject as Gi,throttle as Lh,getTraceSubscriptionMethod as ME,Tracer as e_,InternalsExposure as t_}from"@vkontakte/videoplayer-shared/es2018";import{merge as GO,map as zO,filter as EE,isNonNullable as QO}from"@vkontakte/videoplayer-shared/es2018";var Ah=({seekState:s,position$:e})=>GO(s.stateChangeEnded$.pipe(zO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),EE(QO)),e.pipe(EE(()=>s.getState().state==="none")));import{assertNonNullable as WO}from"@vkontakte/videoplayer-shared/es2018";var wE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return WO(e,`Wrong container or containerId {${s.container}}`),e};import{filter as YO,once as KO}from"@vkontakte/videoplayer-shared/es2018";var PE=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(YO(r=>r.length>0),KO()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Ml=class{constructor(e={configName:[]},t=e_.createRootTracer(!1)){this.subscription=new RE;this.logger=new JO;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new D(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new D(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),isLowLatency:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({x:0,y:0})};this.info={playbackState$:new D(void 0),position$:new D(0),duration$:new D(1/0),muted$:new D(!1),volume$:new D(1),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableQualities$:new D([]),availableQualitiesFps$:new D({}),currentQuality$:new D(void 0),isAutoQualityEnabled$:new D(!0),autoQualityLimitingAvailable$:new D(!1),autoQualityLimits$:new D({}),predefinedQualityLimitType$:new D("unknown"),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),isAudioAvailable$:new D(!0),currentPlaybackRate$:new D(1),currentBuffer$:new D({start:0,end:0}),isBuffering$:new D(!0),isStalled$:new D(!1),isEnded$:new D(!1),isLooped$:new D(!1),isLive$:new D(void 0),isLiveEnded$:new D(null),canChangePlaybackSpeed$:new D(void 0),atLiveEdge$:new D(void 0),atLiveDurationEdge$:new D(void 0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),currentFormat$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),throughputEstimation$:new D(void 0),rttEstimation$:new D(void 0),videoBitrate$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),surface$:new D("none"),chromecastState$:new D("NOT_AVAILABLE"),chromecastDeviceName$:new D(void 0),intrinsicVideoSize$:new D(void 0),availableSources$:new D(void 0),is3DVideo$:new D(!1),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0)};this.events={inited$:new re,ready$:new re,started$:new re,playing$:new re,paused$:new re,stopped$:new re,willStart$:new re,willResume$:new re,willPause$:new re,willStop$:new re,willDestruct$:new re,watchCoverageRecord$:new re,watchCoverageLive$:new re,managedError$:new re,fatalError$:new re,fetcherRecoverableError$:new re,ended$:new re,looped$:new re,seeked$:new re,willSeek$:new re,autoplaySoundProhibited$:new re,firstBytes$:new re,loadedMetadata$:new re,firstFrame$:new re,canplay$:new re,log$:new re,fetcherError$:new re,severeStallOccured$:new re};this.experimental={element$:new D(void 0),tuningConfigName$:new D([]),enableDebugTelemetry$:new D(!1),dumpTelemetry:py,getCurrentTime$:new D(null)};if(this.initLogs(),this.tuning=xE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new $o({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new TE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new t_("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,a)=>{let n=Reflect.get(i,r,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let m=typeof f;return(0,$E.default)(["number","string","boolean"],m)?f:f===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Rl.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,d;let{container:n,...o}=e;this.tracer.log("initVideo",Gi(o)),this.domContainer=wE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Eo({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],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,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?q.isInited$.pipe(z(n=>!!n),Y()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),kh(document,"visibilitychange").pipe(Y()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),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.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).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.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).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.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),a=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||a;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),a=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:a,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:a,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{kl(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(z(i=>i.length>0),Y()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Gi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var i;kl(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.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.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Gi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{var t;PE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).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.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(z(t=>!!t),Y()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(z(i=>!!i),Y()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(z(e=>e),Y()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(z(e=>!!e),Y()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(XO(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return AE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Hi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Z(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(Z(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Hd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(z(({from:e})=>e==="stopped"),Y()).subscribe(()=>{this.initedAt=Ll(),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",Gi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Rl.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Y()).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",Gi(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(Z(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(Z(n=>n.destination),te()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Ai({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(Z(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>LE(u)?1:LE(l)?-1:ZO(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(te()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(z(n=>AE(n))).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(te((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(te((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(te()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(te()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(te()).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(Z(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(Rh(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(Ai({hasLiveOffsetByPaused:Hi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(Z(n=>n.to),te(),Z(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(Ai({atLiveEdge:Ai({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ah({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(Z(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),te(),Rh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(Z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Ai({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(Z(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),te(),Rh(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(Z(n=>n.muted),te()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(Z(n=>n.volume),te()).subscribe(this.info.volume$)).add(Ah({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Hi(e.providerOutput.endedEvent$.pipe(kE(!0)),e.providerOutput.seekedEvent$.pipe(kE(!1))).pipe(te()).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(Z(n=>({id:n?`No${n}`:"NoProviders",category:Rl.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(Y(),Z(n=>n!=null?n:Ll()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Y(),Z(()=>Ll()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Y(),Z(()=>Ll()-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 D(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new D(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(z(({to:n})=>n==="playing"),Y()).subscribe(()=>i.next(!1)));let r=0,a=Hi(e.providerOutput.isBuffering$,t,i).pipe(Z(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),te());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Hi(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(Hi(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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(Z(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 RE;this.subscription.add(t),this.subscription.add(e.current$.pipe(te((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(z(i=>i.length>0),Y()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Wt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,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(Hi(this.desiredState.videoTrack.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(Z(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(Z(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(Z(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;kl(this.providerContainer),kl(e),dy(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>cy(i)),this.providerContainer.current$.subscribe(({type:i})=>$a("provider",i)),e.duration$.subscribe(i=>$a("duration",i)),e.availableVideoTracks$.pipe(z(i=>!!i.length),Y()).subscribe(i=>$a("tracks",i)),this.events.fatalError$.subscribe(new et("fatalError")),this.events.managedError$.subscribe(new et("managedError")),e.position$.subscribe(new et("position")),e.currentVideoTrack$.pipe(Z(i=>i==null?void 0:i.quality)).subscribe(new et("quality")),this.info.currentBuffer$.subscribe(new et("buffer")),e.isBuffering$.subscribe(new et("isBuffering"))].forEach(i=>this.subscription.add(i)),$a("codecs",q.video.supportedCodecs)}initTracerSubscription(){let e=ME(this.tracer.log.bind(this.tracer)),t=ME(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(te()).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(Ai({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(z(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),te((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(z(i=>i>0),te()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(z(i=>i>0),te()).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(Ai({currentBuffer:this.info.currentBuffer$.pipe(z(i=>i.end>0),te((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(te())}).pipe(Lh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(te()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(te()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(te()).subscribe(e("canChangePlaybackSpeed"))).add(Ai({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(z(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Lh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(te(),z(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(te(),z(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(te()).subscribe(e("muted"))).add(this.info.volume$.pipe(te()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(te(),z(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Ai({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(z(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Lh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(te(),z(i=>i===!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},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Rl.DOM,message:String(r)})})};this.subscription.add(Hi(kh(document,"visibilitychange"),kh(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Gi({quality:t,availableTracks:Gi(e),track:Gi(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Fa()}};import{Subscription as Uee,Observable as qee,Subject as jee,ValueSubject as Hee,VideoQuality as Gee}from"@vkontakte/videoplayer-shared/es2018";var zee=`@vkontakte/videoplayer-core@${$h}`;export{wo as ChromecastState,Fl as HttpConnectionType,qee as Observable,st as PlaybackState,Ml as Player,Po as PredefinedQualityLimits,zee as SDK_VERSION,jee as Subject,Uee as Subscription,Nl as Surface,$h as VERSION,Hee as ValueSubject,pi as VideoFormat,Gee as VideoQuality,q as clientChecker,La as isMobile};
|