@vkontakte/videoplayer-core 2.0.131-dev.20b944d3.0 → 2.0.131-dev.45e99145.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 +17 -66
- package/es2015.esm.js +17 -66
- package/es2018.cjs.js +17 -66
- package/es2018.esm.js +17 -66
- package/es2024.cjs.js +17 -66
- package/es2024.esm.js +17 -66
- package/esnext.cjs.js +17 -66
- package/esnext.esm.js +17 -66
- package/evergreen.esm.js +15 -64
- package/package.json +2 -2
- package/types/player/Player.d.ts +2 -9
- package/types/player/types.d.ts +0 -5
- package/types/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +1 -5
- package/types/providers/ChromecastProvider/index.d.ts +0 -2
- package/types/providers/DashLiveProvider/DashLiveProvider.d.ts +0 -1
- package/types/providers/DashLiveProvider/utils/FilesFetcher.d.ts +1 -2
- package/types/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +0 -1
- package/types/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +0 -4
- package/types/providers/DashProvider/baseDashProvider.d.ts +2 -2
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -0
- package/types/providers/DashProvider/lib/fetcher.d.ts +4 -5
- package/types/providers/DashProvider/lib/player.d.ts +2 -4
- package/types/providers/DashProvider/lib/sourceBufferBufferedDiff.d.ts +19 -0
- package/types/providers/DashProvider/lib/utils.d.ts +11 -0
- 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/ProviderContainer/index.d.ts +0 -2
- package/types/providers/WebRTCLiveProvider/WebRTCLiveProvider.d.ts +0 -1
- package/types/providers/types.d.ts +1 -4
- package/types/providers/utils/HTMLVideoElement/DroppedFramesManager.d.ts +1 -3
- package/types/providers/utils/StallsManager.d.ts +18 -4
- package/types/utils/autoSelectTrack.d.ts +7 -5
- package/types/utils/qualityLimits.d.ts +3 -18
- package/types/utils/smoothedValue/baseSmoothedValue.d.ts +0 -3
- package/types/utils/tuningConfig.d.ts +28 -7
package/es2015.esm.js
CHANGED
|
@@ -1,73 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.131-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.131-dev.45e99145.0
|
|
3
|
+
* Mon, 05 May 2025 08:19:59 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-131/doc/
|
|
5
5
|
*/
|
|
6
|
-
var iI=Object.create;var ro=Object.defineProperty,rI=Object.defineProperties,aI=Object.getOwnPropertyDescriptor,sI=Object.getOwnPropertyDescriptors,nI=Object.getOwnPropertyNames,hs=Object.getOwnPropertySymbols,oI=Object.getPrototypeOf,ao=Object.prototype.hasOwnProperty,gd=Object.prototype.propertyIsEnumerable;var uI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,bd=(a,e,t)=>e in a?ro(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,w=(a,e)=>{for(var t in e||(e={}))ao.call(e,t)&&bd(a,t,e[t]);if(hs)for(var t of hs(e))gd.call(e,t)&&bd(a,t,e[t]);return a},C=(a,e)=>rI(a,sI(e));var vd=(a,e)=>{var t={};for(var i in a)ao.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&hs)for(var i of hs(a))e.indexOf(i)<0&&gd.call(a,i)&&(t[i]=a[i]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var lI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of nI(e))!ao.call(a,r)&&r!==t&&ro(a,r,{get:()=>e[r],enumerable:!(i=aI(e,r))||i.enumerable});return a};var O=(a,e,t)=>(t=a!=null?iI(oI(a)):{},lI(e||!a||!a.__esModule?ro(t,"default",{value:a,enumerable:!0}):t,a));var E=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),ms=function(a,e){this[0]=a,this[1]=e},ue=(a,e,t)=>{var i=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof ms,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>s[n]=o=>new Promise((u,l)=>i(n,o,u,l)),s={};return t=t.apply(a,e),s[uI("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var ne=f((oo,yd)=>{"use strict";var gr=function(a){return a&&a.Math===Math&&a};yd.exports=gr(typeof globalThis=="object"&&globalThis)||gr(typeof window=="object"&&window)||gr(typeof self=="object"&&self)||gr(typeof global=="object"&&global)||gr(typeof oo=="object"&&oo)||function(){return this}()||Function("return this")()});var fe=f((_0,Td)=>{"use strict";Td.exports=function(a){try{return!!a()}catch(e){return!0}}});var vr=f((N0,Id)=>{"use strict";var cI=fe();Id.exports=!cI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var uo=f((F0,wd)=>{"use strict";var dI=vr(),Pd=Function.prototype,Ed=Pd.apply,xd=Pd.call;wd.exports=typeof Reflect=="object"&&Reflect.apply||(dI?xd.bind(Ed):function(){return xd.apply(Ed,arguments)})});var ce=f((q0,Rd)=>{"use strict";var Ad=vr(),kd=Function.prototype,lo=kd.call,pI=Ad&&kd.bind.bind(lo,lo);Rd.exports=Ad?pI:function(a){return function(){return lo.apply(a,arguments)}}});var ii=f((U0,Ld)=>{"use strict";var $d=ce(),hI=$d({}.toString),mI=$d("".slice);Ld.exports=function(a){return mI(hI(a),8,-1)}});var co=f((H0,Md)=>{"use strict";var fI=ii(),bI=ce();Md.exports=function(a){if(fI(a)==="Function")return bI(a)}});var ae=f((j0,Cd)=>{"use strict";var po=typeof document=="object"&&document.all;Cd.exports=typeof po=="undefined"&&po!==void 0?function(a){return typeof a=="function"||a===po}:function(a){return typeof a=="function"}});var Ve=f((Q0,Dd)=>{"use strict";var gI=fe();Dd.exports=!gI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Oe=f((G0,Vd)=>{"use strict";var vI=vr(),gs=Function.prototype.call;Vd.exports=vI?gs.bind(gs):function(){return gs.apply(gs,arguments)}});var ho=f(_d=>{"use strict";var Od={}.propertyIsEnumerable,Bd=Object.getOwnPropertyDescriptor,SI=Bd&&!Od.call({1:2},1);_d.f=SI?function(e){var t=Bd(this,e);return!!t&&t.enumerable}:Od});var Sr=f((Y0,Nd)=>{"use strict";Nd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var qd=f((z0,Fd)=>{"use strict";var yI=ce(),TI=fe(),II=ii(),mo=Object,EI=yI("".split);Fd.exports=TI(function(){return!mo("z").propertyIsEnumerable(0)})?function(a){return II(a)==="String"?EI(a,""):mo(a)}:mo});var Ri=f((K0,Ud)=>{"use strict";Ud.exports=function(a){return a==null}});var Mt=f((X0,Hd)=>{"use strict";var xI=Ri(),PI=TypeError;Hd.exports=function(a){if(xI(a))throw new PI("Can't call method on "+a);return a}});var ri=f((J0,jd)=>{"use strict";var wI=qd(),AI=Mt();jd.exports=function(a){return wI(AI(a))}});var Be=f((Z0,Qd)=>{"use strict";var kI=ae();Qd.exports=function(a){return typeof a=="object"?a!==null:kI(a)}});var $i=f((eV,Gd)=>{"use strict";Gd.exports={}});var ft=f((tV,Yd)=>{"use strict";var fo=$i(),bo=ne(),RI=ae(),Wd=function(a){return RI(a)?a:void 0};Yd.exports=function(a,e){return arguments.length<2?Wd(fo[a])||Wd(bo[a]):fo[a]&&fo[a][e]||bo[a]&&bo[a][e]}});var yr=f((iV,zd)=>{"use strict";var $I=ce();zd.exports=$I({}.isPrototypeOf)});var ai=f((rV,Jd)=>{"use strict";var LI=ne(),Kd=LI.navigator,Xd=Kd&&Kd.userAgent;Jd.exports=Xd?String(Xd):""});var vo=f((aV,ap)=>{"use strict";var rp=ne(),go=ai(),Zd=rp.process,ep=rp.Deno,tp=Zd&&Zd.versions||ep&&ep.version,ip=tp&&tp.v8,Ye,vs;ip&&(Ye=ip.split("."),vs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!vs&&go&&(Ye=go.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=go.match(/Chrome\/(\d+)/),Ye&&(vs=+Ye[1])));ap.exports=vs});var So=f((sV,np)=>{"use strict";var sp=vo(),MI=fe(),CI=ne(),DI=CI.String;np.exports=!!Object.getOwnPropertySymbols&&!MI(function(){var a=Symbol("symbol detection");return!DI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&sp&&sp<41})});var yo=f((nV,op)=>{"use strict";var VI=So();op.exports=VI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var To=f((oV,up)=>{"use strict";var OI=ft(),BI=ae(),_I=yr(),NI=yo(),FI=Object;up.exports=NI?function(a){return typeof a=="symbol"}:function(a){var e=OI("Symbol");return BI(e)&&_I(e.prototype,FI(a))}});var Tr=f((uV,lp)=>{"use strict";var qI=String;lp.exports=function(a){try{return qI(a)}catch(e){return"Object"}}});var st=f((lV,cp)=>{"use strict";var UI=ae(),HI=Tr(),jI=TypeError;cp.exports=function(a){if(UI(a))return a;throw new jI(HI(a)+" is not a function")}});var Ir=f((cV,dp)=>{"use strict";var QI=st(),GI=Ri();dp.exports=function(a,e){var t=a[e];return GI(t)?void 0:QI(t)}});var hp=f((dV,pp)=>{"use strict";var Io=Oe(),Eo=ae(),xo=Be(),WI=TypeError;pp.exports=function(a,e){var t,i;if(e==="string"&&Eo(t=a.toString)&&!xo(i=Io(t,a))||Eo(t=a.valueOf)&&!xo(i=Io(t,a))||e!=="string"&&Eo(t=a.toString)&&!xo(i=Io(t,a)))return i;throw new WI("Can't convert object to primitive value")}});var ze=f((pV,mp)=>{"use strict";mp.exports=!0});var gp=f((hV,bp)=>{"use strict";var fp=ne(),YI=Object.defineProperty;bp.exports=function(a,e){try{YI(fp,a,{value:e,configurable:!0,writable:!0})}catch(t){fp[a]=e}return e}});var Er=f((mV,yp)=>{"use strict";var zI=ze(),KI=ne(),XI=gp(),vp="__core-js_shared__",Sp=yp.exports=KI[vp]||XI(vp,{});(Sp.versions||(Sp.versions=[])).push({version:"3.38.0",mode:zI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Po=f((fV,Ip)=>{"use strict";var Tp=Er();Ip.exports=function(a,e){return Tp[a]||(Tp[a]=e||{})}});var Li=f((bV,Ep)=>{"use strict";var JI=Mt(),ZI=Object;Ep.exports=function(a){return ZI(JI(a))}});var Ke=f((gV,xp)=>{"use strict";var eE=ce(),tE=Li(),iE=eE({}.hasOwnProperty);xp.exports=Object.hasOwn||function(e,t){return iE(tE(e),t)}});var wo=f((vV,Pp)=>{"use strict";var rE=ce(),aE=0,sE=Math.random(),nE=rE(1 .toString);Pp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+nE(++aE+sE,36)}});var be=f((SV,Ap)=>{"use strict";var oE=ne(),uE=Po(),wp=Ke(),lE=wo(),cE=So(),dE=yo(),Mi=oE.Symbol,Ao=uE("wks"),pE=dE?Mi.for||Mi:Mi&&Mi.withoutSetter||lE;Ap.exports=function(a){return wp(Ao,a)||(Ao[a]=cE&&wp(Mi,a)?Mi[a]:pE("Symbol."+a)),Ao[a]}});var Lp=f((yV,$p)=>{"use strict";var hE=Oe(),kp=Be(),Rp=To(),mE=Ir(),fE=hp(),bE=be(),gE=TypeError,vE=bE("toPrimitive");$p.exports=function(a,e){if(!kp(a)||Rp(a))return a;var t=mE(a,vE),i;if(t){if(e===void 0&&(e="default"),i=hE(t,a,e),!kp(i)||Rp(i))return i;throw new gE("Can't convert object to primitive value")}return e===void 0&&(e="number"),fE(a,e)}});var ko=f((TV,Mp)=>{"use strict";var SE=Lp(),yE=To();Mp.exports=function(a){var e=SE(a,"string");return yE(e)?e:e+""}});var Ss=f((IV,Dp)=>{"use strict";var TE=ne(),Cp=Be(),Ro=TE.document,IE=Cp(Ro)&&Cp(Ro.createElement);Dp.exports=function(a){return IE?Ro.createElement(a):{}}});var $o=f((EV,Vp)=>{"use strict";var EE=Ve(),xE=fe(),PE=Ss();Vp.exports=!EE&&!xE(function(){return Object.defineProperty(PE("div"),"a",{get:function(){return 7}}).a!==7})});var _p=f(Bp=>{"use strict";var wE=Ve(),AE=Oe(),kE=ho(),RE=Sr(),$E=ri(),LE=ko(),ME=Ke(),CE=$o(),Op=Object.getOwnPropertyDescriptor;Bp.f=wE?Op:function(e,t){if(e=$E(e),t=LE(t),CE)try{return Op(e,t)}catch(i){}if(ME(e,t))return RE(!AE(kE.f,e,t),e[t])}});var Lo=f((PV,Np)=>{"use strict";var DE=fe(),VE=ae(),OE=/#|\.prototype\./,xr=function(a,e){var t=_E[BE(a)];return t===FE?!0:t===NE?!1:VE(e)?DE(e):!!e},BE=xr.normalize=function(a){return String(a).replace(OE,".").toLowerCase()},_E=xr.data={},NE=xr.NATIVE="N",FE=xr.POLYFILL="P";Np.exports=xr});var Ci=f((wV,qp)=>{"use strict";var Fp=co(),qE=st(),UE=vr(),HE=Fp(Fp.bind);qp.exports=function(a,e){return qE(a),e===void 0?a:UE?HE(a,e):function(){return a.apply(e,arguments)}}});var Mo=f((AV,Up)=>{"use strict";var jE=Ve(),QE=fe();Up.exports=jE&&QE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=f((kV,Hp)=>{"use strict";var GE=Be(),WE=String,YE=TypeError;Hp.exports=function(a){if(GE(a))return a;throw new YE(WE(a)+" is not an object")}});var si=f(Qp=>{"use strict";var zE=Ve(),KE=$o(),XE=Mo(),ys=nt(),jp=ko(),JE=TypeError,Co=Object.defineProperty,ZE=Object.getOwnPropertyDescriptor,Do="enumerable",Vo="configurable",Oo="writable";Qp.f=zE?XE?function(e,t,i){if(ys(e),t=jp(t),ys(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Oo in i&&!i[Oo]){var r=ZE(e,t);r&&r[Oo]&&(e[t]=i.value,i={configurable:Vo in i?i[Vo]:r[Vo],enumerable:Do in i?i[Do]:r[Do],writable:!1})}return Co(e,t,i)}:Co:function(e,t,i){if(ys(e),t=jp(t),ys(i),KE)try{return Co(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new JE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Di=f(($V,Gp)=>{"use strict";var ex=Ve(),tx=si(),ix=Sr();Gp.exports=ex?function(a,e,t){return tx.f(a,e,ix(1,t))}:function(a,e,t){return a[e]=t,a}});var le=f((LV,Yp)=>{"use strict";var Pr=ne(),rx=uo(),ax=co(),sx=ae(),nx=_p().f,ox=Lo(),Vi=$i(),ux=Ci(),Oi=Di(),Wp=Ke();Er();var lx=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 rx(a,this,arguments)};return e.prototype=a.prototype,e};Yp.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Pr:r?Pr[t]:Pr[t]&&Pr[t].prototype,o=i?Vi:Vi[t]||Oi(Vi,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,v;for(h in e)l=ox(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Wp(n,h),m=o[h],c&&(a.dontCallGetSet?(v=nx(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=ux(p,Pr):a.wrap&&c?g=lx(p):s&&sx(p)?g=ax(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&Oi(g,"sham",!0),Oi(o,h,g),s&&(d=t+"Prototype",Wp(Vi,d)||Oi(Vi,d,{}),Oi(Vi[d],h,p),a.real&&u&&(l||!u[h])&&Oi(u,h,p)))}});var Kp=f((MV,zp)=>{"use strict";var cx=Math.ceil,dx=Math.floor;zp.exports=Math.trunc||function(e){var t=+e;return(t>0?dx:cx)(t)}});var wr=f((CV,Xp)=>{"use strict";var px=Kp();Xp.exports=function(a){var e=+a;return e!==e||e===0?0:px(e)}});var Zp=f((DV,Jp)=>{"use strict";var hx=wr(),mx=Math.max,fx=Math.min;Jp.exports=function(a,e){var t=hx(a);return t<0?mx(t+e,0):fx(t,e)}});var Bo=f((VV,eh)=>{"use strict";var bx=wr(),gx=Math.min;eh.exports=function(a){var e=bx(a);return e>0?gx(e,9007199254740991):0}});var Bi=f((OV,th)=>{"use strict";var vx=Bo();th.exports=function(a){return vx(a.length)}});var _o=f((BV,rh)=>{"use strict";var Sx=ri(),yx=Zp(),Tx=Bi(),ih=function(a){return function(e,t,i){var r=Sx(e),s=Tx(r);if(s===0)return!a&&-1;var n=yx(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}};rh.exports={includes:ih(!0),indexOf:ih(!1)}});var Ar=f((_V,ah)=>{"use strict";ah.exports=function(){}});var sh=f(()=>{"use strict";var Ix=le(),Ex=_o().includes,xx=fe(),Px=Ar(),wx=xx(function(){return!Array(1).includes()});Ix({target:"Array",proto:!0,forced:wx},{includes:function(e){return Ex(this,e,arguments.length>1?arguments[1]:void 0)}});Px("includes")});var Ct=f((qV,nh)=>{"use strict";var Ax=ft();nh.exports=Ax});var uh=f((UV,oh)=>{"use strict";sh();var kx=Ct();oh.exports=kx("Array","includes")});var ch=f((HV,lh)=>{"use strict";var Rx=uh();lh.exports=Rx});var qe=f((jV,dh)=>{"use strict";var $x=ch();dh.exports=$x});var Es=f((iO,Sh)=>{"use strict";var _x=Po(),Nx=wo(),vh=_x("keys");Sh.exports=function(a){return vh[a]||(vh[a]=Nx(a))}});var Th=f((rO,yh)=>{"use strict";var Fx=fe();yh.exports=!Fx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var xs=f((aO,Eh)=>{"use strict";var qx=Ke(),Ux=ae(),Hx=Li(),jx=Es(),Qx=Th(),Ih=jx("IE_PROTO"),qo=Object,Gx=qo.prototype;Eh.exports=Qx?qo.getPrototypeOf:function(a){var e=Hx(a);if(qx(e,Ih))return e[Ih];var t=e.constructor;return Ux(t)&&e instanceof t?t.prototype:e instanceof qo?Gx:null}});var Ps=f((sO,xh)=>{"use strict";xh.exports={}});var Ah=f((nO,wh)=>{"use strict";var Wx=ce(),Uo=Ke(),Yx=ri(),zx=_o().indexOf,Kx=Ps(),Ph=Wx([].push);wh.exports=function(a,e){var t=Yx(a),i=0,r=[],s;for(s in t)!Uo(Kx,s)&&Uo(t,s)&&Ph(r,s);for(;e.length>i;)Uo(t,s=e[i++])&&(~zx(r,s)||Ph(r,s));return r}});var Ho=f((oO,kh)=>{"use strict";kh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var jo=f((uO,Rh)=>{"use strict";var Xx=Ah(),Jx=Ho();Rh.exports=Object.keys||function(e){return Xx(e,Jx)}});var Qo=f((lO,Dh)=>{"use strict";var Lh=Ve(),Zx=fe(),Mh=ce(),eP=xs(),tP=jo(),iP=ri(),rP=ho().f,Ch=Mh(rP),aP=Mh([].push),sP=Lh&&Zx(function(){var a=Object.create(null);return a[2]=2,!Ch(a,2)}),$h=function(a){return function(e){for(var t=iP(e),i=tP(t),r=sP&&eP(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Lh||(r?u in t:Ch(t,u)))&&aP(o,a?[u,t[u]]:t[u]);return o}};Dh.exports={entries:$h(!0),values:$h(!1)}});var Vh=f(()=>{"use strict";var nP=le(),oP=Qo().entries;nP({target:"Object",stat:!0},{entries:function(e){return oP(e)}})});var Bh=f((pO,Oh)=>{"use strict";Vh();var uP=$i();Oh.exports=uP.Object.entries});var Nh=f((hO,_h)=>{"use strict";var lP=Bh();_h.exports=lP});var _i=f((mO,Fh)=>{"use strict";var cP=Nh();Fh.exports=cP});var ni=f((fO,qh)=>{"use strict";qh.exports={}});var jh=f((bO,Hh)=>{"use strict";var dP=ne(),pP=ae(),Uh=dP.WeakMap;Hh.exports=pP(Uh)&&/native code/.test(String(Uh))});var zo=f((gO,Wh)=>{"use strict";var hP=jh(),Gh=ne(),mP=Be(),fP=Di(),Go=Ke(),Wo=Er(),bP=Es(),gP=Ps(),Qh="Object already initialized",Yo=Gh.TypeError,vP=Gh.WeakMap,ws,kr,As,SP=function(a){return As(a)?kr(a):ws(a,{})},yP=function(a){return function(e){var t;if(!mP(e)||(t=kr(e)).type!==a)throw new Yo("Incompatible receiver, "+a+" required");return t}};hP||Wo.state?(Xe=Wo.state||(Wo.state=new vP),Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,ws=function(a,e){if(Xe.has(a))throw new Yo(Qh);return e.facade=a,Xe.set(a,e),e},kr=function(a){return Xe.get(a)||{}},As=function(a){return Xe.has(a)}):(oi=bP("state"),gP[oi]=!0,ws=function(a,e){if(Go(a,oi))throw new Yo(Qh);return e.facade=a,fP(a,oi,e),e},kr=function(a){return Go(a,oi)?a[oi]:{}},As=function(a){return Go(a,oi)});var Xe,oi;Wh.exports={set:ws,get:kr,has:As,enforce:SP,getterFor:yP}});var Jo=f((vO,zh)=>{"use strict";var Ko=Ve(),TP=Ke(),Yh=Function.prototype,IP=Ko&&Object.getOwnPropertyDescriptor,Xo=TP(Yh,"name"),EP=Xo&&function(){}.name==="something",xP=Xo&&(!Ko||Ko&&IP(Yh,"name").configurable);zh.exports={EXISTS:Xo,PROPER:EP,CONFIGURABLE:xP}});var Xh=f(Kh=>{"use strict";var PP=Ve(),wP=Mo(),AP=si(),kP=nt(),RP=ri(),$P=jo();Kh.f=PP&&!wP?Object.defineProperties:function(e,t){kP(e);for(var i=RP(t),r=$P(t),s=r.length,n=0,o;s>n;)AP.f(e,o=r[n++],i[o]);return e}});var Zo=f((yO,Jh)=>{"use strict";var LP=ft();Jh.exports=LP("document","documentElement")});var ru=f((TO,sm)=>{"use strict";var MP=nt(),CP=Xh(),Zh=Ho(),DP=Ps(),VP=Zo(),OP=Ss(),BP=Es(),em=">",tm="<",tu="prototype",iu="script",rm=BP("IE_PROTO"),eu=function(){},am=function(a){return tm+iu+em+a+tm+"/"+iu+em},im=function(a){a.write(am("")),a.close();var e=a.parentWindow.Object;return a=null,e},_P=function(){var a=OP("iframe"),e="java"+iu+":",t;return a.style.display="none",VP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(am("document.F=Object")),t.close(),t.F},ks,Rs=function(){try{ks=new ActiveXObject("htmlfile")}catch(e){}Rs=typeof document!="undefined"?document.domain&&ks?im(ks):_P():im(ks);for(var a=Zh.length;a--;)delete Rs[tu][Zh[a]];return Rs()};DP[rm]=!0;sm.exports=Object.create||function(e,t){var i;return e!==null?(eu[tu]=MP(e),i=new eu,eu[tu]=null,i[rm]=e):i=Rs(),t===void 0?i:CP.f(i,t)}});var Ni=f((IO,nm)=>{"use strict";var NP=Di();nm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:NP(a,e,t),a}});var ou=f((EO,lm)=>{"use strict";var FP=fe(),qP=ae(),UP=Be(),HP=ru(),om=xs(),jP=Ni(),QP=be(),GP=ze(),nu=QP("iterator"),um=!1,bt,au,su;[].keys&&(su=[].keys(),"next"in su?(au=om(om(su)),au!==Object.prototype&&(bt=au)):um=!0);var WP=!UP(bt)||FP(function(){var a={};return bt[nu].call(a)!==a});WP?bt={}:GP&&(bt=HP(bt));qP(bt[nu])||jP(bt,nu,function(){return this});lm.exports={IteratorPrototype:bt,BUGGY_SAFARI_ITERATORS:um}});var $s=f((xO,dm)=>{"use strict";var YP=be(),zP=YP("toStringTag"),cm={};cm[zP]="z";dm.exports=String(cm)==="[object z]"});var Rr=f((PO,pm)=>{"use strict";var KP=$s(),XP=ae(),Ls=ii(),JP=be(),ZP=JP("toStringTag"),ew=Object,tw=Ls(function(){return arguments}())==="Arguments",iw=function(a,e){try{return a[e]}catch(t){}};pm.exports=KP?Ls:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=iw(e=ew(a),ZP))=="string"?t:tw?Ls(e):(i=Ls(e))==="Object"&&XP(e.callee)?"Arguments":i}});var mm=f((wO,hm)=>{"use strict";var rw=$s(),aw=Rr();hm.exports=rw?{}.toString:function(){return"[object "+aw(this)+"]"}});var $r=f((AO,bm)=>{"use strict";var sw=$s(),nw=si().f,ow=Di(),uw=Ke(),lw=mm(),cw=be(),fm=cw("toStringTag");bm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(uw(r,fm)||nw(r,fm,{configurable:!0,value:e}),i&&!sw&&ow(r,"toString",lw))}});var vm=f((kO,gm)=>{"use strict";var dw=ou().IteratorPrototype,pw=ru(),hw=Sr(),mw=$r(),fw=ni(),bw=function(){return this};gm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=pw(dw,{next:hw(+!i,t)}),mw(a,r,!1,!0),fw[r]=bw,a}});var ym=f((RO,Sm)=>{"use strict";var gw=ce(),vw=st();Sm.exports=function(a,e,t){try{return gw(vw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Im=f(($O,Tm)=>{"use strict";var Sw=Be();Tm.exports=function(a){return Sw(a)||a===null}});var xm=f((LO,Em)=>{"use strict";var yw=Im(),Tw=String,Iw=TypeError;Em.exports=function(a){if(yw(a))return a;throw new Iw("Can't set "+Tw(a)+" as a prototype")}});var uu=f((MO,Pm)=>{"use strict";var Ew=ym(),xw=Be(),Pw=Mt(),ww=xm();Pm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Ew(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return Pw(r),ww(s),xw(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Om=f((CO,Vm)=>{"use strict";var Aw=le(),kw=Oe(),Ms=ze(),Cm=Jo(),Rw=ae(),$w=vm(),wm=xs(),Am=uu(),Lw=$r(),Mw=Di(),lu=Ni(),Cw=be(),km=ni(),Dm=ou(),Dw=Cm.PROPER,Vw=Cm.CONFIGURABLE,Rm=Dm.IteratorPrototype,Cs=Dm.BUGGY_SAFARI_ITERATORS,Lr=Cw("iterator"),$m="keys",Mr="values",Lm="entries",Mm=function(){return this};Vm.exports=function(a,e,t,i,r,s,n){$w(t,e,i);var o=function(v){if(v===r&&h)return h;if(!Cs&&v&&v in c)return c[v];switch(v){case $m:return function(){return new t(this,v)};case Mr:return function(){return new t(this,v)};case Lm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Lr]||c["@@iterator"]||r&&c[r],h=!Cs&&d||o(r),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=wm(p.call(new a)),m!==Object.prototype&&m.next&&(!Ms&&wm(m)!==Rm&&(Am?Am(m,Rm):Rw(m[Lr])||lu(m,Lr,Mm)),Lw(m,u,!0,!0),Ms&&(km[u]=Mm))),Dw&&r===Mr&&d&&d.name!==Mr&&(!Ms&&Vw?Mw(c,"name",Mr):(l=!0,h=function(){return kw(d,this)})),r)if(b={values:o(Mr),keys:s?h:o($m),entries:o(Lm)},n)for(g in b)(Cs||l||!(g in c))&&lu(c,g,b[g]);else Aw({target:e,proto:!0,forced:Cs||l},b);return(!Ms||n)&&c[Lr]!==h&&lu(c,Lr,h,{name:r}),km[e]=h,b}});var _m=f((DO,Bm)=>{"use strict";Bm.exports=function(a,e){return{value:a,done:e}}});var du=f((VO,Hm)=>{"use strict";var Ow=ri(),cu=Ar(),Nm=ni(),qm=zo(),Bw=si().f,_w=Om(),Ds=_m(),Nw=ze(),Fw=Ve(),Um="Array Iterator",qw=qm.set,Uw=qm.getterFor(Um);Hm.exports=_w(Array,"Array",function(a,e){qw(this,{type:Um,target:Ow(a),index:0,kind:e})},function(){var a=Uw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ds(void 0,!0);switch(a.kind){case"keys":return Ds(t,!1);case"values":return Ds(e[t],!1)}return Ds([t,e[t]],!1)},"values");var Fm=Nm.Arguments=Nm.Array;cu("keys");cu("values");cu("entries");if(!Nw&&Fw&&Fm.name!=="values")try{Bw(Fm,"name",{value:"values"})}catch(a){}});var Qm=f((OO,jm)=>{"use strict";var Hw=be(),jw=ni(),Qw=Hw("iterator"),Gw=Array.prototype;jm.exports=function(a){return a!==void 0&&(jw.Array===a||Gw[Qw]===a)}});var pu=f((BO,Wm)=>{"use strict";var Ww=Rr(),Gm=Ir(),Yw=Ri(),zw=ni(),Kw=be(),Xw=Kw("iterator");Wm.exports=function(a){if(!Yw(a))return Gm(a,Xw)||Gm(a,"@@iterator")||zw[Ww(a)]}});var zm=f((_O,Ym)=>{"use strict";var Jw=Oe(),Zw=st(),eA=nt(),tA=Tr(),iA=pu(),rA=TypeError;Ym.exports=function(a,e){var t=arguments.length<2?iA(a):e;if(Zw(t))return eA(Jw(t,a));throw new rA(tA(a)+" is not iterable")}});var Jm=f((NO,Xm)=>{"use strict";var aA=Oe(),Km=nt(),sA=Ir();Xm.exports=function(a,e,t){var i,r;Km(a);try{if(i=sA(a,"return"),!i){if(e==="throw")throw t;return t}i=aA(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Km(i),t}});var Os=f((FO,rf)=>{"use strict";var nA=Ci(),oA=Oe(),uA=nt(),lA=Tr(),cA=Qm(),dA=Bi(),Zm=yr(),pA=zm(),hA=pu(),ef=Jm(),mA=TypeError,Vs=function(a,e){this.stopped=a,this.result=e},tf=Vs.prototype;rf.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=nA(e,i),l,c,d,h,p,m,b,g=function(S){return l&&ef(l,"normal",S),new Vs(!0,S)},v=function(S){return r?(uA(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=hA(a),!c)throw new mA(lA(a)+" is not iterable");if(cA(c)){for(d=0,h=dA(a);h>d;d++)if(p=v(a[d]),p&&Zm(tf,p))return p;return new Vs(!1)}l=pA(a,c)}for(m=s?a.next:l.next;!(b=oA(m,l)).done;){try{p=v(b.value)}catch(S){ef(l,"throw",S)}if(typeof p=="object"&&p&&Zm(tf,p))return p}return new Vs(!1)}});var sf=f((qO,af)=>{"use strict";var fA=Ve(),bA=si(),gA=Sr();af.exports=function(a,e,t){fA?bA.f(a,e,gA(0,t)):a[e]=t}});var nf=f(()=>{"use strict";var vA=le(),SA=Os(),yA=sf();vA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return SA(e,function(i,r){yA(t,i,r)},{AS_ENTRIES:!0}),t}})});var uf=f((jO,of)=>{"use strict";du();nf();var TA=$i();of.exports=TA.Object.fromEntries});var cf=f((QO,lf)=>{"use strict";lf.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 pf=f(()=>{"use strict";du();var IA=cf(),EA=ne(),xA=$r(),df=ni();for(Bs in IA)xA(EA[Bs],Bs),df[Bs]=df.Array;var Bs});var mf=f((YO,hf)=>{"use strict";var PA=uf();pf();hf.exports=PA});var hu=f((zO,ff)=>{"use strict";var wA=mf();ff.exports=wA});var bf=f(()=>{"use strict"});var mu=f((JO,gf)=>{"use strict";var Cr=ne(),AA=ai(),kA=ii(),_s=function(a){return AA.slice(0,a.length)===a};gf.exports=function(){return _s("Bun/")?"BUN":_s("Cloudflare-Workers")?"CLOUDFLARE":_s("Deno/")?"DENO":_s("Node.js/")?"NODE":Cr.Bun&&typeof Bun.version=="string"?"BUN":Cr.Deno&&typeof Deno.version=="object"?"DENO":kA(Cr.process)==="process"?"NODE":Cr.window&&Cr.document?"BROWSER":"REST"}()});var Ns=f((ZO,vf)=>{"use strict";var RA=mu();vf.exports=RA==="NODE"});var yf=f((eB,Sf)=>{"use strict";var $A=si();Sf.exports=function(a,e,t){return $A.f(a,e,t)}});var Ef=f((tB,If)=>{"use strict";var LA=ft(),MA=yf(),CA=be(),DA=Ve(),Tf=CA("species");If.exports=function(a){var e=LA(a);DA&&e&&!e[Tf]&&MA(e,Tf,{configurable:!0,get:function(){return this}})}});var Pf=f((iB,xf)=>{"use strict";var VA=yr(),OA=TypeError;xf.exports=function(a,e){if(VA(e,a))return a;throw new OA("Incorrect invocation")}});var bu=f((rB,wf)=>{"use strict";var BA=ce(),_A=ae(),fu=Er(),NA=BA(Function.toString);_A(fu.inspectSource)||(fu.inspectSource=function(a){return NA(a)});wf.exports=fu.inspectSource});var vu=f((aB,Lf)=>{"use strict";var FA=ce(),qA=fe(),Af=ae(),UA=Rr(),HA=ft(),jA=bu(),kf=function(){},Rf=HA("Reflect","construct"),gu=/^\s*(?:class|function)\b/,QA=FA(gu.exec),GA=!gu.test(kf),Dr=function(e){if(!Af(e))return!1;try{return Rf(kf,[],e),!0}catch(t){return!1}},$f=function(e){if(!Af(e))return!1;switch(UA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return GA||!!QA(gu,jA(e))}catch(t){return!0}};$f.sham=!0;Lf.exports=!Rf||qA(function(){var a;return Dr(Dr.call)||!Dr(Object)||!Dr(function(){a=!0})||a})?$f:Dr});var Cf=f((sB,Mf)=>{"use strict";var WA=vu(),YA=Tr(),zA=TypeError;Mf.exports=function(a){if(WA(a))return a;throw new zA(YA(a)+" is not a constructor")}});var Su=f((nB,Vf)=>{"use strict";var Df=nt(),KA=Cf(),XA=Ri(),JA=be(),ZA=JA("species");Vf.exports=function(a,e){var t=Df(a).constructor,i;return t===void 0||XA(i=Df(t)[ZA])?e:KA(i)}});var Bf=f((oB,Of)=>{"use strict";var ek=ce();Of.exports=ek([].slice)});var Nf=f((uB,_f)=>{"use strict";var tk=TypeError;_f.exports=function(a,e){if(a<e)throw new tk("Not enough arguments");return a}});var yu=f((lB,Ff)=>{"use strict";var ik=ai();Ff.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ik)});var Ru=f((cB,zf)=>{"use strict";var _e=ne(),rk=uo(),ak=Ci(),qf=ae(),sk=Ke(),Yf=fe(),Uf=Zo(),nk=Bf(),Hf=Ss(),ok=Nf(),uk=yu(),lk=Ns(),wu=_e.setImmediate,Au=_e.clearImmediate,ck=_e.process,Tu=_e.Dispatch,dk=_e.Function,jf=_e.MessageChannel,pk=_e.String,Iu=0,Vr={},Qf="onreadystatechange",Or,ui,Eu,xu;Yf(function(){Or=_e.location});var ku=function(a){if(sk(Vr,a)){var e=Vr[a];delete Vr[a],e()}},Pu=function(a){return function(){ku(a)}},Gf=function(a){ku(a.data)},Wf=function(a){_e.postMessage(pk(a),Or.protocol+"//"+Or.host)};(!wu||!Au)&&(wu=function(e){ok(arguments.length,1);var t=qf(e)?e:dk(e),i=nk(arguments,1);return Vr[++Iu]=function(){rk(t,void 0,i)},ui(Iu),Iu},Au=function(e){delete Vr[e]},lk?ui=function(a){ck.nextTick(Pu(a))}:Tu&&Tu.now?ui=function(a){Tu.now(Pu(a))}:jf&&!uk?(Eu=new jf,xu=Eu.port2,Eu.port1.onmessage=Gf,ui=ak(xu.postMessage,xu)):_e.addEventListener&&qf(_e.postMessage)&&!_e.importScripts&&Or&&Or.protocol!=="file:"&&!Yf(Wf)?(ui=Wf,_e.addEventListener("message",Gf,!1)):Qf in Hf("script")?ui=function(a){Uf.appendChild(Hf("script"))[Qf]=function(){Uf.removeChild(this),ku(a)}}:ui=function(a){setTimeout(Pu(a),0)});zf.exports={set:wu,clear:Au}});var Jf=f((dB,Xf)=>{"use strict";var Kf=ne(),hk=Ve(),mk=Object.getOwnPropertyDescriptor;Xf.exports=function(a){if(!hk)return Kf[a];var e=mk(Kf,a);return e&&e.value}});var $u=f((pB,eb)=>{"use strict";var Zf=function(){this.head=null,this.tail=null};Zf.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}}};eb.exports=Zf});var ib=f((hB,tb)=>{"use strict";var fk=ai();tb.exports=/ipad|iphone|ipod/i.test(fk)&&typeof Pebble!="undefined"});var ab=f((mB,rb)=>{"use strict";var bk=ai();rb.exports=/web0s(?!.*chrome)/i.test(bk)});var db=f((fB,cb)=>{"use strict";var qi=ne(),gk=Jf(),sb=Ci(),Lu=Ru().set,vk=$u(),Sk=yu(),yk=ib(),Tk=ab(),Mu=Ns(),nb=qi.MutationObserver||qi.WebKitMutationObserver,ob=qi.document,ub=qi.process,Fs=qi.Promise,Vu=gk("queueMicrotask"),Fi,Cu,Du,qs,lb;Vu||(Br=new vk,_r=function(){var a,e;for(Mu&&(a=ub.domain)&&a.exit();e=Br.get();)try{e()}catch(t){throw Br.head&&Fi(),t}a&&a.enter()},!Sk&&!Mu&&!Tk&&nb&&ob?(Cu=!0,Du=ob.createTextNode(""),new nb(_r).observe(Du,{characterData:!0}),Fi=function(){Du.data=Cu=!Cu}):!yk&&Fs&&Fs.resolve?(qs=Fs.resolve(void 0),qs.constructor=Fs,lb=sb(qs.then,qs),Fi=function(){lb(_r)}):Mu?Fi=function(){ub.nextTick(_r)}:(Lu=sb(Lu,qi),Fi=function(){Lu(_r)}),Vu=function(a){Br.head||Fi(),Br.add(a)});var Br,_r;cb.exports=Vu});var hb=f((bB,pb)=>{"use strict";pb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Us=f((gB,mb)=>{"use strict";mb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var li=f((vB,fb)=>{"use strict";var Ik=ne();fb.exports=Ik.Promise});var Ui=f((SB,Sb)=>{"use strict";var Ek=ne(),Nr=li(),xk=ae(),Pk=Lo(),wk=bu(),Ak=be(),bb=mu(),kk=ze(),Ou=vo(),gb=Nr&&Nr.prototype,Rk=Ak("species"),Bu=!1,vb=xk(Ek.PromiseRejectionEvent),$k=Pk("Promise",function(){var a=wk(Nr),e=a!==String(Nr);if(!e&&Ou===66||kk&&!(gb.catch&&gb.finally))return!0;if(!Ou||Ou<51||!/native code/.test(a)){var t=new Nr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[Rk]=i,Bu=t.then(function(){})instanceof i,!Bu)return!0}return!e&&(bb==="BROWSER"||bb==="DENO")&&!vb});Sb.exports={CONSTRUCTOR:$k,REJECTION_EVENT:vb,SUBCLASSING:Bu}});var Hi=f((yB,Tb)=>{"use strict";var yb=st(),Lk=TypeError,Mk=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new Lk("Bad Promise constructor");e=i,t=r}),this.resolve=yb(e),this.reject=yb(t)};Tb.exports.f=function(a){return new Mk(a)}});var Fb=f(()=>{"use strict";var Ck=le(),Dk=ze(),Gs=Ns(),Dt=ne(),Wi=Oe(),Ib=Ni(),Eb=uu(),Vk=$r(),Ok=Ef(),Bk=st(),Qs=ae(),_k=Be(),Nk=Pf(),Fk=Su(),kb=Ru().set,Uu=db(),qk=hb(),Uk=Us(),Hk=$u(),Rb=zo(),Ws=li(),Hu=Ui(),$b=Hi(),Ys="Promise",Lb=Hu.CONSTRUCTOR,jk=Hu.REJECTION_EVENT,Qk=Hu.SUBCLASSING,_u=Rb.getterFor(Ys),Gk=Rb.set,ji=Ws&&Ws.prototype,ci=Ws,Hs=ji,Mb=Dt.TypeError,Nu=Dt.document,ju=Dt.process,Fu=$b.f,Wk=Fu,Yk=!!(Nu&&Nu.createEvent&&Dt.dispatchEvent),Cb="unhandledrejection",zk="rejectionhandled",xb=0,Db=1,Kk=2,Qu=1,Vb=2,js,Pb,Xk,wb,Ob=function(a){var e;return _k(a)&&Qs(e=a.then)?e:!1},Bb=function(a,e){var t=e.value,i=e.state===Db,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===Vb&&Zk(e),e.rejection=Qu),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Mb("Promise-chain cycle")):(l=Ob(u))?Wi(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},_b=function(a,e){a.notified||(a.notified=!0,Uu(function(){for(var t=a.reactions,i;i=t.get();)Bb(i,a);a.notified=!1,e&&!a.rejection&&Jk(a)}))},Nb=function(a,e,t){var i,r;Yk?(i=Nu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Dt.dispatchEvent(i)):i={promise:e,reason:t},!jk&&(r=Dt["on"+a])?r(i):a===Cb&&qk("Unhandled promise rejection",t)},Jk=function(a){Wi(kb,Dt,function(){var e=a.facade,t=a.value,i=Ab(a),r;if(i&&(r=Uk(function(){Gs?ju.emit("unhandledRejection",t,e):Nb(Cb,e,t)}),a.rejection=Gs||Ab(a)?Vb:Qu,r.error))throw r.value})},Ab=function(a){return a.rejection!==Qu&&!a.parent},Zk=function(a){Wi(kb,Dt,function(){var e=a.facade;Gs?ju.emit("rejectionHandled",e):Nb(zk,e,a.value)})},Qi=function(a,e,t){return function(i){a(e,i,t)}},Gi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Kk,_b(a,!0))},qu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Mb("Promise can't be resolved itself");var i=Ob(e);i?Uu(function(){var r={done:!1};try{Wi(i,e,Qi(qu,r,a),Qi(Gi,r,a))}catch(s){Gi(r,s,a)}}):(a.value=e,a.state=Db,_b(a,!1))}catch(r){Gi({done:!1},r,a)}}};if(Lb&&(ci=function(e){Nk(this,Hs),Bk(e),Wi(js,this);var t=_u(this);try{e(Qi(qu,t),Qi(Gi,t))}catch(i){Gi(t,i)}},Hs=ci.prototype,js=function(e){Gk(this,{type:Ys,done:!1,notified:!1,parent:!1,reactions:new Hk,rejection:!1,state:xb,value:void 0})},js.prototype=Ib(Hs,"then",function(e,t){var i=_u(this),r=Fu(Fk(this,ci));return i.parent=!0,r.ok=Qs(e)?e:!0,r.fail=Qs(t)&&t,r.domain=Gs?ju.domain:void 0,i.state===xb?i.reactions.add(r):Uu(function(){Bb(r,i)}),r.promise}),Pb=function(){var a=new js,e=_u(a);this.promise=a,this.resolve=Qi(qu,e),this.reject=Qi(Gi,e)},$b.f=Fu=function(a){return a===ci||a===Xk?new Pb(a):Wk(a)},!Dk&&Qs(Ws)&&ji!==Object.prototype)){wb=ji.then,Qk||Ib(ji,"then",function(e,t){var i=this;return new ci(function(r,s){Wi(wb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete ji.constructor}catch(a){}Eb&&Eb(ji,Hs)}Ck({global:!0,constructor:!0,wrap:!0,forced:Lb},{Promise:ci});Vk(ci,Ys,!1,!0);Ok(Ys)});var Qb=f((EB,jb)=>{"use strict";var eR=be(),Ub=eR("iterator"),Hb=!1;try{qb=0,Gu={next:function(){return{done:!!qb++}},return:function(){Hb=!0}},Gu[Ub]=function(){return this},Array.from(Gu,function(){throw 2})}catch(a){}var qb,Gu;jb.exports=function(a,e){try{if(!e&&!Hb)return!1}catch(r){return!1}var t=!1;try{var i={};i[Ub]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Wu=f((xB,Gb)=>{"use strict";var tR=li(),iR=Qb(),rR=Ui().CONSTRUCTOR;Gb.exports=rR||!iR(function(a){tR.all(a).then(void 0,function(){})})});var Wb=f(()=>{"use strict";var aR=le(),sR=Oe(),nR=st(),oR=Hi(),uR=Us(),lR=Os(),cR=Wu();aR({target:"Promise",stat:!0,forced:cR},{all:function(e){var t=this,i=oR.f(t),r=i.resolve,s=i.reject,n=uR(function(){var o=nR(t.resolve),u=[],l=0,c=1;lR(e,function(d){var h=l++,p=!1;c++,sR(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 zb=f(()=>{"use strict";var dR=le(),pR=ze(),hR=Ui().CONSTRUCTOR,zu=li(),mR=ft(),fR=ae(),bR=Ni(),Yb=zu&&zu.prototype;dR({target:"Promise",proto:!0,forced:hR,real:!0},{catch:function(a){return this.then(void 0,a)}});!pR&&fR(zu)&&(Yu=mR("Promise").prototype.catch,Yb.catch!==Yu&&bR(Yb,"catch",Yu,{unsafe:!0}));var Yu});var Kb=f(()=>{"use strict";var gR=le(),vR=Oe(),SR=st(),yR=Hi(),TR=Us(),IR=Os(),ER=Wu();gR({target:"Promise",stat:!0,forced:ER},{race:function(e){var t=this,i=yR.f(t),r=i.reject,s=TR(function(){var n=SR(t.resolve);IR(e,function(o){vR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Xb=f(()=>{"use strict";var xR=le(),PR=Hi(),wR=Ui().CONSTRUCTOR;xR({target:"Promise",stat:!0,forced:wR},{reject:function(e){var t=PR.f(this),i=t.reject;return i(e),t.promise}})});var Ku=f((CB,Jb)=>{"use strict";var AR=nt(),kR=Be(),RR=Hi();Jb.exports=function(a,e){if(AR(a),kR(e)&&e.constructor===a)return e;var t=RR.f(a),i=t.resolve;return i(e),t.promise}});var tg=f(()=>{"use strict";var $R=le(),LR=ft(),Zb=ze(),MR=li(),eg=Ui().CONSTRUCTOR,CR=Ku(),DR=LR("Promise"),VR=Zb&&!eg;$R({target:"Promise",stat:!0,forced:Zb||eg},{resolve:function(e){return CR(VR&&this===DR?MR:this,e)}})});var ig=f(()=>{"use strict";Fb();Wb();zb();Kb();Xb();tg()});var ng=f(()=>{"use strict";var OR=le(),BR=ze(),zs=li(),_R=fe(),ag=ft(),sg=ae(),NR=Su(),rg=Ku(),FR=Ni(),Ju=zs&&zs.prototype,qR=!!zs&&_R(function(){Ju.finally.call({then:function(){}},function(){})});OR({target:"Promise",proto:!0,real:!0,forced:qR},{finally:function(a){var e=NR(this,ag("Promise")),t=sg(a);return this.then(t?function(i){return rg(e,a()).then(function(){return i})}:a,t?function(i){return rg(e,a()).then(function(){throw i})}:a)}});!BR&&sg(zs)&&(Xu=ag("Promise").prototype.finally,Ju.finally!==Xu&&FR(Ju,"finally",Xu,{unsafe:!0}));var Xu});var ug=f((FB,og)=>{"use strict";bf();ig();ng();var UR=Ct();og.exports=UR("Promise","finally")});var cg=f((qB,lg)=>{"use strict";var HR=ug();lg.exports=HR});var Ks=f((UB,dg)=>{"use strict";var jR=cg();dg.exports=jR});var xg=f(()=>{"use strict";var a$=le(),s$=Qo().values;a$({target:"Object",stat:!0},{values:function(e){return s$(e)}})});var wg=f((w_,Pg)=>{"use strict";xg();var n$=$i();Pg.exports=n$.Object.values});var kg=f((A_,Ag)=>{"use strict";var o$=wg();Ag.exports=o$});var zi=f((k_,Rg)=>{"use strict";var u$=kg();Rg.exports=u$});var Gg=f(()=>{"use strict";var M$=le(),C$=Li(),D$=Bi(),V$=wr(),O$=Ar();M$({target:"Array",proto:!0},{at:function(e){var t=C$(this),i=D$(t),r=V$(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});O$("at")});var Yg=f((FN,Wg)=>{"use strict";Gg();var B$=Ct();Wg.exports=B$("Array","at")});var Kg=f((qN,zg)=>{"use strict";var _$=Yg();zg.exports=_$});var Nt=f((UN,Xg)=>{"use strict";var N$=Kg();Xg.exports=N$});var xl=f(($q,Mv)=>{"use strict";var IL=ii();Mv.exports=Array.isArray||function(e){return IL(e)==="Array"}});var Dv=f((Lq,Cv)=>{"use strict";var EL=TypeError,xL=9007199254740991;Cv.exports=function(a){if(a>xL)throw EL("Maximum allowed index exceeded");return a}});var Bv=f((Mq,Ov)=>{"use strict";var PL=xl(),wL=Bi(),AL=Dv(),kL=Ci(),Vv=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?kL(n,o):!1,d,h;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&PL(d)?(h=wL(d),u=Vv(a,e,d,h,u,s-1)-1):(AL(u+1),a[u]=d),u++),l++;return u};Ov.exports=Vv});var qv=f((Cq,Fv)=>{"use strict";var _v=xl(),RL=vu(),$L=Be(),LL=be(),ML=LL("species"),Nv=Array;Fv.exports=function(a){var e;return _v(a)&&(e=a.constructor,RL(e)&&(e===Nv||_v(e.prototype))?e=void 0:$L(e)&&(e=e[ML],e===null&&(e=void 0))),e===void 0?Nv:e}});var Hv=f((Dq,Uv)=>{"use strict";var CL=qv();Uv.exports=function(a,e){return new(CL(a))(e===0?0:e)}});var jv=f(()=>{"use strict";var DL=le(),VL=Bv(),OL=st(),BL=Li(),_L=Bi(),NL=Hv();DL({target:"Array",proto:!0},{flatMap:function(e){var t=BL(this),i=_L(t),r;return OL(e),r=NL(t,0),r.length=VL(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Qv=f(()=>{"use strict";var FL=Ar();FL("flatMap")});var Wv=f((Nq,Gv)=>{"use strict";jv();Qv();var qL=Ct();Gv.exports=qL("Array","flatMap")});var zv=f((Fq,Yv)=>{"use strict";var UL=Wv();Yv.exports=UL});var Pl=f((qq,Kv)=>{"use strict";var HL=zv();Kv.exports=HL});var ia=f((Uq,Xv)=>{"use strict";var jL=Rr(),QL=String;Xv.exports=function(a){if(jL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return QL(a)}});var wl=f((Hq,Jv)=>{"use strict";Jv.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 tS=f((jq,eS)=>{"use strict";var GL=ce(),WL=Mt(),YL=ia(),kl=wl(),Zv=GL("".replace),zL=RegExp("^["+kl+"]+"),KL=RegExp("(^|[^"+kl+"])["+kl+"]+$"),Al=function(a){return function(e){var t=YL(WL(e));return a&1&&(t=Zv(t,zL,"")),a&2&&(t=Zv(t,KL,"$1")),t}};eS.exports={start:Al(1),end:Al(2),trim:Al(3)}});var sS=f((Qq,aS)=>{"use strict";var XL=Jo().PROPER,JL=fe(),iS=wl(),rS="\u200B\x85\u180E";aS.exports=function(a){return JL(function(){return!!iS[a]()||rS[a]()!==rS||XL&&iS[a].name!==a})}});var Rl=f((Gq,nS)=>{"use strict";var ZL=tS().start,eM=sS();nS.exports=eM("trimStart")?function(){return ZL(this)}:"".trimStart});var uS=f(()=>{"use strict";var tM=le(),oS=Rl();tM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==oS},{trimLeft:oS})});var cS=f(()=>{"use strict";uS();var iM=le(),lS=Rl();iM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==lS},{trimStart:lS})});var pS=f((Xq,dS)=>{"use strict";cS();var rM=Ct();dS.exports=rM("String","trimLeft")});var mS=f((Jq,hS)=>{"use strict";var aM=pS();hS.exports=aM});var bS=f((Zq,fS)=>{"use strict";var sM=mS();fS.exports=sM});var MS=f(()=>{"use strict"});var CS=f(()=>{"use strict"});var VS=f((OH,DS)=>{"use strict";var kM=Be(),RM=ii(),$M=be(),LM=$M("match");DS.exports=function(a){var e;return kM(a)&&((e=a[LM])!==void 0?!!e:RM(a)==="RegExp")}});var BS=f((BH,OS)=>{"use strict";var MM=nt();OS.exports=function(){var a=MM(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 FS=f((_H,NS)=>{"use strict";var CM=Oe(),DM=Ke(),VM=yr(),OM=BS(),_S=RegExp.prototype;NS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in _S)&&!DM(a,"flags")&&VM(_S,a)?CM(OM,a):e}});var US=f((NH,qS)=>{"use strict";var Bl=ce(),BM=Li(),_M=Math.floor,Vl=Bl("".charAt),NM=Bl("".replace),Ol=Bl("".slice),FM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qM=/\$([$&'`]|\d{1,2})/g;qS.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=qM;return r!==void 0&&(r=BM(r),u=FM),NM(s,u,function(l,c){var d;switch(Vl(c,0)){case"$":return"$";case"&":return a;case"`":return Ol(e,0,t);case"'":return Ol(e,n);case"<":d=r[Ol(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=_M(h/10);return p===0?l:p<=o?i[p-1]===void 0?Vl(c,1):i[p-1]+Vl(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var QS=f(()=>{"use strict";var UM=le(),HM=Oe(),Nl=ce(),HS=Mt(),jM=ae(),QM=Ri(),GM=VS(),tr=ia(),WM=Ir(),YM=FS(),zM=US(),KM=be(),XM=ze(),JM=KM("replace"),ZM=TypeError,_l=Nl("".indexOf),eC=Nl("".replace),jS=Nl("".slice),tC=Math.max;UM({target:"String",proto:!0},{replaceAll:function(e,t){var i=HS(this),r,s,n,o,u,l,c,d,h,p,m=0,b="";if(!QM(e)){if(r=GM(e),r&&(s=tr(HS(YM(e))),!~_l(s,"g")))throw new ZM("`.replaceAll` does not allow non-global regexes");if(n=WM(e,JM),n)return HM(n,e,i,t);if(XM&&r)return eC(tr(i),e,t)}for(o=tr(i),u=tr(e),l=jM(t),l||(t=tr(t)),c=u.length,d=tC(1,c),h=_l(o,u);h!==-1;)p=l?tr(t(u,h,o)):zM(u,o,h,[],void 0,t),b+=jS(o,m,h)+p,m=h+c,h=h+d>o.length?-1:_l(o,u,h+d);return m<o.length&&(b+=jS(o,m)),b}})});var WS=f((UH,GS)=>{"use strict";MS();CS();QS();var iC=Ct();GS.exports=iC("String","replaceAll")});var zS=f((HH,YS)=>{"use strict";var rC=WS();YS.exports=rC});var XS=f((jH,KS)=>{"use strict";var aC=zS();KS.exports=aC});var ZS=f((QH,JS)=>{"use strict";var sC=wr(),nC=ia(),oC=Mt(),uC=RangeError;JS.exports=function(e){var t=nC(oC(this)),i="",r=sC(e);if(r<0||r===1/0)throw new uC("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var ay=f((GH,ry)=>{"use strict";var iy=ce(),lC=Bo(),ey=ia(),cC=ZS(),dC=Mt(),pC=iy(cC),hC=iy("".slice),mC=Math.ceil,ty=function(a){return function(e,t,i){var r=ey(dC(e)),s=lC(t),n=r.length,o=i===void 0?" ":ey(i),u,l;return s<=n||o===""?r:(u=s-n,l=pC(o,mC(u/o.length)),l.length>u&&(l=hC(l,0,u)),a?r+l:l+r)}};ry.exports={start:ty(!1),end:ty(!0)}});var ny=f((WH,sy)=>{"use strict";var fC=ai();sy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(fC)});var oy=f(()=>{"use strict";var bC=le(),gC=ay().start,vC=ny();bC({target:"String",proto:!0,forced:vC},{padStart:function(e){return gC(this,e,arguments.length>1?arguments[1]:void 0)}})});var ly=f((KH,uy)=>{"use strict";oy();var SC=Ct();uy.exports=SC("String","padStart")});var dy=f((XH,cy)=>{"use strict";var yC=ly();cy.exports=yC});var hy=f((JH,py)=>{"use strict";var TC=dy();py.exports=TC});var Sd="2.0.131-dev.20b944d3.0";var De=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(De||{}),mt=(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))(mt||{});var fs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(fs||{}),so=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(so||{});var no=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(no||{}),bs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(bs||{});var YT=O(qe(),1);import{assertNever as gh,assertNonNullable as Lx,isNonNullable as Ts,ValueSubject as No,Subject as Mx,Subscription as Cx,merge as Dx,observableFrom as Vx,fromEvent as hh,map as mh,tap as fh,filterChanged as Ox,isNullable as Fo,ErrorCategory as bh}from"@vkontakte/videoplayer-shared/es2015";var ph=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 Is=class{constructor(e){this.connection$=new No(void 0);this.castState$=new No("NOT_AVAILABLE");this.errorEvent$=new Mx;this.realCastState$=new No("NOT_AVAILABLE");this.subscription=new Cx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Ts((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||ph("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:bh.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(){Ts(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Fo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Fo(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(hh(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 gh(r.sessionState)}})).add(Dx(hh(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(fh(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),mh(r=>r.castState)),Vx([i.getCastState()])).pipe(Ox(),mh(Bx),fh(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=Ts(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();Lx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Fo(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"?Ts(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:bh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Bx=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 gh(a)}};var xc=O(qe(),1),RT=O(_i(),1),$T=O(hu(),1);var Tg=O(Ks(),1);import{assertNever as pg}from"@vkontakte/videoplayer-shared/es2015";var ge=(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:pg(t)}return a},Xs=(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:pg(e)}};var k=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as QR,Subject as Js,merge as hg}from"@vkontakte/videoplayer-shared/es2015";var B=class{constructor(e){this.transitionStarted$=new Js;this.transitionEnded$=new Js;this.transitionUpdated$=new Js;this.forceChanged$=new Js;this.stateChangeStarted$=hg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=hg(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||QR(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 GR}from"@vkontakte/videoplayer-shared/es2015";var mg=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 GR(a)}};import{assertNever as Yi,assertNonNullable as di,debounce as fg,ErrorCategory as bg,fromEvent as pi,isNonNullable as gg,map as vg,merge as Sg,observableFrom as WR,Subject as YR,Subscription as Zu,timeout as zR,getHighestQuality as KR}from"@vkontakte/videoplayer-shared/es2015";var XR=5,JR=5,ZR=500,yg=7e3,Fr=class{constructor(e){this.subscription=new Zu;this.loadMediaTimeoutSubscription=new Zu;this.videoState=new B("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:Yi(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:Yi(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:Yi(e)}break}default:Yi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(mg(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 Zu;this.subscription.add(e),this.subscription.add(Sg(this.videoState.stateChangeStarted$.pipe(vg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(vg(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 YR;e.add(r.pipe(fg(ZR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(pi(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)>XR)&&r.next(o),s=o})),e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(pi(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<JR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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:Yi(n)}}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Sg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,WR(["init"])).pipe(fg(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"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(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"),k(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"),k(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"&&k(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];di(c);let d=KR(Object.keys(c));di(d);let h=c[d];di(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];di(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];di(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];di(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];di(c),i=ge(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:bg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yi(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 gg(o)&&(n.metadata.title=o),gg(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(zR(yg).subscribe(()=>s(`timeout(${yg})`)))});(0,Tg.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:bg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Il=O(qe(),1);import{clearVideoElement as Eg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as e$}from"@vkontakte/videoplayer-shared/es2015";var Ig=a=>{try{a.pause(),a.playbackRate=0,e$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as t$,Subscription as i$}from"@vkontakte/videoplayer-shared/es2015";var el=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)}},tl=window.WeakMap?new WeakMap:new el,il=window.WeakMap?new WeakMap:new Map,r$=(a,e=20)=>{let t=0;return t$(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ae=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?Eg(i):(i=document.createElement("video"),a.appendChild(i)),tl.set(i,r);let s=new i$;return s.add(r$(i,e)),il.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},ke=a=>{let e=il.get(a);e==null||e.unsubscribe(),il.delete(a);let t=tl.get(a);tl.delete(a),t?Eg(a):Ig(a)};var al=O(zi(),1);import{assertNonNullable as qr,isNonNullable as ut,isNullable as d$,fromEvent as Ki,merge as $g,observableFrom as Lg,filterChanged as Mg,map as Ur,Subject as Cg,Subscription as p$,ValueSubject as h$,ErrorCategory as m$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as rl,isNullable as l$,Subscription as c$}from"@vkontakte/videoplayer-shared/es2015";var Zs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=l$(r),l=new c$;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},ot=(a,e,t)=>Zs(e,()=>a.loop,i=>{rl(i)&&(a.loop=i)},{onError:t}),Re=(a,e,t,i)=>Zs(e,()=>({muted:a.muted,volume:a.volume}),r=>{rl(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}),Ue=(a,e,t,i)=>Zs(e,()=>a.playbackRate,r=>{rl(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Vt=Zs;var f$=a=>["__",a.language,a.label].join("|"),b$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},sl=class a{constructor(e){this.available$=new Cg;this.current$=new h$(void 0);this.error$=new Cg;this.subscription=new p$;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:m$.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(Vt(t.internalTextTracks,()=>(0,al.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ur(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Vt(t.externalTextTracks,()=>(0,al.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ur(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Vt(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(Vt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qr(this.video);let{textTracks:e}=this.video;this.subscription.add(Ki(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add($g(Ki(e,"addtrack"),Ki(e,"removetrack"),Lg(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Mg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add($g(Ki(e,"change"),Lg(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ur(i=>i&&this.htmlTextTrackToITextTrack(i).id),Mg()).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(Ki(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(Ki(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;ut(t.align)&&(r.align=t.align),ut(t.position)&&(r.position=t.position),ut(t.size)&&(r.size=t.size),ut(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){qr(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:f$(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){qr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(d$(e)||!b$(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){qr(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){qr(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)}},He=sl;var hi=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 Dg=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},nl=a=>{let e=Dg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Vg=a=>{let e=Dg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as $e,map as Ot,merge as ul,filterChanged as P$,isNonNullable as jg,Subject as w$,filter as jr,mapTo as ll,combine as A$,once as k$,throttle as R$,ErrorCategory as $$,ValueSubject as Qg,Subscription as L$}from"@vkontakte/videoplayer-shared/es2015";var g$=3,Og=(a,e,t=g$)=>{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 en=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 Bg=O(qe(),1);var Hr=()=>{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 tn=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,Bg.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=Hr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return E(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var rn=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 Je=()=>window.ManagedMediaSource||window.MediaSource,an=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_g=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ng=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var v$=document.createElement("video"),S$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',y$='video/mp4; codecs="hev1.1.6.L93.B0"',Fg='video/webm; codecs="vp09.00.10.08"',qg='video/webm; codecs="av01.0.00M.08"',T$='audio/mp4; codecs="mp4a.40.2"',I$='audio/webm; codecs="opus"',Ug,E$=()=>E(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(C(w({},a),{video:C(w({},a.video),{contentType:qg})})),window.navigator.mediaCapabilities.decodingInfo(C(w({},a),{video:C(w({},a.video),{contentType:Fg})}))]);Ug={DASH_WEBM_AV1:e,DASH_WEBM:t}});E$().catch(a=>{console.log(v$),console.error(a)});var sn=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 Ug}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:an(),mse:_g(),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=Je())==null?void 0:l.isTypeSupported)!=null&&c.call(l,S$)),$=!!((h=(d=Je())==null?void 0:d.isTypeSupported)!=null&&h.call(d,y$)),F=!!((m=(p=Je())==null?void 0:p.isTypeSupported)!=null&&m.call(p,T$));this._codecs={h264:T,h265:$,vp9:!!((g=(b=Je())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Fg)),av1:!!((S=(v=Je())==null?void 0:v.isTypeSupported)!=null&&S.call(v,qg)),aac:F,opus:!!((I=(y=Je())==null?void 0:y.isTypeSupported)!=null&&I.call(y,I$)),mpeg:(T||$)&&F},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 Hg="audio/mpeg",nn=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,Hg))},this._codecs={mp3:!!((r=(i=Je())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Hg))}}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 x$}from"@vkontakte/videoplayer-shared/es2015";var ol=class{constructor(){this.isInited$=new x$(!1);this._displayChecker=new rn,this._deviceChecker=new tn(this._displayChecker),this._browserChecker=new en,this._videoChecker=new sn(this._deviceChecker,this._browserChecker),this._audioChecker=new nn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return E(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},U=new ol;var Le=a=>{let e=x=>$e(a,x).pipe(ll(void 0)),t=new L$,i=()=>t.unsubscribe(),s=ul(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>$e(a,x))).pipe(Ot(x=>x.type==="ended"?a.readyState<2:a.readyState<3),P$()),n=ul($e(a,"progress"),$e(a,"timeupdate")).pipe(Ot(()=>Og(a.buffered,a.currentTime))),o=U.browser.isSafari?A$({play:e("play").pipe(k$()),playing:e("playing")}).pipe(ll(void 0)):e("playing"),u=$e(a,"volumechange").pipe(Ot(()=>({muted:a.muted,volume:a.volume}))),l=$e(a,"ratechange").pipe(Ot(()=>a.playbackRate)),c=$e(a,"error").pipe(jr(()=>!!(a.error||a.played.length)),Ot(()=>{var j;let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:$$.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:(j=a.error)!=null?j:void 0}})),d=$e(a,"timeupdate").pipe(Ot(()=>a.currentTime)),h=new w$,p=.3,m;t.add(d.subscribe(x=>{a.loop&&jg(m)&&jg(x)&&m>=a.duration-p&&x<=p&&h.next(m),m=x}));let b=e("pause").pipe(jr(()=>!a.error&&m!==a.duration)),g=$e(a,"enterpictureinpicture"),v=$e(a,"leavepictureinpicture"),S=new Qg(Vg(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new Qg(nl(a)),I=$e(a,"fullscreenchange");t.add(I.pipe(Ot(()=>nl(a))).subscribe(y));let T=.1,$=1e3,F=$e(a,"timeupdate").pipe(jr(x=>a.duration-a.currentTime<T)),q=ul(F.pipe(jr(x=>!a.loop)),$e(a,"ended")).pipe(R$($),ll(void 0)),K=F.pipe(jr(x=>a.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:q,looped$:h,loopExpected$:K,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:$e(a,"durationchange").pipe(Ot(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:S,inFullscreen$:y,enterPip$:g,leavePip$:v,destroy:i}};import{VideoQuality as Bt}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Bt.Q_144P;case"lowest":return Bt.Q_240P;case"low":return Bt.Q_360P;case"sd":case"medium":return Bt.Q_480P;case"hd":case"high":return Bt.Q_720P;case"fullhd":case"full":return Bt.Q_1080P;case"quadhd":case"quad":return Bt.Q_1440P;case"ultrahd":case"ultra":return Bt.Q_2160P}};var Ft=O(Nt(),1),ov=O(qe(),1),ln=O(_i(),1);import{isNonNullable as Ee,isNullable as rv,now as uv,isHigher as av,isHigherOrEqual as hl,isInvariantQuality as sv,isLowerOrEqual as ml,videoSizeToQuality as U$,assertNotEmptyArray as lv,assertNonNullable as H$}from"@vkontakte/videoplayer-shared/es2015";var cl=!1,vt={},Jg=a=>{cl=a},Zg=()=>{vt={}},ev=a=>{a(vt)},Qr=(a,e)=>{var t;cl&&(vt.meta=(t=vt.meta)!=null?t:{},vt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var i,r;if(!cl)return;vt.series=(i=vt.series)!=null?i:{};let t=(r=vt.series[this.name])!=null?r:[];t.push([Date.now(),e]),vt.series[this.name]=t}};import{isHigher as F$,isHigherOrEqual as YN,isLower as tv,isLowerOrEqual as zN,isNonNullable as on,isNullable as q$,videoHeightToQuality as un}from"@vkontakte/videoplayer-shared/es2015";function dl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function pl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&dl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Gr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return q$(a)||on(a.min)&&on(a.max)&&tv(a.max,a.min)||on(a.min)&&e&&F$(a.min,e)||on(a.max)&&t&&tv(a.max,t)}function iv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Gr({limits:{max:a!=null&&a.max?un(a.max):void 0,min:a!=null&&a.min?un(a.min):void 0},highestAvailableQuality:e?un(e):void 0,lowestAvailableQuality:t?un(t):void 0})}var j$=new Ie("best_bitrate"),cv=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var fl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=uv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},dv='Assertion "ABR Tracks is empty array" failed',cn=(a,e,t,i)=>{var u;let r=[...e].sort(fl(1)),s=[...t].sort(fl(1)),n=s.filter(l=>Ee(l.bitrate)&&Ee(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Ft.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Ft.default)(s,-1);return o&&(0,ov.default)(n,o)?o:n.length?(0,Ft.default)(n,-1):(0,Ft.default)(s,0)},nv=a=>"quality"in a,pv=(a,e,t,i)=>{var n;let r=Ee((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&Ee(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&uv()-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=nv(o)?"video":"audio",l=nv(o)?o.quality:o.bitrate;return e({message:`
|
|
8
|
-
[
|
|
9
|
-
`}),o}return i==null||i.recordSwitch(t),t},Q$=(a,e)=>Math.log(e)/Math.log(a),G$=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&U.display.pixelRatio){let s=U.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=Q$(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return pl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},qt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:b})=>{var N,Z,R,D,X;lv(a,dv);let{containerSizeFactor:g,containerSizeLimit:v}=G$({container:e,tuning:i,limits:r,panelSize:b}),S=i.considerPlaybackRate&&Ee(o)?o:1,y=a.filter(P=>!sv(P.quality)).sort((P,M)=>av(P.quality,M.quality)?-1:1),I=(N=(0,Ft.default)(y,-1))==null?void 0:N.quality,T=(Z=(0,Ft.default)(y,0))==null?void 0:Z.quality,$=Gr({limits:r,lowestAvailableQuality:I,highestAvailableQuality:T}),F=S*cv(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),q={},x=y.filter(P=>{let M=!0;if(v)if(P.size)M=P.size.width<=v.width&&P.size.height<=v.height;else{let pt=v&&U$(v);M=pt?ml(P.quality,pt):!0}if(!M)return q[P.quality]="FitsContainer",!1;let me=p||t,Ti=Ee(me)&&isFinite(me)&&Ee(P.bitrate)?me-s>=P.bitrate*F:!0,dt=pl({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&(r==null?void 0:r.min)===P.quality;if(!Ti&&!dt)return q[P.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Ee(i.minBufferToSwitchUp)&&u&&!sv(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&av(P.quality,u.quality))return q[P.quality]="Buffer",!1;if(!!d&&hl(P.quality,d)&&!dt)return q[P.quality]="DroppedFramesLimit",!1;if(!!h&&hl(P.quality,h)&&!dt)return q[P.quality]="StallsLimit",!1;let we=$||(rv(r==null?void 0:r.max)||ml(P.quality,r.max))&&(rv(r==null?void 0:r.min)||hl(P.quality,r.min)),tt=Ee(c)&&!c?ml(P.quality,i.backgroundVideoQualityLimit):!0;return!we||!tt?(q[P.quality]="FitsQualityLimits",!1):!0})[0];x&&x.bitrate&&j$.next(x.bitrate);let j=(R=x!=null?x:(0,Ft.default)(y,-1))!=null?R:a[0],L=l==null?void 0:l.last,Q=pv(i,m,j,l);return Ee(l)&&Q.quality!==(L==null?void 0:L.quality)&&m({message:`
|
|
10
|
-
[VIDEO TRACKS ABR]
|
|
11
|
-
[available video tracks]
|
|
12
|
-
${a.map(P=>{var M,me;return`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate}, size: ${(M=P.size)==null?void 0:M.width}:${(me=P.size)==null?void 0:me.height} }`}).join(`
|
|
13
|
-
`)}
|
|
14
|
-
|
|
15
|
-
[tuning]
|
|
16
|
-
${(0,ln.default)(i!=null?i:{}).map(([P,M])=>`${P}: ${M}`).join(`
|
|
17
|
-
`)}
|
|
18
|
-
|
|
19
|
-
[limit params]
|
|
20
|
-
containerSizeFactor: ${g},
|
|
21
|
-
containerSizeLimit: ${(D=v==null?void 0:v.width)!=null?D:0} x ${(X=v==null?void 0:v.height)!=null?X:0},
|
|
22
|
-
estimatedThroughput: ${t},
|
|
23
|
-
stallsPredictedThroughput: ${p},
|
|
24
|
-
reserve: ${s},
|
|
25
|
-
playbackRate: ${o},
|
|
26
|
-
playbackRateFactor: ${S},
|
|
27
|
-
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${F},
|
|
29
|
-
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${d},
|
|
31
|
-
stallsVideoMaxQualityLimit: ${h},
|
|
32
|
-
limitsAreInvalid: ${$},
|
|
33
|
-
maxQualityLimit: ${r==null?void 0:r.max},
|
|
34
|
-
minQualityLimit: ${r==null?void 0:r.min},
|
|
35
|
-
|
|
36
|
-
[limited video tracks]
|
|
37
|
-
${(0,ln.default)(q).map(([P,M])=>`${P}: ${M}`).join(`
|
|
38
|
-
`)||"All tracks are available"}
|
|
39
|
-
|
|
40
|
-
[best video track] ${x==null?void 0:x.quality}
|
|
41
|
-
[selected video track] ${Q==null?void 0:Q.quality}
|
|
42
|
-
`}),Q},hv=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{lv(t,dv);let c=r.considerPlaybackRate&&Ee(s)?s:1,d=[...t].sort(fl(-1)),h=a.bitrate;H$(h);let p=c*cv(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=cn(a,e,t,r.minVideoAudioRatio),g=l||i;Ee(g)&&isFinite(g)&&(m=d.find(y=>Ee(y.bitrate)&&Ee(b==null?void 0:b.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,S=m&&pv(r,u,m,o);return Ee(o)&&(S==null?void 0:S.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
|
|
43
|
-
[AUDIO TRACKS ABR]
|
|
44
|
-
[available audio tracks]
|
|
45
|
-
${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
|
|
46
|
-
`)}
|
|
47
|
-
|
|
48
|
-
[tuning]
|
|
49
|
-
${(0,ln.default)(r!=null?r:{}).map(([y,I])=>`${y}: ${I}`).join(`
|
|
50
|
-
`)}
|
|
51
|
-
|
|
52
|
-
[limit params]
|
|
53
|
-
estimatedThroughput: ${i},
|
|
54
|
-
stallsPredictedThroughput: ${l},
|
|
55
|
-
reserve: ${h},
|
|
56
|
-
playbackRate: ${s},
|
|
57
|
-
playbackRateFactor: ${c},
|
|
58
|
-
forwardBufferHealth: ${n},
|
|
59
|
-
bitrateFactor: ${p},
|
|
60
|
-
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
61
|
-
|
|
62
|
-
[selected audio track] ${S==null?void 0:S.id}
|
|
63
|
-
`}),S};var de=a=>new URL(a).hostname;import{assertNever as xv,assertNonNullable as Pv,combine as hL,debounce as mL,ErrorCategory as wv,filter as Av,filterChanged as fL,isNonNullable as yl,map as fn,merge as kv,observableFrom as bL,once as gL,Subscription as vL,ValueSubject as Tl,videoQualityToHeight as Rv,videoSizeToQuality as SL}from"@vkontakte/videoplayer-shared/es2015";var yv=O(Nt(),1);var fv=O(qe(),1);var mv=a=>{if(a instanceof DOMException&&(0,fv.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"))},Me=(a,e)=>E(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!mv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return mv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as pn,isNullable as z$,assertNonNullable as Kr}from"@vkontakte/videoplayer-shared/es2015";var gv=O(zi(),1);import{isNonNullable as bv,assertNonNullable as dn,now as W$}from"@vkontakte/videoplayer-shared/es2015";function pe(){return W$()}function bl(a){return pe()-a}function gl(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 vv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Xi(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;dn(c);let L=bl(c),Q;if(L<b){Q=b-L,setTimeout(g,Q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,$()},v=L=>(s=L,j),S=L=>(d=L,j),y=()=>(p="json",j),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},T=L=>(h=L,j),$=()=>{c=pe(),n=new r,n.open("get",a);let L=0,Q,N=0,Z=()=>(dn(c),Math.max(c,Math.max(Q||0,N||0)));if(s&&n.addEventListener("progress",R=>{let D=pe();s.updateChunk&&R.loaded>L&&(s.updateChunk(Z(),R.loaded-L),L=R.loaded,Q=D)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;dn(n);let R=n.status;if(R>=200&&R<300){let{response:D,responseType:X}=n,P=D==null?void 0:D.byteLength;if(typeof P=="number"&&s){let M=P-L;M&&s.updateChunk&&s.updateChunk(Z(),M)}X==="json"&&(!D||!(0,gv.default)(D).length)?I():(d&&d(),e(D))}else I()}),n.addEventListener("error",()=>{I()}),h){let R=()=>{dn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=pe(),n.removeEventListener("readystatechange",R))};n.addEventListener("readystatechange",R)}return n.responseType=p,n.send(),j},j={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:L=>(l=L,j),withRetryInterval:(L,Q)=>(bv(L)&&(b=L),bv(Q)&&(m=Q),j),withTimeout:L=>(o=L,j),withFinally:S,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return j}var Yr=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 Sv=O(zi(),1);var zr=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=pe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=pe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Xi(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=pe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Sv.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 K$}from"@vkontakte/videoplayer-shared/es2015";var hn=1e4,vl=3;var X$=6e4,J$=10,Z$=1,eL=500,Xr=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 K$,this.chunkRateEstimator=new Yr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=gl(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=gl(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*(U.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||{};!iv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,yv.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||pn(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=()=>{vv(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 zr(vl,hn,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,$)=>{u&&u.abort(),u=Xi(this.urlResolver.resolve(I,!1),T,$,()=>this._retryCallback()).withTimeout(hn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(vl).withFinally(()=>{u=null}).send()},p=(I,T,$)=>{Kr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,$,()=>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 $=pe()-1e4,F=0;for(let K=0;K<this.bufferStates.length;K++){let x=this.bufferStates[K];I=Math.min(I,x.buf),x.ts<$&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${I} drop=${F} jitter=${this.sourceJitter}`);let q=I-Z$;this.sourceJitter>=0?q-=this.sourceJitter/2:this.sourceJitter-=1,q>3?m(1.15):q>1?m(1.1):q>.3?m(1.05):m(1)}},v=I=>{let T,$=()=>T&&T.start?T.start.length:0,F=R=>T.start[R]/1e3,q=R=>T.dur[R]/1e3,K=R=>T.fragIndex+R,x=(R,D)=>({chunkIdx:K(R),startTS:F(R),dur:q(R),discontinuity:D}),j=()=>{let R=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,P=D;this.sourceJitter>1&&(P+=this.sourceJitter-1);let M=T.dur.length-1;for(;M>=0&&(P-=T.dur[M],!(P<=0));--M);R=Math.min(M,T.dur.length-1-X),R=Math.max(R,0)}return x(R,!0)},L=R=>{let D=$();if(!(D<=0)){if(pn(R)){for(let X=0;X<D;X++)if(F(X)>R)return x(X)}return j()}},Q=R=>{let D=$(),X=R?R.chunkIdx+1:0,P=X-T.fragIndex;if(!(D<=0)){if(!R||P<0||P-D>J$)return t(`Resync: offset=${P} bChunks=${D} chunk=`+JSON.stringify(R)),j();if(!(P>=D))return x(X-T.fragIndex,!1)}},N=(R,D,X)=>{l&&l.abort(),l=Xi(this.urlResolver.resolve(R,!0,this.lowLatency),D,X,()=>this._retryCallback()).withTimeout(hn).withRetryCount(vl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(R,D)=>{N(I,X=>{if(!d())return;T=X;let P=!!T.lowLatency;P!==this.lowLatency&&b(P);let M=0;for(let me=0;me<T.dur.length;++me)M+=T.dur[me];M>0&&(Kr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(M/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,R(L(D))},()=>this._handleNetworkError())},nextChunk:Q}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Kr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:T,logger:$}=this.params,F=v(e.jidxUrl),q,K,x,j,L=0,Q,N,Z,R=()=>{Q&&(clearTimeout(Q),Q=void 0);let Y=Math.max(eL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=L+Y,Pe=pe(),we=Math.min(1e4,ye-Pe);L=Pe;let tt=()=>{l||d()&&F.seek(()=>{d()&&(L=pe(),D(),R())})};we>0?Q=window.setTimeout(()=>{this.paused?R():tt()},we):tt()},D=()=>{let Y;for(;Y=F.nextChunk(j);)j=Y,Ti(Y);let ye=F.nextChunk(x);if(ye){if(x&&ye.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?R():(S(),this._initPlayerWith(e));return}me(ye)}else R()},X=(Y,ye)=>{if(!d()||!this.sourceBuffer)return;let Pe,we,tt,pt=Pt=>{window.setTimeout(()=>{d()&&X(Y,ye)},Pt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),pt(100);else{let Pt=pe(),zt=T.currentTime;!this.paused&&T.buffered.length>1&&N===zt&&Pt-Z>500&&($("Stall suspected; trying to fix"),this._fixupStall()),N!==zt&&(N=zt,Z=Pt);let Ii=this._getBufferSizeSec();if(Ii>30)$(`Buffered ${Ii} seconds; delaying appendBuffer`),pt(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:Pt,buf:Ii}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(cr){if(cr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(Pe=this.sourceBuffer.buffered.start(0),we=zt,we-Pe>4&&this.sourceBuffer.remove(Pe,we-3)),pt(1e3);else throw cr}}},P=()=>{K&&q&&($([`Appending chunk, sz=${K.byteLength}:`,JSON.stringify(x)]),X(K,function(){K=null,D()}))},M=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),me=Y=>{d()&&p(M(Y),(ye,Pe)=>{if(d()){if(Pe/=1e3,K=ye,x=Y,n=Y.startTS,Pe){let we=Math.min(10,Y.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}P()}},()=>this._handleNetworkError())},Ti=Y=>{d()&&(Kr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(M(Y),!1)))},dt=Y=>{d()&&(e.cachedHeader=Y,X(Y,()=>{q=!0,P()}))};s=!0,F.seek(Y=>{if(d()){if(L=pe(),!Y){R();return}j=Y,!z$(I)||Y.startTS>I?me(Y):(x=Y,D())}},I),e.cachedHeader?dt(e.cachedHeader):h(e.headerUrl,dt,()=>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(),pn(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,Kr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return pn(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=pe();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&&bl(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=pe();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Xi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(hn).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;Me(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))},X$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ev=O(_i(),1);import{debounce as tL,filter as Tv,fromEvent as iL,interval as rL,isHigher as aL,isInvariantQuality as sL,isLower as nL,merge as oL,Subject as Iv,Subscription as uL}from"@vkontakte/videoplayer-shared/es2015";var Sl=class{constructor(){this.onDroopedVideoFramesLimit$=new Iv;this.subscription=new uL;this.playing=!1;this.tracks=[];this.forceChecker$=new Iv;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&&!sL(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&&aL(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(iL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=rL(this.droppedFramesChecker.checkTime).pipe(Tv(()=>this.playing),Tv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(tL(this.droppedFramesChecker.checkTime)),i=oL(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,Ev.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>nL(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}},mn=Sl;import{map as lL,Observable as cL}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as dL}from"@vkontakte/videoplayer-shared/es2015";var Jr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var pL=(a,e)=>new cL(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Jr()))},w(w({},i),e));r.observe(a);let s=dL(document,"visibilitychange").pipe(lL(n=>!document.hidden||Jr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),je=pL;var yL=["paused","playing","ready"],TL=["paused","playing","ready"],Zr=class{constructor(e){this.subscription=new vL;this.videoState=new B("stopped");this.representations$=new Tl([]);this.droppedFramesManager=new mn;this.maxSeekBackTime$=new Tl(1/0);this.zeroTime$=new Tl(void 0);this.liveOffset=new hi;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:wv.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=_t(u.name))!=null?i:SL(u.video),d=u.bitrate/1e3,h=w({},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),yl(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,Il.default)(TL,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Il.default)(yL,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ge(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(ge(this.params.source.url,u))}return;default:return xv(e)}};this.textTracksManager=new He(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:wv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(kv(this.videoState.stateChangeStarted$.pipe(fn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ae(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(de(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=Le(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(fn(r=>r.map(({track:s})=>s)),Av(r=>!!r.length),gL()).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(fL(),fn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(hL({zeroTime:this.zeroTime$.pipe(Av(yl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Re(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ue(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(je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Rv(r),min:s&&Rv(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 xv(r.to)}},t)).add(kv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,bL(["init"])).pipe(mL(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ke(this.video)}createLiveDashPlayer(){let e=new Xr({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&&yl(t)?t:qt(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;Pv(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;Pv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),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(ge(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var $v=Zr;var Jy=O(qe(),1);var Ji=(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 iD,assertNonNullable as rD,debounce as aD,ErrorCategory as zy,filter as lc,filterChanged as qa,fromEvent as sD,isNonNullable as Ky,map as cc,merge as On,observableFrom as dc,once as Xy,Subscription as nD}from"@vkontakte/videoplayer-shared/es2015";var bn=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}},Zi=class extends bn{constructor(){super(),this.listeners||bn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},ea=class{constructor(){Object.defineProperty(this,"signal",{value:new Zi,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&&(ea.prototype[Symbol.toStringTag]="AbortController",Zi.prototype[Symbol.toStringTag]="AbortSignal");function gn(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 El(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!gn({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 ta=gn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Lv=ta?El({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ta?Lv.fetch:window.fetch,Aq=ta?Lv.Request:window.Request,ve=ta?ea:window.AbortController,kq=ta?Zi:window.AbortSignal;var sc=O(Pl(),1);var gS=O(bS(),1);import{ErrorCategory as ra}from"@vkontakte/videoplayer-shared/es2015";var vS=a=>{if(!a)return{id:"EmptyResponse",category:ra.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ra.NETWORK,message:`UV Error ${a}`};let e=(0,gS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ra.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ra.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ra.PARSER,message:"Response is valid XML, but parser failed"}};var Ut=(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 ic,assertNonNullable as sr,combine as nr,ErrorCategory as ct,filter as Rn,filterChanged as _a,flattenObject as Na,fromEvent as It,getTraceSubscriptionMethod as _C,interval as rc,isNonNullable as Fa,isNullable as Uy,map as or,merge as Si,now as ac,Subject as $n,Subscription as Hy,tap as NC,throttle as FC,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2015";var Sn=O(qe(),1),rr=O(Nt(),1),yn=O(Pl(),1);var nM=(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)},oM=a=>window.clearTimeout(a),SS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),yS=!SS(window.requestIdleCallback)||!SS(window.cancelIdleCallback),$l=yS?nM:window.requestIdleCallback,aa=yS?oM:window.cancelIdleCallback;var Ry=O(Ks(),1);import{assertNever as uM,ErrorCategory as TS,Subject as IS}from"@vkontakte/videoplayer-shared/es2015";var lM=18,ES=!1;try{ES=U.browser.isSafari&&!!U.browser.safariVersion&&U.browser.safariVersion<=lM}catch(a){console.error(a)}var Ll=class{constructor(e){this.bufferFull$=new IS;this.error$=new IS;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:TS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return E(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return E(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return E(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};ES&&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:TS.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:uM(t)}}},xS=Ll;var Ml=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 jt,assertNonNullable as Ce,ErrorCategory as Tt,fromEvent as zl,getExponentialDelay as Kl,isNonNullable as ir,isNullable as Se,now as vn,once as PC,Subject as wC,Subscription as AC,ValueSubject as bi}from"@vkontakte/videoplayer-shared/es2015";var G=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 er=class extends G{};var sa=class extends G{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 na=class extends G{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 oa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ie=class extends G{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ua=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var la=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ca=class extends G{constructor(e,t){super(e,t),this.data=this.content}};var mi=class extends ie{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 da=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends ie{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ma=class extends ie{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var fa=class extends ie{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ba=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends ie{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var va=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends ie{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ta=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends ie{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Ea=class extends ie{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 xa=class extends ie{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 Pa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends ie{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Aa=class extends G{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var dM={ftyp:na,moov:oa,mvhd:ua,moof:la,mdat:ca,sidx:mi,trak:da,mdia:ba,mfhd:ya,tkhd:ga,traf:Ta,tfhd:Ia,tfdt:Ea,trun:xa,minf:va,sv3d:pa,st3d:ha,prhd:ma,proj:Sa,equi:fa,uuid:sa,stbl:Pa,stsd:wa,avc1:Aa,unknown:er},St=class a{constructor(e={}){this.options=w({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=dM[e];return i?new i(t,new a):new er(t,new a)}};var Ht=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 hM=new TextDecoder("ascii"),mM=a=>hM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",fM=a=>{let e=new mi(a,new St),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})},bM=(a,e)=>{let i=new St().parse(a),r=new Ht(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)},gM=a=>{let t=new St().parse(a),i=new Ht(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},vM=a=>{var r;let t=new St().parse(a);return(r=new Ht(t).find("sidx"))==null?void 0:r.timescale},SM=(a,e)=>{let i=new St().parse(a),s=new Ht(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},yM=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 St().parse(a),r=new Ht(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},PS={validateData:mM,parseInit:yM,getIndexRange:()=>{},parseSegments:fM,parseFeedableSegmentChunk:bM,getChunkEndTime:SM,getServerLatencyTimestamps:gM,getTimescaleFromIndex:vM};var Ra=O(qe(),1);import{assertNonNullable as Dl,isNonNullable as RS,isNullable as IM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as TM}from"@vkontakte/videoplayer-shared/es2015";var wS={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"}},AS=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=ka(a,t),r=i in wS,s=r?wS[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=ka(u),d=l*at(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}},ka=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*at(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*at(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*at(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ka(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:TM(e)}},fi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=AS(i);if(!e(r))return;r.type==="master"&&fi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},kS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=AS(a);return fi(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 $S=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],EM=[231,22612,22743,167,171,163,160,175],xM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return fi(a,({tag:h,type:p,value:m,valueSize:b})=>{if(h===21419){let g=Ze(m,p);l=ka(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?fi(m,({tag:g,type:v,value:S})=>g===30321?(c=Ze(S,v)===1,!1):!0):s&&n&&(0,Ra.default)($S,h)&&(o=!0),!o}),Dl(e,"Failed to parse webm Segment start"),Dl(t,"Failed to parse webm Segment end"),Dl(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(IM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},wM=(a,e)=>{let t=!1,i=!1,r=o=>RS(o.time)&&RS(o.position),s=[],n;return fi(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,Ra.default)($S,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}}})},AM=a=>{let e=0,t=!1;try{fi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ra.default)(EM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,Ra.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},LS={validateData:kS,parseInit:xM,getIndexRange:PM,parseSegments:wM,parseFeedableSegmentChunk:AM};var $a=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return LS;case"mp4":return PS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Gl=O(XS(),1),Ey=O(_i(),1),xy=O(hy(),1),Py=O(Nt(),1),Wl=O(zi(),1);var my=O(qe(),1),Fl=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,my.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as xC,isNullable as Ty}from"@vkontakte/videoplayer-shared/es2015";var fy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var by=a=>{var e;try{let t=IC(),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 IC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
64
|
-
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
6
|
+
var AE=Object.create;var Ul=Object.defineProperty,kE=Object.defineProperties,RE=Object.getOwnPropertyDescriptor,ME=Object.getOwnPropertyDescriptors,LE=Object.getOwnPropertyNames,Dh=Object.getOwnPropertySymbols,BE=Object.getPrototypeOf,Ch=Object.prototype.hasOwnProperty,DE=Object.prototype.propertyIsEnumerable;var $E=(s,e)=>(e=Symbol[s])?e:Symbol.for("Symbol."+s);var Ze=Math.pow,$h=(s,e,t)=>e in s?Ul(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,x=(s,e)=>{for(var t in e||(e={}))Ch.call(e,t)&&$h(s,t,e[t]);if(Dh)for(var t of Dh(e))DE.call(e,t)&&$h(s,t,e[t]);return s},D=(s,e)=>kE(s,ME(e));var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var CE=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of LE(e))!Ch.call(s,r)&&r!==t&&Ul(s,r,{get:()=>e[r],enumerable:!(i=RE(e,r))||i.enumerable});return s};var U=(s,e,t)=>(t=s!=null?AE(BE(s)):{},CE(e||!s||!s.__esModule?Ul(t,"default",{value:s,enumerable:!0}):t,s));var I=(s,e,t)=>new Promise((i,r)=>{var a=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(a,n);o((t=t.apply(s,e)).next())}),Qi=function(s,e){this[0]=s,this[1]=e},Q=(s,e,t)=>{var i=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof Qi,h=d.done;Promise.resolve(c?o[0]:o).then(p=>c?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>a[n]=o=>new Promise((u,l)=>i(n,o,u,l)),a={};return t=t.apply(s,e),a[$E("asyncIterator")]=()=>a,r("next"),r("throw"),r("return"),a};var Ie=b((jl,Oh)=>{"use strict";var sa=function(s){return s&&s.Math===Math&&s};Oh.exports=sa(typeof globalThis=="object"&&globalThis)||sa(typeof window=="object"&&window)||sa(typeof self=="object"&&self)||sa(typeof global=="object"&&global)||sa(typeof jl=="object"&&jl)||function(){return this}()||Function("return this")()});var Ve=b((o_,_h)=>{"use strict";_h.exports=function(s){try{return!!s()}catch(e){return!0}}});var aa=b((u_,Fh)=>{"use strict";var VE=Ve();Fh.exports=!VE(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var Gl=b((l_,Hh)=>{"use strict";var OE=aa(),qh=Function.prototype,Nh=qh.apply,Uh=qh.call;Hh.exports=typeof Reflect=="object"&&Reflect.apply||(OE?Uh.bind(Nh):function(){return Uh.apply(Nh,arguments)})});var De=b((c_,zh)=>{"use strict";var jh=aa(),Gh=Function.prototype,zl=Gh.call,_E=jh&&Gh.bind.bind(zl,zl);zh.exports=jh?_E:function(s){return function(){return zl.apply(s,arguments)}}});var Yi=b((d_,Qh)=>{"use strict";var Wh=De(),FE=Wh({}.toString),NE=Wh("".slice);Qh.exports=function(s){return NE(FE(s),8,-1)}});var Wl=b((p_,Yh)=>{"use strict";var UE=Yi(),qE=De();Yh.exports=function(s){if(UE(s)==="Function")return qE(s)}});var ye=b((h_,Kh)=>{"use strict";var Ql=typeof document=="object"&&document.all;Kh.exports=typeof Ql=="undefined"&&Ql!==void 0?function(s){return typeof s=="function"||s===Ql}:function(s){return typeof s=="function"}});var gt=b((f_,Xh)=>{"use strict";var HE=Ve();Xh.exports=!HE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var St=b((m_,Jh)=>{"use strict";var jE=aa(),Po=Function.prototype.call;Jh.exports=jE?Po.bind(Po):function(){return Po.apply(Po,arguments)}});var Yl=b(tf=>{"use strict";var Zh={}.propertyIsEnumerable,ef=Object.getOwnPropertyDescriptor,GE=ef&&!Zh.call({1:2},1);tf.f=GE?function(e){var t=ef(this,e);return!!t&&t.enumerable}:Zh});var na=b((g_,rf)=>{"use strict";rf.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var af=b((S_,sf)=>{"use strict";var zE=De(),WE=Ve(),QE=Yi(),Kl=Object,YE=zE("".split);sf.exports=WE(function(){return!Kl("z").propertyIsEnumerable(0)})?function(s){return QE(s)==="String"?YE(s,""):Kl(s)}:Kl});var Ir=b((v_,nf)=>{"use strict";nf.exports=function(s){return s==null}});var ki=b((y_,of)=>{"use strict";var KE=Ir(),XE=TypeError;of.exports=function(s){if(KE(s))throw new XE("Can't call method on "+s);return s}});var Ki=b((T_,uf)=>{"use strict";var JE=af(),ZE=ki();uf.exports=function(s){return JE(ZE(s))}});var vt=b((I_,lf)=>{"use strict";var ew=ye();lf.exports=function(s){return typeof s=="object"?s!==null:ew(s)}});var xr=b((x_,cf)=>{"use strict";cf.exports={}});var mi=b((E_,pf)=>{"use strict";var Xl=xr(),Jl=Ie(),tw=ye(),df=function(s){return tw(s)?s:void 0};pf.exports=function(s,e){return arguments.length<2?df(Xl[s])||df(Jl[s]):Xl[s]&&Xl[s][e]||Jl[s]&&Jl[s][e]}});var oa=b((w_,hf)=>{"use strict";var iw=De();hf.exports=iw({}.isPrototypeOf)});var Xi=b((P_,bf)=>{"use strict";var rw=Ie(),ff=rw.navigator,mf=ff&&ff.userAgent;bf.exports=mf?String(mf):""});var ec=b((A_,If)=>{"use strict";var Tf=Ie(),Zl=Xi(),gf=Tf.process,Sf=Tf.Deno,vf=gf&&gf.versions||Sf&&Sf.version,yf=vf&&vf.v8,Ct,Ao;yf&&(Ct=yf.split("."),Ao=Ct[0]>0&&Ct[0]<4?1:+(Ct[0]+Ct[1]));!Ao&&Zl&&(Ct=Zl.match(/Edge\/(\d+)/),(!Ct||Ct[1]>=74)&&(Ct=Zl.match(/Chrome\/(\d+)/),Ct&&(Ao=+Ct[1])));If.exports=Ao});var tc=b((k_,Ef)=>{"use strict";var xf=ec(),sw=Ve(),aw=Ie(),nw=aw.String;Ef.exports=!!Object.getOwnPropertySymbols&&!sw(function(){var s=Symbol("symbol detection");return!nw(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&xf&&xf<41})});var ic=b((R_,wf)=>{"use strict";var ow=tc();wf.exports=ow&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var rc=b((M_,Pf)=>{"use strict";var uw=mi(),lw=ye(),cw=oa(),dw=ic(),pw=Object;Pf.exports=dw?function(s){return typeof s=="symbol"}:function(s){var e=uw("Symbol");return lw(e)&&cw(e.prototype,pw(s))}});var ua=b((L_,Af)=>{"use strict";var hw=String;Af.exports=function(s){try{return hw(s)}catch(e){return"Object"}}});var jt=b((B_,kf)=>{"use strict";var fw=ye(),mw=ua(),bw=TypeError;kf.exports=function(s){if(fw(s))return s;throw new bw(mw(s)+" is not a function")}});var la=b((D_,Rf)=>{"use strict";var gw=jt(),Sw=Ir();Rf.exports=function(s,e){var t=s[e];return Sw(t)?void 0:gw(t)}});var Lf=b(($_,Mf)=>{"use strict";var sc=St(),ac=ye(),nc=vt(),vw=TypeError;Mf.exports=function(s,e){var t,i;if(e==="string"&&ac(t=s.toString)&&!nc(i=sc(t,s))||ac(t=s.valueOf)&&!nc(i=sc(t,s))||e!=="string"&&ac(t=s.toString)&&!nc(i=sc(t,s)))return i;throw new vw("Can't convert object to primitive value")}});var Vt=b((C_,Bf)=>{"use strict";Bf.exports=!0});var Cf=b((V_,$f)=>{"use strict";var Df=Ie(),yw=Object.defineProperty;$f.exports=function(s,e){try{yw(Df,s,{value:e,configurable:!0,writable:!0})}catch(t){Df[s]=e}return e}});var ca=b((O_,_f)=>{"use strict";var Tw=Vt(),Iw=Ie(),xw=Cf(),Vf="__core-js_shared__",Of=_f.exports=Iw[Vf]||xw(Vf,{});(Of.versions||(Of.versions=[])).push({version:"3.38.0",mode:Tw?"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 oc=b((__,Nf)=>{"use strict";var Ff=ca();Nf.exports=function(s,e){return Ff[s]||(Ff[s]=e||{})}});var Er=b((F_,Uf)=>{"use strict";var Ew=ki(),ww=Object;Uf.exports=function(s){return ww(Ew(s))}});var Ot=b((N_,qf)=>{"use strict";var Pw=De(),Aw=Er(),kw=Pw({}.hasOwnProperty);qf.exports=Object.hasOwn||function(e,t){return kw(Aw(e),t)}});var uc=b((U_,Hf)=>{"use strict";var Rw=De(),Mw=0,Lw=Math.random(),Bw=Rw(1 .toString);Hf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Bw(++Mw+Lw,36)}});var Oe=b((q_,Gf)=>{"use strict";var Dw=Ie(),$w=oc(),jf=Ot(),Cw=uc(),Vw=tc(),Ow=ic(),wr=Dw.Symbol,lc=$w("wks"),_w=Ow?wr.for||wr:wr&&wr.withoutSetter||Cw;Gf.exports=function(s){return jf(lc,s)||(lc[s]=Vw&&jf(wr,s)?wr[s]:_w("Symbol."+s)),lc[s]}});var Yf=b((H_,Qf)=>{"use strict";var Fw=St(),zf=vt(),Wf=rc(),Nw=la(),Uw=Lf(),qw=Oe(),Hw=TypeError,jw=qw("toPrimitive");Qf.exports=function(s,e){if(!zf(s)||Wf(s))return s;var t=Nw(s,jw),i;if(t){if(e===void 0&&(e="default"),i=Fw(t,s,e),!zf(i)||Wf(i))return i;throw new Hw("Can't convert object to primitive value")}return e===void 0&&(e="number"),Uw(s,e)}});var cc=b((j_,Kf)=>{"use strict";var Gw=Yf(),zw=rc();Kf.exports=function(s){var e=Gw(s,"string");return zw(e)?e:e+""}});var ko=b((G_,Jf)=>{"use strict";var Ww=Ie(),Xf=vt(),dc=Ww.document,Qw=Xf(dc)&&Xf(dc.createElement);Jf.exports=function(s){return Qw?dc.createElement(s):{}}});var pc=b((z_,Zf)=>{"use strict";var Yw=gt(),Kw=Ve(),Xw=ko();Zf.exports=!Yw&&!Kw(function(){return Object.defineProperty(Xw("div"),"a",{get:function(){return 7}}).a!==7})});var im=b(tm=>{"use strict";var Jw=gt(),Zw=St(),eP=Yl(),tP=na(),iP=Ki(),rP=cc(),sP=Ot(),aP=pc(),em=Object.getOwnPropertyDescriptor;tm.f=Jw?em:function(e,t){if(e=iP(e),t=rP(t),aP)try{return em(e,t)}catch(i){}if(sP(e,t))return tP(!Zw(eP.f,e,t),e[t])}});var hc=b((Q_,rm)=>{"use strict";var nP=Ve(),oP=ye(),uP=/#|\.prototype\./,da=function(s,e){var t=cP[lP(s)];return t===pP?!0:t===dP?!1:oP(e)?nP(e):!!e},lP=da.normalize=function(s){return String(s).replace(uP,".").toLowerCase()},cP=da.data={},dP=da.NATIVE="N",pP=da.POLYFILL="P";rm.exports=da});var Pr=b((Y_,am)=>{"use strict";var sm=Wl(),hP=jt(),fP=aa(),mP=sm(sm.bind);am.exports=function(s,e){return hP(s),e===void 0?s:fP?mP(s,e):function(){return s.apply(e,arguments)}}});var fc=b((K_,nm)=>{"use strict";var bP=gt(),gP=Ve();nm.exports=bP&&gP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Gt=b((X_,om)=>{"use strict";var SP=vt(),vP=String,yP=TypeError;om.exports=function(s){if(SP(s))return s;throw new yP(vP(s)+" is not an object")}});var Ji=b(lm=>{"use strict";var TP=gt(),IP=pc(),xP=fc(),Ro=Gt(),um=cc(),EP=TypeError,mc=Object.defineProperty,wP=Object.getOwnPropertyDescriptor,bc="enumerable",gc="configurable",Sc="writable";lm.f=TP?xP?function(e,t,i){if(Ro(e),t=um(t),Ro(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Sc in i&&!i[Sc]){var r=wP(e,t);r&&r[Sc]&&(e[t]=i.value,i={configurable:gc in i?i[gc]:r[gc],enumerable:bc in i?i[bc]:r[bc],writable:!1})}return mc(e,t,i)}:mc:function(e,t,i){if(Ro(e),t=um(t),Ro(i),IP)try{return mc(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new EP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ar=b((Z_,cm)=>{"use strict";var PP=gt(),AP=Ji(),kP=na();cm.exports=PP?function(s,e,t){return AP.f(s,e,kP(1,t))}:function(s,e,t){return s[e]=t,s}});var we=b((eF,pm)=>{"use strict";var pa=Ie(),RP=Gl(),MP=Wl(),LP=ye(),BP=im().f,DP=hc(),kr=xr(),$P=Pr(),Rr=Ar(),dm=Ot();ca();var CP=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 RP(s,this,arguments)};return e.prototype=s.prototype,e};pm.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?pa:r?pa[t]:pa[t]&&pa[t].prototype,o=i?kr:kr[t]||Rr(kr,t,{})[t],u=o.prototype,l,d,c,h,p,f,m,g,S;for(h in e)l=DP(i?h:t+(r?".":"#")+h,s.forced),d=!l&&n&&dm(n,h),f=o[h],d&&(s.dontCallGetSet?(S=BP(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=$P(p,pa):s.wrap&&d?g=CP(p):a&&LP(p)?g=MP(p):g=p,(s.sham||p&&p.sham||f&&f.sham)&&Rr(g,"sham",!0),Rr(o,h,g),a&&(c=t+"Prototype",dm(kr,c)||Rr(kr,c,{}),Rr(kr[c],h,p),s.real&&u&&(l||!u[h])&&Rr(u,h,p)))}});var fm=b((tF,hm)=>{"use strict";var VP=Math.ceil,OP=Math.floor;hm.exports=Math.trunc||function(e){var t=+e;return(t>0?OP:VP)(t)}});var ha=b((iF,mm)=>{"use strict";var _P=fm();mm.exports=function(s){var e=+s;return e!==e||e===0?0:_P(e)}});var gm=b((rF,bm)=>{"use strict";var FP=ha(),NP=Math.max,UP=Math.min;bm.exports=function(s,e){var t=FP(s);return t<0?NP(t+e,0):UP(t,e)}});var vc=b((sF,Sm)=>{"use strict";var qP=ha(),HP=Math.min;Sm.exports=function(s){var e=qP(s);return e>0?HP(e,9007199254740991):0}});var Mr=b((aF,vm)=>{"use strict";var jP=vc();vm.exports=function(s){return jP(s.length)}});var yc=b((nF,Tm)=>{"use strict";var GP=Ki(),zP=gm(),WP=Mr(),ym=function(s){return function(e,t,i){var r=GP(e),a=WP(r);if(a===0)return!s&&-1;var n=zP(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}};Tm.exports={includes:ym(!0),indexOf:ym(!1)}});var fa=b((oF,Im)=>{"use strict";Im.exports=function(){}});var xm=b(()=>{"use strict";var QP=we(),YP=yc().includes,KP=Ve(),XP=fa(),JP=KP(function(){return!Array(1).includes()});QP({target:"Array",proto:!0,forced:JP},{includes:function(e){return YP(this,e,arguments.length>1?arguments[1]:void 0)}});XP("includes")});var Ri=b((cF,Em)=>{"use strict";var ZP=mi();Em.exports=ZP});var Pm=b((dF,wm)=>{"use strict";xm();var eA=Ri();wm.exports=eA("Array","includes")});var km=b((pF,Am)=>{"use strict";var tA=Pm();Am.exports=tA});var xt=b((hF,Rm)=>{"use strict";var iA=km();Rm.exports=iA});var Bo=b((xF,Vm)=>{"use strict";var cA=oc(),dA=uc(),Cm=cA("keys");Vm.exports=function(s){return Cm[s]||(Cm[s]=dA(s))}});var _m=b((EF,Om)=>{"use strict";var pA=Ve();Om.exports=!pA(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Do=b((wF,Nm)=>{"use strict";var hA=Ot(),fA=ye(),mA=Er(),bA=Bo(),gA=_m(),Fm=bA("IE_PROTO"),xc=Object,SA=xc.prototype;Nm.exports=gA?xc.getPrototypeOf:function(s){var e=mA(s);if(hA(e,Fm))return e[Fm];var t=e.constructor;return fA(t)&&e instanceof t?t.prototype:e instanceof xc?SA:null}});var $o=b((PF,Um)=>{"use strict";Um.exports={}});var jm=b((AF,Hm)=>{"use strict";var vA=De(),Ec=Ot(),yA=Ki(),TA=yc().indexOf,IA=$o(),qm=vA([].push);Hm.exports=function(s,e){var t=yA(s),i=0,r=[],a;for(a in t)!Ec(IA,a)&&Ec(t,a)&&qm(r,a);for(;e.length>i;)Ec(t,a=e[i++])&&(~TA(r,a)||qm(r,a));return r}});var wc=b((kF,Gm)=>{"use strict";Gm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Pc=b((RF,zm)=>{"use strict";var xA=jm(),EA=wc();zm.exports=Object.keys||function(e){return xA(e,EA)}});var Ac=b((MF,Xm)=>{"use strict";var Qm=gt(),wA=Ve(),Ym=De(),PA=Do(),AA=Pc(),kA=Ki(),RA=Yl().f,Km=Ym(RA),MA=Ym([].push),LA=Qm&&wA(function(){var s=Object.create(null);return s[2]=2,!Km(s,2)}),Wm=function(s){return function(e){for(var t=kA(e),i=AA(t),r=LA&&PA(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!Qm||(r?u in t:Km(t,u)))&&MA(o,s?[u,t[u]]:t[u]);return o}};Xm.exports={entries:Wm(!0),values:Wm(!1)}});var Jm=b(()=>{"use strict";var BA=we(),DA=Ac().entries;BA({target:"Object",stat:!0},{entries:function(e){return DA(e)}})});var eb=b((DF,Zm)=>{"use strict";Jm();var $A=xr();Zm.exports=$A.Object.entries});var ib=b(($F,tb)=>{"use strict";var CA=eb();tb.exports=CA});var Lr=b((CF,rb)=>{"use strict";var VA=ib();rb.exports=VA});var Zi=b((VF,sb)=>{"use strict";sb.exports={}});var ob=b((OF,nb)=>{"use strict";var OA=Ie(),_A=ye(),ab=OA.WeakMap;nb.exports=_A(ab)&&/native code/.test(String(ab))});var Lc=b((_F,cb)=>{"use strict";var FA=ob(),lb=Ie(),NA=vt(),UA=Ar(),kc=Ot(),Rc=ca(),qA=Bo(),HA=$o(),ub="Object already initialized",Mc=lb.TypeError,jA=lb.WeakMap,Co,ma,Vo,GA=function(s){return Vo(s)?ma(s):Co(s,{})},zA=function(s){return function(e){var t;if(!NA(e)||(t=ma(e)).type!==s)throw new Mc("Incompatible receiver, "+s+" required");return t}};FA||Rc.state?(_t=Rc.state||(Rc.state=new jA),_t.get=_t.get,_t.has=_t.has,_t.set=_t.set,Co=function(s,e){if(_t.has(s))throw new Mc(ub);return e.facade=s,_t.set(s,e),e},ma=function(s){return _t.get(s)||{}},Vo=function(s){return _t.has(s)}):(er=qA("state"),HA[er]=!0,Co=function(s,e){if(kc(s,er))throw new Mc(ub);return e.facade=s,UA(s,er,e),e},ma=function(s){return kc(s,er)?s[er]:{}},Vo=function(s){return kc(s,er)});var _t,er;cb.exports={set:Co,get:ma,has:Vo,enforce:GA,getterFor:zA}});var $c=b((FF,pb)=>{"use strict";var Bc=gt(),WA=Ot(),db=Function.prototype,QA=Bc&&Object.getOwnPropertyDescriptor,Dc=WA(db,"name"),YA=Dc&&function(){}.name==="something",KA=Dc&&(!Bc||Bc&&QA(db,"name").configurable);pb.exports={EXISTS:Dc,PROPER:YA,CONFIGURABLE:KA}});var fb=b(hb=>{"use strict";var XA=gt(),JA=fc(),ZA=Ji(),ek=Gt(),tk=Ki(),ik=Pc();hb.f=XA&&!JA?Object.defineProperties:function(e,t){ek(e);for(var i=tk(t),r=ik(t),a=r.length,n=0,o;a>n;)ZA.f(e,o=r[n++],i[o]);return e}});var Cc=b((UF,mb)=>{"use strict";var rk=mi();mb.exports=rk("document","documentElement")});var Fc=b((qF,Ib)=>{"use strict";var sk=Gt(),ak=fb(),bb=wc(),nk=$o(),ok=Cc(),uk=ko(),lk=Bo(),gb=">",Sb="<",Oc="prototype",_c="script",yb=lk("IE_PROTO"),Vc=function(){},Tb=function(s){return Sb+_c+gb+s+Sb+"/"+_c+gb},vb=function(s){s.write(Tb("")),s.close();var e=s.parentWindow.Object;return s=null,e},ck=function(){var s=uk("iframe"),e="java"+_c+":",t;return s.style.display="none",ok.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Tb("document.F=Object")),t.close(),t.F},Oo,_o=function(){try{Oo=new ActiveXObject("htmlfile")}catch(e){}_o=typeof document!="undefined"?document.domain&&Oo?vb(Oo):ck():vb(Oo);for(var s=bb.length;s--;)delete _o[Oc][bb[s]];return _o()};nk[yb]=!0;Ib.exports=Object.create||function(e,t){var i;return e!==null?(Vc[Oc]=sk(e),i=new Vc,Vc[Oc]=null,i[yb]=e):i=_o(),t===void 0?i:ak.f(i,t)}});var Br=b((HF,xb)=>{"use strict";var dk=Ar();xb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:dk(s,e,t),s}});var Hc=b((jF,Pb)=>{"use strict";var pk=Ve(),hk=ye(),fk=vt(),mk=Fc(),Eb=Do(),bk=Br(),gk=Oe(),Sk=Vt(),qc=gk("iterator"),wb=!1,bi,Nc,Uc;[].keys&&(Uc=[].keys(),"next"in Uc?(Nc=Eb(Eb(Uc)),Nc!==Object.prototype&&(bi=Nc)):wb=!0);var vk=!fk(bi)||pk(function(){var s={};return bi[qc].call(s)!==s});vk?bi={}:Sk&&(bi=mk(bi));hk(bi[qc])||bk(bi,qc,function(){return this});Pb.exports={IteratorPrototype:bi,BUGGY_SAFARI_ITERATORS:wb}});var Fo=b((GF,kb)=>{"use strict";var yk=Oe(),Tk=yk("toStringTag"),Ab={};Ab[Tk]="z";kb.exports=String(Ab)==="[object z]"});var ba=b((zF,Rb)=>{"use strict";var Ik=Fo(),xk=ye(),No=Yi(),Ek=Oe(),wk=Ek("toStringTag"),Pk=Object,Ak=No(function(){return arguments}())==="Arguments",kk=function(s,e){try{return s[e]}catch(t){}};Rb.exports=Ik?No:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=kk(e=Pk(s),wk))=="string"?t:Ak?No(e):(i=No(e))==="Object"&&xk(e.callee)?"Arguments":i}});var Lb=b((WF,Mb)=>{"use strict";var Rk=Fo(),Mk=ba();Mb.exports=Rk?{}.toString:function(){return"[object "+Mk(this)+"]"}});var ga=b((QF,Db)=>{"use strict";var Lk=Fo(),Bk=Ji().f,Dk=Ar(),$k=Ot(),Ck=Lb(),Vk=Oe(),Bb=Vk("toStringTag");Db.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&($k(r,Bb)||Bk(r,Bb,{configurable:!0,value:e}),i&&!Lk&&Dk(r,"toString",Ck))}});var Cb=b((YF,$b)=>{"use strict";var Ok=Hc().IteratorPrototype,_k=Fc(),Fk=na(),Nk=ga(),Uk=Zi(),qk=function(){return this};$b.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=_k(Ok,{next:Fk(+!i,t)}),Nk(s,r,!1,!0),Uk[r]=qk,s}});var Ob=b((KF,Vb)=>{"use strict";var Hk=De(),jk=jt();Vb.exports=function(s,e,t){try{return Hk(jk(Object.getOwnPropertyDescriptor(s,e)[t]))}catch(i){}}});var Fb=b((XF,_b)=>{"use strict";var Gk=vt();_b.exports=function(s){return Gk(s)||s===null}});var Ub=b((JF,Nb)=>{"use strict";var zk=Fb(),Wk=String,Qk=TypeError;Nb.exports=function(s){if(zk(s))return s;throw new Qk("Can't set "+Wk(s)+" as a prototype")}});var jc=b((ZF,qb)=>{"use strict";var Yk=Ob(),Kk=vt(),Xk=ki(),Jk=Ub();qb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=Yk(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch(i){}return function(r,a){return Xk(r),Jk(a),Kk(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var Zb=b((eN,Jb)=>{"use strict";var Zk=we(),eR=St(),Uo=Vt(),Kb=$c(),tR=ye(),iR=Cb(),Hb=Do(),jb=jc(),rR=ga(),sR=Ar(),Gc=Br(),aR=Oe(),Gb=Zi(),Xb=Hc(),nR=Kb.PROPER,oR=Kb.CONFIGURABLE,zb=Xb.IteratorPrototype,qo=Xb.BUGGY_SAFARI_ITERATORS,Sa=aR("iterator"),Wb="keys",va="values",Qb="entries",Yb=function(){return this};Jb.exports=function(s,e,t,i,r,a,n){iR(t,e,i);var o=function(S){if(S===r&&h)return h;if(!qo&&S&&S in d)return d[S];switch(S){case Wb:return function(){return new t(this,S)};case va:return function(){return new t(this,S)};case Qb:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=s.prototype,c=d[Sa]||d["@@iterator"]||r&&d[r],h=!qo&&c||o(r),p=e==="Array"&&d.entries||c,f,m,g;if(p&&(f=Hb(p.call(new s)),f!==Object.prototype&&f.next&&(!Uo&&Hb(f)!==zb&&(jb?jb(f,zb):tR(f[Sa])||Gc(f,Sa,Yb)),rR(f,u,!0,!0),Uo&&(Gb[u]=Yb))),nR&&r===va&&c&&c.name!==va&&(!Uo&&oR?sR(d,"name",va):(l=!0,h=function(){return eR(c,this)})),r)if(m={values:o(va),keys:a?h:o(Wb),entries:o(Qb)},n)for(g in m)(qo||l||!(g in d))&&Gc(d,g,m[g]);else Zk({target:e,proto:!0,forced:qo||l},m);return(!Uo||n)&&d[Sa]!==h&&Gc(d,Sa,h,{name:r}),Gb[e]=h,m}});var tg=b((tN,eg)=>{"use strict";eg.exports=function(s,e){return{value:s,done:e}}});var Wc=b((iN,ng)=>{"use strict";var uR=Ki(),zc=fa(),ig=Zi(),sg=Lc(),lR=Ji().f,cR=Zb(),Ho=tg(),dR=Vt(),pR=gt(),ag="Array Iterator",hR=sg.set,fR=sg.getterFor(ag);ng.exports=cR(Array,"Array",function(s,e){hR(this,{type:ag,target:uR(s),index:0,kind:e})},function(){var s=fR(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 rg=ig.Arguments=ig.Array;zc("keys");zc("values");zc("entries");if(!dR&&pR&&rg.name!=="values")try{lR(rg,"name",{value:"values"})}catch(s){}});var ug=b((rN,og)=>{"use strict";var mR=Oe(),bR=Zi(),gR=mR("iterator"),SR=Array.prototype;og.exports=function(s){return s!==void 0&&(bR.Array===s||SR[gR]===s)}});var Qc=b((sN,cg)=>{"use strict";var vR=ba(),lg=la(),yR=Ir(),TR=Zi(),IR=Oe(),xR=IR("iterator");cg.exports=function(s){if(!yR(s))return lg(s,xR)||lg(s,"@@iterator")||TR[vR(s)]}});var pg=b((aN,dg)=>{"use strict";var ER=St(),wR=jt(),PR=Gt(),AR=ua(),kR=Qc(),RR=TypeError;dg.exports=function(s,e){var t=arguments.length<2?kR(s):e;if(wR(t))return PR(ER(t,s));throw new RR(AR(s)+" is not iterable")}});var mg=b((nN,fg)=>{"use strict";var MR=St(),hg=Gt(),LR=la();fg.exports=function(s,e,t){var i,r;hg(s);try{if(i=LR(s,"return"),!i){if(e==="throw")throw t;return t}i=MR(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return hg(i),t}});var Go=b((oN,vg)=>{"use strict";var BR=Pr(),DR=St(),$R=Gt(),CR=ua(),VR=ug(),OR=Mr(),bg=oa(),_R=pg(),FR=Qc(),gg=mg(),NR=TypeError,jo=function(s,e){this.stopped=s,this.result=e},Sg=jo.prototype;vg.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=BR(e,i),l,d,c,h,p,f,m,g=function(y){return l&&gg(l,"normal",y),new jo(!0,y)},S=function(y){return r?($R(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=FR(s),!d)throw new NR(CR(s)+" is not iterable");if(VR(d)){for(c=0,h=OR(s);h>c;c++)if(p=S(s[c]),p&&bg(Sg,p))return p;return new jo(!1)}l=_R(s,d)}for(f=a?s.next:l.next;!(m=DR(f,l)).done;){try{p=S(m.value)}catch(y){gg(l,"throw",y)}if(typeof p=="object"&&p&&bg(Sg,p))return p}return new jo(!1)}});var Tg=b((uN,yg)=>{"use strict";var UR=gt(),qR=Ji(),HR=na();yg.exports=function(s,e,t){UR?qR.f(s,e,HR(0,t)):s[e]=t}});var Ig=b(()=>{"use strict";var jR=we(),GR=Go(),zR=Tg();jR({target:"Object",stat:!0},{fromEntries:function(e){var t={};return GR(e,function(i,r){zR(t,i,r)},{AS_ENTRIES:!0}),t}})});var Eg=b((dN,xg)=>{"use strict";Wc();Ig();var WR=xr();xg.exports=WR.Object.fromEntries});var Pg=b((pN,wg)=>{"use strict";wg.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 kg=b(()=>{"use strict";Wc();var QR=Pg(),YR=Ie(),KR=ga(),Ag=Zi();for(zo in QR)KR(YR[zo],zo),Ag[zo]=Ag.Array;var zo});var Mg=b((mN,Rg)=>{"use strict";var XR=Eg();kg();Rg.exports=XR});var Yc=b((bN,Lg)=>{"use strict";var JR=Mg();Lg.exports=JR});var Bg=b(()=>{"use strict"});var Kc=b((vN,Dg)=>{"use strict";var ya=Ie(),ZR=Xi(),eM=Yi(),Wo=function(s){return ZR.slice(0,s.length)===s};Dg.exports=function(){return Wo("Bun/")?"BUN":Wo("Cloudflare-Workers")?"CLOUDFLARE":Wo("Deno/")?"DENO":Wo("Node.js/")?"NODE":ya.Bun&&typeof Bun.version=="string"?"BUN":ya.Deno&&typeof Deno.version=="object"?"DENO":eM(ya.process)==="process"?"NODE":ya.window&&ya.document?"BROWSER":"REST"}()});var Qo=b((yN,$g)=>{"use strict";var tM=Kc();$g.exports=tM==="NODE"});var Vg=b((TN,Cg)=>{"use strict";var iM=Ji();Cg.exports=function(s,e,t){return iM.f(s,e,t)}});var Fg=b((IN,_g)=>{"use strict";var rM=mi(),sM=Vg(),aM=Oe(),nM=gt(),Og=aM("species");_g.exports=function(s){var e=rM(s);nM&&e&&!e[Og]&&sM(e,Og,{configurable:!0,get:function(){return this}})}});var Ug=b((xN,Ng)=>{"use strict";var oM=oa(),uM=TypeError;Ng.exports=function(s,e){if(oM(e,s))return s;throw new uM("Incorrect invocation")}});var Jc=b((EN,qg)=>{"use strict";var lM=De(),cM=ye(),Xc=ca(),dM=lM(Function.toString);cM(Xc.inspectSource)||(Xc.inspectSource=function(s){return dM(s)});qg.exports=Xc.inspectSource});var ed=b((wN,Wg)=>{"use strict";var pM=De(),hM=Ve(),Hg=ye(),fM=ba(),mM=mi(),bM=Jc(),jg=function(){},Gg=mM("Reflect","construct"),Zc=/^\s*(?:class|function)\b/,gM=pM(Zc.exec),SM=!Zc.test(jg),Ta=function(e){if(!Hg(e))return!1;try{return Gg(jg,[],e),!0}catch(t){return!1}},zg=function(e){if(!Hg(e))return!1;switch(fM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return SM||!!gM(Zc,bM(e))}catch(t){return!0}};zg.sham=!0;Wg.exports=!Gg||hM(function(){var s;return Ta(Ta.call)||!Ta(Object)||!Ta(function(){s=!0})||s})?zg:Ta});var Yg=b((PN,Qg)=>{"use strict";var vM=ed(),yM=ua(),TM=TypeError;Qg.exports=function(s){if(vM(s))return s;throw new TM(yM(s)+" is not a constructor")}});var td=b((AN,Xg)=>{"use strict";var Kg=Gt(),IM=Yg(),xM=Ir(),EM=Oe(),wM=EM("species");Xg.exports=function(s,e){var t=Kg(s).constructor,i;return t===void 0||xM(i=Kg(t)[wM])?e:IM(i)}});var Zg=b((kN,Jg)=>{"use strict";var PM=De();Jg.exports=PM([].slice)});var tS=b((RN,eS)=>{"use strict";var AM=TypeError;eS.exports=function(s,e){if(s<e)throw new AM("Not enough arguments");return s}});var id=b((MN,iS)=>{"use strict";var kM=Xi();iS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(kM)});var dd=b((LN,dS)=>{"use strict";var yt=Ie(),RM=Gl(),MM=Pr(),rS=ye(),LM=Ot(),cS=Ve(),sS=Cc(),BM=Zg(),aS=ko(),DM=tS(),$M=id(),CM=Qo(),ud=yt.setImmediate,ld=yt.clearImmediate,VM=yt.process,rd=yt.Dispatch,OM=yt.Function,nS=yt.MessageChannel,_M=yt.String,sd=0,Ia={},oS="onreadystatechange",xa,tr,ad,nd;cS(function(){xa=yt.location});var cd=function(s){if(LM(Ia,s)){var e=Ia[s];delete Ia[s],e()}},od=function(s){return function(){cd(s)}},uS=function(s){cd(s.data)},lS=function(s){yt.postMessage(_M(s),xa.protocol+"//"+xa.host)};(!ud||!ld)&&(ud=function(e){DM(arguments.length,1);var t=rS(e)?e:OM(e),i=BM(arguments,1);return Ia[++sd]=function(){RM(t,void 0,i)},tr(sd),sd},ld=function(e){delete Ia[e]},CM?tr=function(s){VM.nextTick(od(s))}:rd&&rd.now?tr=function(s){rd.now(od(s))}:nS&&!$M?(ad=new nS,nd=ad.port2,ad.port1.onmessage=uS,tr=MM(nd.postMessage,nd)):yt.addEventListener&&rS(yt.postMessage)&&!yt.importScripts&&xa&&xa.protocol!=="file:"&&!cS(lS)?(tr=lS,yt.addEventListener("message",uS,!1)):oS in aS("script")?tr=function(s){sS.appendChild(aS("script"))[oS]=function(){sS.removeChild(this),cd(s)}}:tr=function(s){setTimeout(od(s),0)});dS.exports={set:ud,clear:ld}});var fS=b((BN,hS)=>{"use strict";var pS=Ie(),FM=gt(),NM=Object.getOwnPropertyDescriptor;hS.exports=function(s){if(!FM)return pS[s];var e=NM(pS,s);return e&&e.value}});var pd=b((DN,bS)=>{"use strict";var mS=function(){this.head=null,this.tail=null};mS.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}}};bS.exports=mS});var SS=b(($N,gS)=>{"use strict";var UM=Xi();gS.exports=/ipad|iphone|ipod/i.test(UM)&&typeof Pebble!="undefined"});var yS=b((CN,vS)=>{"use strict";var qM=Xi();vS.exports=/web0s(?!.*chrome)/i.test(qM)});var AS=b((VN,PS)=>{"use strict";var $r=Ie(),HM=fS(),TS=Pr(),hd=dd().set,jM=pd(),GM=id(),zM=SS(),WM=yS(),fd=Qo(),IS=$r.MutationObserver||$r.WebKitMutationObserver,xS=$r.document,ES=$r.process,Yo=$r.Promise,gd=HM("queueMicrotask"),Dr,md,bd,Ko,wS;gd||(Ea=new jM,wa=function(){var s,e;for(fd&&(s=ES.domain)&&s.exit();e=Ea.get();)try{e()}catch(t){throw Ea.head&&Dr(),t}s&&s.enter()},!GM&&!fd&&!WM&&IS&&xS?(md=!0,bd=xS.createTextNode(""),new IS(wa).observe(bd,{characterData:!0}),Dr=function(){bd.data=md=!md}):!zM&&Yo&&Yo.resolve?(Ko=Yo.resolve(void 0),Ko.constructor=Yo,wS=TS(Ko.then,Ko),Dr=function(){wS(wa)}):fd?Dr=function(){ES.nextTick(wa)}:(hd=TS(hd,$r),Dr=function(){hd(wa)}),gd=function(s){Ea.head||Dr(),Ea.add(s)});var Ea,wa;PS.exports=gd});var RS=b((ON,kS)=>{"use strict";kS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch(t){}}});var Xo=b((_N,MS)=>{"use strict";MS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var ir=b((FN,LS)=>{"use strict";var QM=Ie();LS.exports=QM.Promise});var Cr=b((NN,CS)=>{"use strict";var YM=Ie(),Pa=ir(),KM=ye(),XM=hc(),JM=Jc(),ZM=Oe(),BS=Kc(),eL=Vt(),Sd=ec(),DS=Pa&&Pa.prototype,tL=ZM("species"),vd=!1,$S=KM(YM.PromiseRejectionEvent),iL=XM("Promise",function(){var s=JM(Pa),e=s!==String(Pa);if(!e&&Sd===66||eL&&!(DS.catch&&DS.finally))return!0;if(!Sd||Sd<51||!/native code/.test(s)){var t=new Pa(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[tL]=i,vd=t.then(function(){})instanceof i,!vd)return!0}return!e&&(BS==="BROWSER"||BS==="DENO")&&!$S});CS.exports={CONSTRUCTOR:iL,REJECTION_EVENT:$S,SUBCLASSING:vd}});var Vr=b((UN,OS)=>{"use strict";var VS=jt(),rL=TypeError,sL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new rL("Bad Promise constructor");e=i,t=r}),this.resolve=VS(e),this.reject=VS(t)};OS.exports.f=function(s){return new sL(s)}});var iv=b(()=>{"use strict";var aL=we(),nL=Vt(),tu=Qo(),Mi=Ie(),Nr=St(),_S=Br(),FS=jc(),oL=ga(),uL=Fg(),lL=jt(),eu=ye(),cL=vt(),dL=Ug(),pL=td(),jS=dd().set,Ed=AS(),hL=RS(),fL=Xo(),mL=pd(),GS=Lc(),iu=ir(),wd=Cr(),zS=Vr(),ru="Promise",WS=wd.CONSTRUCTOR,bL=wd.REJECTION_EVENT,gL=wd.SUBCLASSING,yd=GS.getterFor(ru),SL=GS.set,Or=iu&&iu.prototype,rr=iu,Jo=Or,QS=Mi.TypeError,Td=Mi.document,Pd=Mi.process,Id=zS.f,vL=Id,yL=!!(Td&&Td.createEvent&&Mi.dispatchEvent),YS="unhandledrejection",TL="rejectionhandled",NS=0,KS=1,IL=2,Ad=1,XS=2,Zo,US,xL,qS,JS=function(s){var e;return cL(s)&&eu(e=s.then)?e:!1},ZS=function(s,e){var t=e.value,i=e.state===KS,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,d;try{r?(i||(e.rejection===XS&&wL(e),e.rejection=Ad),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===s.promise?n(new QS("Promise-chain cycle")):(l=JS(u))?Nr(l,u,a,n):a(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},ev=function(s,e){s.notified||(s.notified=!0,Ed(function(){for(var t=s.reactions,i;i=t.get();)ZS(i,s);s.notified=!1,e&&!s.rejection&&EL(s)}))},tv=function(s,e,t){var i,r;yL?(i=Td.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Mi.dispatchEvent(i)):i={promise:e,reason:t},!bL&&(r=Mi["on"+s])?r(i):s===YS&&hL("Unhandled promise rejection",t)},EL=function(s){Nr(jS,Mi,function(){var e=s.facade,t=s.value,i=HS(s),r;if(i&&(r=fL(function(){tu?Pd.emit("unhandledRejection",t,e):tv(YS,e,t)}),s.rejection=tu||HS(s)?XS:Ad,r.error))throw r.value})},HS=function(s){return s.rejection!==Ad&&!s.parent},wL=function(s){Nr(jS,Mi,function(){var e=s.facade;tu?Pd.emit("rejectionHandled",e):tv(TL,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=IL,ev(s,!0))},xd=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new QS("Promise can't be resolved itself");var i=JS(e);i?Ed(function(){var r={done:!1};try{Nr(i,e,_r(xd,r,s),_r(Fr,r,s))}catch(a){Fr(r,a,s)}}):(s.value=e,s.state=KS,ev(s,!1))}catch(r){Fr({done:!1},r,s)}}};if(WS&&(rr=function(e){dL(this,Jo),lL(e),Nr(Zo,this);var t=yd(this);try{e(_r(xd,t),_r(Fr,t))}catch(i){Fr(t,i)}},Jo=rr.prototype,Zo=function(e){SL(this,{type:ru,done:!1,notified:!1,parent:!1,reactions:new mL,rejection:!1,state:NS,value:void 0})},Zo.prototype=_S(Jo,"then",function(e,t){var i=yd(this),r=Id(pL(this,rr));return i.parent=!0,r.ok=eu(e)?e:!0,r.fail=eu(t)&&t,r.domain=tu?Pd.domain:void 0,i.state===NS?i.reactions.add(r):Ed(function(){ZS(r,i)}),r.promise}),US=function(){var s=new Zo,e=yd(s);this.promise=s,this.resolve=_r(xd,e),this.reject=_r(Fr,e)},zS.f=Id=function(s){return s===rr||s===xL?new US(s):vL(s)},!nL&&eu(iu)&&Or!==Object.prototype)){qS=Or.then,gL||_S(Or,"then",function(e,t){var i=this;return new rr(function(r,a){Nr(qS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Or.constructor}catch(s){}FS&&FS(Or,Jo)}aL({global:!0,constructor:!0,wrap:!0,forced:WS},{Promise:rr});oL(rr,ru,!1,!0);uL(ru)});var ov=b((jN,nv)=>{"use strict";var PL=Oe(),sv=PL("iterator"),av=!1;try{rv=0,kd={next:function(){return{done:!!rv++}},return:function(){av=!0}},kd[sv]=function(){return this},Array.from(kd,function(){throw 2})}catch(s){}var rv,kd;nv.exports=function(s,e){try{if(!e&&!av)return!1}catch(r){return!1}var t=!1;try{var i={};i[sv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t}});var Rd=b((GN,uv)=>{"use strict";var AL=ir(),kL=ov(),RL=Cr().CONSTRUCTOR;uv.exports=RL||!kL(function(s){AL.all(s).then(void 0,function(){})})});var lv=b(()=>{"use strict";var ML=we(),LL=St(),BL=jt(),DL=Vr(),$L=Xo(),CL=Go(),VL=Rd();ML({target:"Promise",stat:!0,forced:VL},{all:function(e){var t=this,i=DL.f(t),r=i.resolve,a=i.reject,n=$L(function(){var o=BL(t.resolve),u=[],l=0,d=1;CL(e,function(c){var h=l++,p=!1;d++,LL(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 dv=b(()=>{"use strict";var OL=we(),_L=Vt(),FL=Cr().CONSTRUCTOR,Ld=ir(),NL=mi(),UL=ye(),qL=Br(),cv=Ld&&Ld.prototype;OL({target:"Promise",proto:!0,forced:FL,real:!0},{catch:function(s){return this.then(void 0,s)}});!_L&&UL(Ld)&&(Md=NL("Promise").prototype.catch,cv.catch!==Md&&qL(cv,"catch",Md,{unsafe:!0}));var Md});var pv=b(()=>{"use strict";var HL=we(),jL=St(),GL=jt(),zL=Vr(),WL=Xo(),QL=Go(),YL=Rd();HL({target:"Promise",stat:!0,forced:YL},{race:function(e){var t=this,i=zL.f(t),r=i.reject,a=WL(function(){var n=GL(t.resolve);QL(e,function(o){jL(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var hv=b(()=>{"use strict";var KL=we(),XL=Vr(),JL=Cr().CONSTRUCTOR;KL({target:"Promise",stat:!0,forced:JL},{reject:function(e){var t=XL.f(this),i=t.reject;return i(e),t.promise}})});var Bd=b((eU,fv)=>{"use strict";var ZL=Gt(),eB=vt(),tB=Vr();fv.exports=function(s,e){if(ZL(s),eB(e)&&e.constructor===s)return e;var t=tB.f(s),i=t.resolve;return i(e),t.promise}});var gv=b(()=>{"use strict";var iB=we(),rB=mi(),mv=Vt(),sB=ir(),bv=Cr().CONSTRUCTOR,aB=Bd(),nB=rB("Promise"),oB=mv&&!bv;iB({target:"Promise",stat:!0,forced:mv||bv},{resolve:function(e){return aB(oB&&this===nB?sB:this,e)}})});var Sv=b(()=>{"use strict";iv();lv();dv();pv();hv();gv()});var Iv=b(()=>{"use strict";var uB=we(),lB=Vt(),su=ir(),cB=Ve(),yv=mi(),Tv=ye(),dB=td(),vv=Bd(),pB=Br(),$d=su&&su.prototype,hB=!!su&&cB(function(){$d.finally.call({then:function(){}},function(){})});uB({target:"Promise",proto:!0,real:!0,forced:hB},{finally:function(s){var e=dB(this,yv("Promise")),t=Tv(s);return this.then(t?function(i){return vv(e,s()).then(function(){return i})}:s,t?function(i){return vv(e,s()).then(function(){throw i})}:s)}});!lB&&Tv(su)&&(Dd=yv("Promise").prototype.finally,$d.finally!==Dd&&pB($d,"finally",Dd,{unsafe:!0}));var Dd});var Ev=b((oU,xv)=>{"use strict";Bg();Sv();Iv();var fB=Ri();xv.exports=fB("Promise","finally")});var Pv=b((uU,wv)=>{"use strict";var mB=Ev();wv.exports=mB});var Aa=b((lU,Av)=>{"use strict";var bB=Pv();Av.exports=bB});var _v=b(()=>{"use strict";var LB=we(),BB=Ac().values;LB({target:"Object",stat:!0},{values:function(e){return BB(e)}})});var Nv=b((zU,Fv)=>{"use strict";_v();var DB=xr();Fv.exports=DB.Object.values});var qv=b((WU,Uv)=>{"use strict";var $B=Nv();Uv.exports=$B});var nr=b((QU,Hv)=>{"use strict";var CB=qv();Hv.exports=CB});var ay=b(()=>{"use strict";var aD=we(),nD=Er(),oD=Mr(),uD=ha(),lD=fa();aD({target:"Array",proto:!0},{at:function(e){var t=nD(this),i=oD(t),r=uD(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});lD("at")});var oy=b((nq,ny)=>{"use strict";ay();var cD=Ri();ny.exports=cD("Array","at")});var ly=b((oq,uy)=>{"use strict";var dD=oy();uy.exports=dD});var Ft=b((uq,cy)=>{"use strict";var pD=ly();cy.exports=pD});var ip=b((zH,Fy)=>{"use strict";var QD=Yi();Fy.exports=Array.isArray||function(e){return QD(e)==="Array"}});var Uy=b((WH,Ny)=>{"use strict";var YD=TypeError,KD=9007199254740991;Ny.exports=function(s){if(s>KD)throw YD("Maximum allowed index exceeded");return s}});var jy=b((QH,Hy)=>{"use strict";var XD=ip(),JD=Mr(),ZD=Uy(),e0=Pr(),qy=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,d=n?e0(n,o):!1,c,h;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],a>0&&XD(c)?(h=JD(c),u=qy(s,e,c,h,u,a-1)-1):(ZD(u+1),s[u]=c),u++),l++;return u};Hy.exports=qy});var Qy=b((YH,Wy)=>{"use strict";var Gy=ip(),t0=ed(),i0=vt(),r0=Oe(),s0=r0("species"),zy=Array;Wy.exports=function(s){var e;return Gy(s)&&(e=s.constructor,t0(e)&&(e===zy||Gy(e.prototype))?e=void 0:i0(e)&&(e=e[s0],e===null&&(e=void 0))),e===void 0?zy:e}});var Ky=b((KH,Yy)=>{"use strict";var a0=Qy();Yy.exports=function(s,e){return new(a0(s))(e===0?0:e)}});var Xy=b(()=>{"use strict";var n0=we(),o0=jy(),u0=jt(),l0=Er(),c0=Mr(),d0=Ky();n0({target:"Array",proto:!0},{flatMap:function(e){var t=l0(this),i=c0(t),r;return u0(e),r=d0(t,0),r.length=o0(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Jy=b(()=>{"use strict";var p0=fa();p0("flatMap")});var eT=b((tj,Zy)=>{"use strict";Xy();Jy();var h0=Ri();Zy.exports=h0("Array","flatMap")});var iT=b((ij,tT)=>{"use strict";var f0=eT();tT.exports=f0});var Ha=b((rj,rT)=>{"use strict";var m0=iT();rT.exports=m0});var ja=b((sj,sT)=>{"use strict";var b0=ba(),g0=String;sT.exports=function(s){if(b0(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return g0(s)}});var rp=b((aj,aT)=>{"use strict";aT.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 uT=b((nj,oT)=>{"use strict";var S0=De(),v0=ki(),y0=ja(),ap=rp(),nT=S0("".replace),T0=RegExp("^["+ap+"]+"),I0=RegExp("(^|[^"+ap+"])["+ap+"]+$"),sp=function(s){return function(e){var t=y0(v0(e));return s&1&&(t=nT(t,T0,"")),s&2&&(t=nT(t,I0,"$1")),t}};oT.exports={start:sp(1),end:sp(2),trim:sp(3)}});var pT=b((oj,dT)=>{"use strict";var x0=$c().PROPER,E0=Ve(),lT=rp(),cT="\u200B\x85\u180E";dT.exports=function(s){return E0(function(){return!!lT[s]()||cT[s]()!==cT||x0&&lT[s].name!==s})}});var np=b((uj,hT)=>{"use strict";var w0=uT().start,P0=pT();hT.exports=P0("trimStart")?function(){return w0(this)}:"".trimStart});var mT=b(()=>{"use strict";var A0=we(),fT=np();A0({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==fT},{trimLeft:fT})});var gT=b(()=>{"use strict";mT();var k0=we(),bT=np();k0({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==bT},{trimStart:bT})});var vT=b((hj,ST)=>{"use strict";gT();var R0=Ri();ST.exports=R0("String","trimLeft")});var TT=b((fj,yT)=>{"use strict";var M0=vT();yT.exports=M0});var xT=b((mj,IT)=>{"use strict";var L0=TT();IT.exports=L0});var _T=b(()=>{"use strict"});var FT=b(()=>{"use strict"});var UT=b((J3,NT)=>{"use strict";var e$=vt(),t$=Yi(),i$=Oe(),r$=i$("match");NT.exports=function(s){var e;return e$(s)&&((e=s[r$])!==void 0?!!e:t$(s)==="RegExp")}});var HT=b((Z3,qT)=>{"use strict";var s$=Gt();qT.exports=function(){var s=s$(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 zT=b((eG,GT)=>{"use strict";var a$=St(),n$=Ot(),o$=oa(),u$=HT(),jT=RegExp.prototype;GT.exports=function(s){var e=s.flags;return e===void 0&&!("flags"in jT)&&!n$(s,"flags")&&o$(jT,s)?a$(u$,s):e}});var QT=b((tG,WT)=>{"use strict";var pp=De(),l$=Er(),c$=Math.floor,cp=pp("".charAt),d$=pp("".replace),dp=pp("".slice),p$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,h$=/\$([$&'`]|\d{1,2})/g;WT.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=h$;return r!==void 0&&(r=l$(r),u=p$),d$(a,u,function(l,d){var c;switch(cp(d,0)){case"$":return"$";case"&":return s;case"`":return dp(e,0,t);case"'":return dp(e,n);case"<":c=r[dp(d,1,-1)];break;default:var h=+d;if(h===0)return l;if(h>o){var p=c$(h/10);return p===0?l:p<=o?i[p-1]===void 0?cp(d,1):i[p-1]+cp(d,1):l}c=i[h-1]}return c===void 0?"":c})}});var XT=b(()=>{"use strict";var f$=we(),m$=St(),fp=De(),YT=ki(),b$=ye(),g$=Ir(),S$=UT(),es=ja(),v$=la(),y$=zT(),T$=QT(),I$=Oe(),x$=Vt(),E$=I$("replace"),w$=TypeError,hp=fp("".indexOf),P$=fp("".replace),KT=fp("".slice),A$=Math.max;f$({target:"String",proto:!0},{replaceAll:function(e,t){var i=YT(this),r,a,n,o,u,l,d,c,h,p,f=0,m="";if(!g$(e)){if(r=S$(e),r&&(a=es(YT(y$(e))),!~hp(a,"g")))throw new w$("`.replaceAll` does not allow non-global regexes");if(n=v$(e,E$),n)return m$(n,e,i,t);if(x$&&r)return P$(es(i),e,t)}for(o=es(i),u=es(e),l=b$(t),l||(t=es(t)),d=u.length,c=A$(1,d),h=hp(o,u);h!==-1;)p=l?es(t(u,h,o)):T$(u,o,h,[],void 0,t),m+=KT(o,f,h)+p,f=h+d,h=h+c>o.length?-1:hp(o,u,h+c);return f<o.length&&(m+=KT(o,f)),m}})});var ZT=b((sG,JT)=>{"use strict";_T();FT();XT();var k$=Ri();JT.exports=k$("String","replaceAll")});var tI=b((aG,eI)=>{"use strict";var R$=ZT();eI.exports=R$});var mp=b((nG,iI)=>{"use strict";var M$=tI();iI.exports=M$});var sI=b((oG,rI)=>{"use strict";var L$=ha(),B$=ja(),D$=ki(),$$=RangeError;rI.exports=function(e){var t=B$(D$(this)),i="",r=L$(e);if(r<0||r===1/0)throw new $$("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var lI=b((uG,uI)=>{"use strict";var oI=De(),C$=vc(),aI=ja(),V$=sI(),O$=ki(),_$=oI(V$),F$=oI("".slice),N$=Math.ceil,nI=function(s){return function(e,t,i){var r=aI(O$(e)),a=C$(t),n=r.length,o=i===void 0?" ":aI(i),u,l;return a<=n||o===""?r:(u=a-n,l=_$(o,N$(u/o.length)),l.length>u&&(l=F$(l,0,u)),s?r+l:l+r)}};uI.exports={start:nI(!1),end:nI(!0)}});var dI=b((lG,cI)=>{"use strict";var U$=Xi();cI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(U$)});var pI=b(()=>{"use strict";var q$=we(),H$=lI().start,j$=dI();q$({target:"String",proto:!0,forced:j$},{padStart:function(e){return H$(this,e,arguments.length>1?arguments[1]:void 0)}})});var fI=b((pG,hI)=>{"use strict";pI();var G$=Ri();hI.exports=G$("String","padStart")});var bI=b((hG,mI)=>{"use strict";var z$=fI();mI.exports=z$});var bp=b((fG,gI)=>{"use strict";var W$=bI();gI.exports=W$});var Vh="2.0.131-dev.45e99145.0";var st=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(st||{}),fi=(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))(fi||{});var Eo=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Eo||{}),ql=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ql||{});var Hl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Hl||{}),wo=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(wo||{});var PE=U(xt(),1);import{assertNever as $m,assertNonNullable as rA,isNonNullable as Mo,ValueSubject as Tc,Subject as sA,Subscription as aA,merge as nA,observableFrom as oA,fromEvent as Lm,map as Bm,filterChanged as uA,isNullable as Ic,ErrorCategory as Dm}from"@vkontakte/videoplayer-shared/es2015";var Mm=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 Lo=class{constructor(e){this.connection$=new Tc(void 0);this.castState$=new Tc("NOT_AVAILABLE");this.errorEvent$=new sA;this.realCastState$=new Tc("NOT_AVAILABLE");this.subscription=new aA;this.isDestroyed=!1;var a;this.params=e;let t="chrome"in window;if(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||Mm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Dm.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();Ic(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ic(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(Lm(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 $m(r.sessionState)}})).add(nA(Lm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Bm(r=>r.castState)),oA([i.getCastState()])).pipe(uA(),Bm(lA)).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();rA(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Ic(c)||c===this.contentId)&&this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d})}else!a&&n&&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:Dm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},lA=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 $m(s)}};var Ph=U(xt(),1),uE=U(Lr(),1),lE=U(Yc(),1);var Cv=U(Aa(),1);import{assertNever as kv}from"@vkontakte/videoplayer-shared/es2015";var Te=(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:kv(t)}return s},Li=(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:kv(e)}};var R=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};import{isNonNullable as gB,Subject as au,merge as Rv}from"@vkontakte/videoplayer-shared/es2015";var G=class{constructor(e){this.transitionStarted$=new au;this.transitionEnded$=new au;this.transitionUpdated$=new au;this.forceChanged$=new au;this.stateChangeStarted$=Rv(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Rv(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||gB(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 SB}from"@vkontakte/videoplayer-shared/es2015";var Mv=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 SB(s)}};import{assertNever as Ur,assertNonNullable as sr,debounce as Lv,ErrorCategory as Bv,fromEvent as ar,isNonNullable as Dv,merge as vB,observableFrom as yB,Subject as TB,Subscription as Cd,timeout as IB,getHighestQuality as xB}from"@vkontakte/videoplayer-shared/es2015";var EB=5,wB=5,PB=500,$v=7e3,ka=class{constructor(e){this.subscription=new Cd;this.loadMediaTimeoutSubscription=new Cd;this.videoState=new G("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(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.params.output.isLive$.next(Mv(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.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Cd;this.subscription.add(e);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 TB;e.add(r.pipe(Lv(PB)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>EB)&&r.next(o),a=o})),e.add(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.params.output.duration$.next(n.value)}))}t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{r.value?this.handleRemotePause():this.handleRemotePlay()}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),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<wB&&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(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.handleRemoteVolumeChange({volume:r.value})}),t(ar(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.handleRemoteVolumeChange({muted:r.value})});let i=vB(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,yB(["init"])).pipe(Lv(0));t(i,this.syncPlayback)}restoreSession(e){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,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];sr(d);let c=xB(Object.keys(d));sr(c);let h=d[c];sr(h),i=h,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];sr(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];sr(d),i=d.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];sr(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];sr(d),i=Te(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:Bv.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 Dv(o)&&(n.metadata.title=o),Dv(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(IB($v).subscribe(()=>a(`timeout(${$v})`)))});(0,Cv.default)(Promise.race([t,i]).then(()=>{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.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Bv.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}};var ep=U(xt(),1);import{clearVideoElement as Ov}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as AB}from"@vkontakte/videoplayer-shared/es2015";var Vv=s=>{try{s.pause(),s.playbackRate=0,AB(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as kB,Subscription as RB}from"@vkontakte/videoplayer-shared/es2015";var Vd=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)}},Od=window.WeakMap?new WeakMap:new Vd,_d=window.WeakMap?new WeakMap:new Map,MB=(s,e=20)=>{let t=0;return kB(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},_e=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Ov(i):(i=document.createElement("video"),s.appendChild(i)),Od.set(i,r);let a=new RB;return a.add(MB(i,e)),_d.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},Fe=s=>{let e=_d.get(s);e==null||e.unsubscribe(),_d.delete(s);let t=Od.get(s);Od.delete(s),t?Ov(s):Vv(s)};var Nd=U(nr(),1);import{assertNonNullable as Ra,isNonNullable as Wt,isNullable as _B,fromEvent as qr,merge as jv,observableFrom as Gv,filterChanged as zv,map as Ma,Subject as Wv,Subscription as FB,ValueSubject as NB,ErrorCategory as UB}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Fd,isNullable as VB,Subscription as OB}from"@vkontakte/videoplayer-shared/es2015";var nu=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=VB(r),l=new OB;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},Et=(s,e,t)=>nu(e,()=>s.loop,i=>{Fd(i)&&(s.loop=i)},{onError:t}),Ne=(s,e,t,i)=>nu(e,()=>({muted:s.muted,volume:s.volume}),r=>{Fd(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)=>nu(e,()=>s.playbackRate,r=>{Fd(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Bi=nu;var qB=s=>["__",s.language,s.label].join("|"),HB=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},Ud=class s{constructor(e){this.available$=new Wv;this.current$=new NB(void 0);this.error$=new Wv;this.subscription=new FB;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:UB.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,Nd.default)(this.internalTracks),a=>{Wt(a)&&this.setInternal(a)},{equal:(a,n)=>Wt(a)&&Wt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ma(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Bi(t.externalTextTracks,()=>(0,Nd.default)(this.externalTracks),a=>{Wt(a)&&this.setExternal(a)},{equal:(a,n)=>Wt(a)&&Wt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ma(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(){Ra(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"),Gv(["init"])).pipe(Ma(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),zv((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"),Gv(["init"])).pipe(Ma(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ma(i=>i&&this.htmlTextTrackToITextTrack(i).id),zv()).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;Wt(t.align)&&(r.align=t.align),Wt(t.position)&&(r.position=t.position),Wt(t.size)&&(r.size=t.size),Wt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ra(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:qB(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){Ra(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(_B(e)||!HB(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){Ra(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){Ra(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=Ud;var or=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},qd=s=>{let e=Qv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Yv=s=>{let e=Qv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as ot,map as Di,merge as jd,filterChanged as JB,isNonNullable as ry,Subject as ZB,filter as Ba,mapTo as Gd,combine as eD,once as tD,throttle as iD,ErrorCategory as rD,ValueSubject as sy,Subscription as sD}from"@vkontakte/videoplayer-shared/es2015";var jB=3,Kv=(s,e,t=jB)=>{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 ou=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,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._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 Xv=U(xt(),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 uu=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,Xv.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()}detectHighEntropyValues(){return I(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,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 lu=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 Tt=()=>window.ManagedMediaSource||window.MediaSource,Hr=()=>{var s,e;return!!(window.ManagedMediaSource&&((e=(s=window.ManagedSourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},Jv=()=>{var s,e;return!!(window.MediaSource&&((e=(s=window.SourceBuffer)==null?void 0:s.prototype)!=null&&e.appendBuffer))},cu=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var GB=document.createElement("video"),zB='video/mp4; codecs="avc1.42000a,mp4a.40.2"',WB='video/mp4; codecs="hev1.1.6.L93.B0"',Zv='video/webm; codecs="vp09.00.10.08"',ey='video/webm; codecs="av01.0.00M.08"',QB='audio/mp4; codecs="mp4a.40.2"',YB='audio/webm; codecs="opus"',ty,KB=()=>I(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(D(x({},s),{video:D(x({},s.video),{contentType:ey})})),window.navigator.mediaCapabilities.decodingInfo(D(x({},s),{video:D(x({},s.video),{contentType:Zv})}))]);ty={DASH_WEBM_AV1:e,DASH_WEBM:t}});KB().catch(s=>{console.log(GB),console.error(s)});var du=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 ty}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,T;this._video=document.createElement("video");try{this._protocols={mms:Hr(),mse:Jv(),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 w=!!((d=(l=Tt())==null?void 0:l.isTypeSupported)!=null&&d.call(l,zB)),E=!!((h=(c=Tt())==null?void 0:c.isTypeSupported)!=null&&h.call(c,WB)),L=!!((f=(p=Tt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,QB));this._codecs={h264:w,h265:E,vp9:!!((g=(m=Tt())==null?void 0:m.isTypeSupported)!=null&&g.call(m,Zv)),av1:!!((y=(S=Tt())==null?void 0:S.isTypeSupported)!=null&&y.call(S,ey)),aac:L,opus:!!((T=(v=Tt())==null?void 0:v.isTypeSupported)!=null&&T.call(v,YB)),mpeg:(w||E)&&L},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(w){console.error(w)}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 iy="audio/mpeg",pu=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,iy))},this._codecs={mp3:!!((r=(i=Tt())==null?void 0:i.isTypeSupported)!=null&&r.call(i,iy))}}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 XB}from"@vkontakte/videoplayer-shared/es2015";var Hd=class{constructor(){this.isInited$=new XB(!1);this._displayChecker=new lu,this._deviceChecker=new uu(this._displayChecker),this._browserChecker=new ou,this._videoChecker=new du(this._deviceChecker,this._browserChecker),this._audioChecker=new pu,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return I(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},z=new Hd;var Ue=s=>{let e=P=>ot(s,P).pipe(Gd(void 0)),t=new sD,i=()=>t.unsubscribe(),a=jd(...["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),JB()),n=jd(ot(s,"progress"),ot(s,"timeupdate")).pipe(Di(()=>Kv(s.buffered,s.currentTime))),o=z.browser.isSafari?eD({play:e("play").pipe(tD()),playing:e("playing")}).pipe(Gd(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(Ba(()=>!!(s.error||s.played.length)),Di(()=>{var $;let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:rD.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:($=s.error)!=null?$:void 0}})),c=ot(s,"timeupdate").pipe(Di(()=>s.currentTime)),h=new ZB,p=.3,f;t.add(c.subscribe(P=>{s.loop&&ry(f)&&ry(P)&&f>=s.duration-p&&P<=p&&h.next(f),f=P}));let m=e("pause").pipe(Ba(()=>!s.error&&f!==s.duration)),g=ot(s,"enterpictureinpicture"),S=ot(s,"leavepictureinpicture"),y=new sy(Yv(s));t.add(g.subscribe(()=>y.next(!0))),t.add(S.subscribe(()=>y.next(!1)));let v=new sy(qd(s)),T=ot(s,"fullscreenchange");t.add(T.pipe(Di(()=>qd(s))).subscribe(v));let w=.1,E=1e3,L=ot(s,"timeupdate").pipe(Ba(P=>s.duration-s.currentTime<w)),_=jd(L.pipe(Ba(P=>!s.loop)),ot(s,"ended")).pipe(iD(E),Gd(void 0)),q=L.pipe(Ba(P=>s.loop));return{playing$:o,pause$:m,canplay$:e("canplay"),ended$:_,looped$:h,loopExpected$:q,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 $i}from"@vkontakte/videoplayer-shared/es2015";var Qt=s=>{switch(s){case"mobile":return $i.Q_144P;case"lowest":return $i.Q_240P;case"low":return $i.Q_360P;case"sd":case"medium":return $i.Q_480P;case"hd":case"high":return $i.Q_720P;case"fullhd":case"full":return $i.Q_1080P;case"quadhd":case"quad":return $i.Q_1440P;case"ultrahd":case"ultra":return $i.Q_2160P}};var et=U(Ft(),1),Wd=U(xt(),1);import{isNonNullable as oe,isNullable as vu,now as by,isHigher as yu,isHigherOrEqual as Gr,isInvariantQuality as Tu,isLowerOrEqual as zr,videoSizeToQuality as gy,assertNotEmptyArray as Iu,assertNonNullable as Sy}from"@vkontakte/videoplayer-shared/es2015";var hD=!1,hu={};var fu=class{constructor(e){this.name=e}next(e){var i,r;if(!hD)return;hu.series=(i=hu.series)!=null?i:{};let t=(r=hu.series[this.name])!=null?r:[];t.push([Date.now(),e]),hu.series[this.name]=t}};import{isHigher as fD,isHigherOrEqual as fq,isLower as dy,isLowerOrEqual as mq,isNonNullable as mu,isNullable as mD,videoHeightToQuality as bu}from"@vkontakte/videoplayer-shared/es2015";function zd(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function gu(s,e,t){return!!s&&zd(s,e,t)==="high_quality"}function jr(s,e,t){return mD(s)||mu(s.min)&&mu(s.max)&&dy(s.max,s.min)||mu(s.min)&&e&&fD(s.min,e)||mu(s.max)&&t&&dy(s.max,t)}function py({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return jr({max:s!=null&&s.max?bu(s.max):void 0,min:s!=null&&s.min?bu(s.min):void 0},e?bu(e):void 0,t?bu(t):void 0)}var vy=new fu("best_bitrate"),xu=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Wr=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Ci=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=by()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Eu='Assertion "ABR Tracks is empty array" failed',Su=new WeakMap,hy=new WeakMap,fy=new WeakMap,Da=(s,e,t,i)=>{var u;let r=[...e].sort(Wr(1)),a=[...t].sort(Wr(1)),n=a.filter(l=>oe(l.bitrate)&&oe(s.bitrate)?s.bitrate/l.bitrate>i:!0),o=(u=(0,et.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,et.default)(a,-1);return o&&(0,Wd.default)(n,o)?o:n.length?(0,et.default)(n,-1):(0,et.default)(a,0)},$a=(s,e,t,i)=>{var u;let r=Su.get(e);r||(r=[...e].sort(Wr(1)),Su.set(e,r));let a=Su.get(t);a||(a=[...t].sort(Wr(1)),Su.set(t,a));let n=fy.get(s);n||(n=a.filter(l=>oe(l.bitrate)&&oe(s.bitrate)?s.bitrate/l.bitrate>i:!0),fy.set(s,n));let o=(u=(0,et.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1))))!=null?u:(0,et.default)(a,-1);return o&&(0,Wd.default)(n,o)?o:n.length?(0,et.default)(n,-1):(0,et.default)(a,0)},wu=(s,e,t)=>{var a;let i=oe((a=t==null?void 0:t.last)==null?void 0:a.bitrate)&&oe(e==null?void 0:e.bitrate)&&t.last.bitrate<e.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,r=e&&t&&t.history[e.id]&&by()-t.history[e.id]<=i&&(!t.last||e.id!==t.last.id);if(e!=null&&e.id&&t&&!r&&t.recordSelection(e),r&&(t!=null&&t.last)){let n=t.last;return t==null||t.recordSwitch(n),n}return t==null||t.recordSwitch(e),e},bD=(s,e)=>Math.log(e)/Math.log(s),yy=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&z.display.pixelRatio){let a=z.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=bD(n,o*a+u)+l;Number.isFinite(d)&&(r*=d)}}return gu(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}},my=new WeakMap,Yt=(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,panelSize:f})=>{var P,$,M;Iu(s,Eu);let{containerSizeLimit:m}=yy({container:e,tuning:i,limits:r,panelSize:f}),g=i.considerPlaybackRate&&oe(o)?o:1,S=my.get(s);S||(S=s.filter(B=>!Tu(B.quality)).sort((B,A)=>yu(B.quality,A.quality)?-1:1),my.set(s,S));let y=(P=(0,et.default)(S,-1))==null?void 0:P.quality,v=($=(0,et.default)(S,0))==null?void 0:$.quality,T=jr(r,v,y),w=g*xu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},L=null;for(let B of S){let A=!0;if(m)if(B.size)A=B.size.width<=m.width&&B.size.height<=m.height;else{let he=m&&gy(m);A=he?zr(B.quality,he):!0}if(!A){E[B.quality]="FitsContainer";continue}let C=p||t,k=oe(C)&&isFinite(C)&&oe(B.bitrate)?C-a>=B.bitrate*w:!0,O=gu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===B.quality;if(!k&&!O){E[B.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&oe(i.minBufferToSwitchUp)&&u&&!Tu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&yu(B.quality,u.quality)){E[B.quality]="Buffer";continue}if(!!c&&Gr(B.quality,c)&&!O){E[B.quality]="DroppedFramesLimit";continue}if(!!h&&Gr(B.quality,h)&&!O){E[B.quality]="StallsLimit";continue}let Pt=T||(vu(r==null?void 0:r.max)||zr(B.quality,r.max))&&(vu(r==null?void 0:r.min)||Gr(B.quality,r.min)),K=oe(d)&&!d?zr(B.quality,i.backgroundVideoQualityLimit):!0;if(!Pt||!K){E[B.quality]="FitsQualityLimits";continue}L||(L=B)}L&&L.bitrate&&vy.next(L.bitrate);let _=(M=L!=null?L:(0,et.default)(S,-1))!=null?M:s[0];return wu(i,_,l)},Pu=(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,panelSize:f})=>{var $,M,B;Iu(s,Eu);let{containerSizeLimit:m}=yy({container:e,tuning:i,limits:r,panelSize:f}),g=i.considerPlaybackRate&&oe(o)?o:1,S=s.filter(A=>!Tu(A.quality)).sort((A,C)=>yu(A.quality,C.quality)?-1:1),y=($=(0,et.default)(S,-1))==null?void 0:$.quality,v=(M=(0,et.default)(S,0))==null?void 0:M.quality,T=jr(r,y,v),w=g*xu(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),E={},_=S.filter(A=>{let C=!0;if(m)if(A.size)C=A.size.width<=m.width&&A.size.height<=m.height;else{let xe=m&&gy(m);C=xe?zr(A.quality,xe):!0}if(!C)return E[A.quality]="FitsContainer",!1;let k=p||t,O=oe(k)&&isFinite(k)&&oe(A.bitrate)?k-a>=A.bitrate*w:!0,ee=gu(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===A.quality;if(!O&&!ee)return E[A.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&oe(i.minBufferToSwitchUp)&&u&&!Tu(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&yu(A.quality,u.quality))return E[A.quality]="Buffer",!1;if(!!c&&Gr(A.quality,c)&&!ee)return E[A.quality]="DroppedFramesLimit",!1;if(!!h&&Gr(A.quality,h)&&!ee)return E[A.quality]="StallsLimit",!1;let K=T||(vu(r==null?void 0:r.max)||zr(A.quality,r.max))&&(vu(r==null?void 0:r.min)||Gr(A.quality,r.min)),he=oe(d)&&!d?zr(A.quality,i.backgroundVideoQualityLimit):!0;return!K||!he?(E[A.quality]="FitsQualityLimits",!1):!0})[0];_&&_.bitrate&&vy.next(_.bitrate);let q=(B=_!=null?_:(0,et.default)(S,-1))!=null?B:s[0];return wu(i,q,l)},Au=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,stallsPredictedThroughput:u})=>{Iu(t,Eu);let l=r.considerPlaybackRate&&oe(a)?a:1,d=[...t].sort(Wr(-1)),c=s.bitrate;Sy(c);let h=l*xu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),p,f=Da(s,e,t,r.minVideoAudioRatio),m=u||i;return oe(m)&&isFinite(m)&&(p=d.find(S=>oe(S.bitrate)&&oe(f==null?void 0:f.bitrate)?m-c>=S.bitrate*h&&S.bitrate>=f.bitrate:!1)),p||(p=f),p&&wu(r,p,o)},ku=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,stallsPredictedThroughput:u})=>{Iu(t,Eu);let l=r.considerPlaybackRate&&oe(a)?a:1,d=hy.get(t);d||(d=[...t].sort(Wr(-1)),hy.set(t,d));let c=s.bitrate;Sy(c);let h=l*xu(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),p,f=$a(s,e,t,r.minVideoAudioRatio),m=u||i;return oe(m)&&isFinite(m)&&(p=d.find(S=>oe(S.bitrate)&&oe(f==null?void 0:f.bitrate)?m-c>=S.bitrate*h&&S.bitrate>=f.bitrate:!1)),p||(p=f),p&&wu(r,p,o)};var Pe=s=>new URL(s).hostname;import{assertNever as Ly,assertNonNullable as By,combine as OD,debounce as _D,ErrorCategory as Dy,filter as $y,filterChanged as FD,isNonNullable as Jd,map as Cy,merge as ND,observableFrom as UD,once as qD,Subscription as HD,ValueSubject as Zd,videoQualityToHeight as Vy,videoSizeToQuality as jD}from"@vkontakte/videoplayer-shared/es2015";var Ay=U(Ft(),1);var Iy=U(xt(),1);var Ty=s=>{if(s instanceof DOMException&&(0,Iy.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"))},qe=(s,e)=>I(void 0,null,function*(){let t=s.muted;try{yield s.play()}catch(i){if(!Ty(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{yield s.play()}catch(r){return Ty(r)&&(s.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as Mu,isNullable as vD,assertNonNullable as Oa}from"@vkontakte/videoplayer-shared/es2015";var Ey=U(nr(),1);import{isNonNullable as xy,assertNonNullable as Ru,now as gD}from"@vkontakte/videoplayer-shared/es2015";function $e(){return gD()}function Qd(s){return $e()-s}function Yd(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 wy(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Qr(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;Ru(d);let M=Qd(d),B;if(M<m){B=m-M,setTimeout(g,B);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,E()},S=M=>(a=M,$),y=M=>(c=M,$),v=()=>(p="json",$),T=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},w=M=>(h=M,$),E=()=>{d=$e(),n=new r,n.open("get",s);let M=0,B,A=0,C=()=>(Ru(d),Math.max(d,Math.max(B||0,A||0)));if(a&&n.addEventListener("progress",k=>{let O=$e();a.updateChunk&&k.loaded>M&&(a.updateChunk(C(),k.loaded-M),M=k.loaded,B=O)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;Ru(n);let k=n.status;if(k>=200&&k<300){let{response:O,responseType:ee}=n,te=O==null?void 0:O.byteLength;if(typeof te=="number"&&a){let H=te-M;H&&a.updateChunk&&a.updateChunk(C(),H)}ee==="json"&&(!O||!(0,Ey.default)(O).length)?T():(c&&c(),e(O))}else T()}),n.addEventListener("error",()=>{T()}),h){let k=()=>{Ru(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(A=$e(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=p,n.send(),$},$={withBitrateReporting:S,withParallel:w,withJSONResponse:v,withRetryCount:M=>(l=M,$),withRetryInterval:(M,B)=>(xy(M)&&(m=M),xy(B)&&(f=B),$),withTimeout:M=>(o=M,$),withFinally:y,send:E,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return $}var Ca=class{constructor(){this.intervals=[];this.currentRate=0}_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),!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._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Py=U(nr(),1);var Va=class{constructor(e,t,i,r){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}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];delete this.completeRequests[t]}}_sendRequest(e,t){let i=$e(),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=$e()-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=Qr(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=$e()}_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=$e();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._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Py.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?t(n._responseData,n._downloadTime):i(n._errorMsg),a._finallyCB&&a._finallyCB()},0));else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),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.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as yD}from"@vkontakte/videoplayer-shared/es2015";var Lu=1e4,Kd=3;var TD=6e4,ID=10,xD=1,ED=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 yD,this.chunkRateEstimator=new Ca,this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Yd(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=Yd(e),this.catchUp()}_handleNetworkError(){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.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&this.params.playerCallback({name:"error",type:"media"})}),e.addEventListener("timeupdate",()=>{let t=this._getBufferSizeSec();!this.paused&&t<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(t+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{videoElement:e}=this.params,t=e.buffered.length,i;t!==0&&!this.waitingForFirstBufferAfterSrcChange&&(i=e.buffered.start(t-1),e.currentTime<i&&(e.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*(z.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||{};!py({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Ay.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||Mu(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{videoElement:i,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let a=()=>{wy(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,r({name:"playing"})):a()})};this.waitingForFirstBufferAfterSrcChange=!0,a()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Va(Kd,Lu,this.bitrateSwitcher,this.params.config.maxParallelRequests),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{videoElement:t,playerCallback:i}=this.params,r=!1,a=null,n=null,o=null,u=null,l=!1,d=()=>r&&(!l||l===this.rep),c=(v,T,w)=>{o&&o.abort(),o=Qr(this.urlResolver.resolve(v,!1),T,w,()=>this._retryCallback()).withTimeout(Lu).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Kd).withFinally(()=>{o=null}).send()},h=(v,T,w)=>{Oa(this.filesFetcher),n==null||n.abort(),n=this.filesFetcher.requestData(this.urlResolver.resolve(v,!1),T,w,()=>this._retryCallback()).withFinally(()=>{n=null}).send()},p=v=>{let T=t.playbackRate;t.playbackRate!==v&&(t.playbackRate=v)},f=v=>{this.lowLatency=v,m()},m=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)p(1);else{let v=this._getBufferSizeSec();if(this.bufferStates.length<5){p(1);return}let w=$e()-1e4,E=0;for(let _=0;_<this.bufferStates.length;_++){let q=this.bufferStates[_];v=Math.min(v,q.buf),q.ts<w&&E++}this.bufferStates.splice(0,E);let L=v-xD;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?p(1.15):L>1?p(1.1):L>.3?p(1.05):p(1)}},g=v=>{let T,w=()=>T&&T.start?T.start.length:0,E=C=>T.start[C]/1e3,L=C=>T.dur[C]/1e3,_=C=>T.fragIndex+C,q=(C,k)=>({chunkIdx:_(C),startTS:E(C),dur:L(C),discontinuity:k}),P=()=>{let C=0;if(T&&T.dur){let k=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,O=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=k;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let te=T.dur.length-1;for(;te>=0&&(ee-=T.dur[te],!(ee<=0));--te);C=Math.min(te,T.dur.length-1-O),C=Math.max(C,0)}return q(C,!0)},$=C=>{let k=w();if(!(k<=0)){if(Mu(C)){for(let O=0;O<k;O++)if(E(O)>C)return q(O)}return P()}},M=C=>{let k=w(),O=C?C.chunkIdx+1:0,ee=O-T.fragIndex;if(!(k<=0)){if(!C||ee<0||ee-k>ID)return P();if(!(ee>=k))return q(O-T.fragIndex,!1)}},B=(C,k,O)=>{u&&u.abort(),u=Qr(this.urlResolver.resolve(C,!0,this.lowLatency),k,O,()=>this._retryCallback()).withTimeout(Lu).withRetryCount(Kd).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(C,k)=>{B(v,O=>{if(!d())return;T=O;let ee=!!T.lowLatency;ee!==this.lowLatency&&f(ee);let te=0;for(let H=0;H<T.dur.length;++H)te+=T.dur[H];te>0&&(Oa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/T.dur.length)),i({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,C($(k))},()=>this._handleNetworkError())},nextChunk:M}},S=()=>{r=!1,n&&n.abort(),o&&o.abort(),u&&u.abort(),Oa(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:v=>{let{videoElement:T}=this.params,w=g(e.jidxUrl),E,L,_,q,P=0,$,M,B,A=()=>{$&&(clearTimeout($),$=void 0);let K=Math.max(ED,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=P+K,xe=$e(),ze=Math.min(1e4,he-xe);P=xe;let At=()=>{u||d()&&w.seek(()=>{d()&&(P=$e(),C(),A())})};ze>0?$=window.setTimeout(()=>{this.paused?A():At()},ze):At()},C=()=>{let K;for(;K=w.nextChunk(q);)q=K,H(K);let he=w.nextChunk(_);if(he){if(_&&he.discontinuity){this.paused?A():(S(),this._initPlayerWith(e));return}te(he)}else A()},k=(K,he)=>{if(!d()||!this.sourceBuffer)return;let xe,ze,At,ei=kt=>{window.setTimeout(()=>{d()&&k(K,he)},kt)};if(this.sourceBuffer.updating)ei(100);else{let kt=$e(),Ht=T.currentTime;!this.paused&&T.buffered.length>1&&M===Ht&&kt-B>500&&this._fixupStall(),M!==Ht&&(M=Ht,B=kt);let Pi=this._getBufferSizeSec();if(Pi>30)ei(2e3);else try{this.sourceBuffer.appendBuffer(K),this.videoPlayStarted?(this.bufferStates.push({ts:kt,buf:Pi}),m(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch(Ai){if(Ai.name==="QuotaExceededError")At=this.sourceBuffer.buffered.length,At!==0&&(xe=this.sourceBuffer.buffered.start(0),ze=Ht,ze-xe>4&&this.sourceBuffer.remove(xe,ze-3)),ei(1e3);else throw Ai}}},O=()=>{L&&E&&k(L,function(){L=null,C()})},ee=K=>e.fragUrlTemplate.replace("%%id%%",K.chunkIdx),te=K=>{d()&&h(ee(K),(he,xe)=>{if(d()){if(xe/=1e3,L=he,_=K,a=K.startTS,xe){let ze=Math.min(10,K.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ze:ze}O()}},()=>this._handleNetworkError())},H=K=>{d()&&(Oa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(K),!1)))},Pt=K=>{d()&&(e.cachedHeader=K,k(K,()=>{E=!0,O()}))};r=!0,w.seek(K=>{if(d()){if(P=$e(),!K){A();return}q=K,!vD(v)||K.startTS>v?te(K):(_=K,C())}},v),e.cachedHeader?Pt(e.cachedHeader):c(e.headerUrl,Pt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>a},l}_switchToQuality(e){let{playerCallback:t}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Mu(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),this.bitrate=e.bitrate,Oa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),t({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Mu(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{playerCallback:e}=this.params,t=d=>{if(!this.autoQuality)return;let c,h,p;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),p=d/this.bitrate,h>10&&p>.8||h>15&&p>.5||h>20&&p>.3)||(c=this._selectQuality(d),c&&this._switchToQuality(c))},r={updateChunk:(c,h)=>{let p=$e();if(this.chunkRateEstimator.addInterval(c,p,h)){let m=this.chunkRateEstimator.getBitRate();return e({name:"bandwidth",size:h,duration:p-c,speed:m}),!0}},get:()=>{let c=this.chunkRateEstimator.getBitRate();return c?c*.85:0}},a=-1/0,n,o=!0,u=()=>{let d=r.get();if(d&&n&&this.autoQuality){if(o&&d>n&&Qd(a)<3e4)return;t(d)}o=this.autoQuality};return{updateChunk:(d,c)=>{let h=r.updateChunk(d,c);return h&&u(),h},notifySwitch:d=>{let c=$e();d<n&&(a=c),n=d}}}_fetchManifest(e,t,i){this.manifestRequest=Qr(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;qe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{playerCallback:t,videoElement:i}=this.params,r=a=>{let n=[];return a!=null&&a.length?(a.forEach((o,u)=>{var l,d;o.video&&i.canPlayType(o.codecs).replace(/no/,"")&&((d=(l=window.MediaSource)==null?void 0:l.isTypeSupported)!=null&&d.call(l,o.codecs))&&(o.index=u,n.push(o))}),n.sort(function(o,u){return o.video&&u.video?u.video.height-o.video.height:u.bitrate-o.bitrate}),n):(t({name:"error",type:"empty_manifest"}),[])};this.manifest=r(e),t({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))},TD))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var My=U(Lr(),1);import{debounce as wD,filter as ky,fromEvent as PD,interval as AD,isHigher as kD,isInvariantQuality as RD,isLower as MD,merge as LD,Subject as Ry,Subscription as BD}from"@vkontakte/videoplayer-shared/es2015";var Xd=class{constructor(){this.onDroopedVideoFramesLimit$=new Ry;this.subscription=new BD;this.playing=!1;this.tracks=[];this.forceChecker$=new Ry;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&&!RD(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>=this.droppedFramesChecker.percentLimit&&kD(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.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(PD(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=AD(this.droppedFramesChecker.checkTime).pipe(ky(()=>this.playing),ky(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(wD(this.droppedFramesChecker.checkTime)),i=LD(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.onDroopedVideoFramesLimit$.next()}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,My.default)(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>MD(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=Xd;import{map as DD,Observable as $D}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as CD}from"@vkontakte/videoplayer-shared/es2015";var Fa=()=>{var s;return!!((s=window.documentPictureInPicture)!=null&&s.window)||!!document.pictureInPictureElement};var VD=(s,e)=>new $D(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Fa()))},x(x({},i),e));r.observe(s);let a=CD(document,"visibilitychange").pipe(DD(n=>!document.hidden||Fa())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),ut=VD;var GD=["paused","playing","ready"],zD=["paused","playing","ready"],Na=class{constructor(e){this.subscription=new HD;this.videoState=new G("stopped");this.representations$=new Zd([]);this.droppedFramesManager=new Yr;this.maxSeekBackTime$=new Zd(1/0);this.zeroTime$=new Zd(void 0);this.liveOffset=new or;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:Dy.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:jD(u.video),c=u.bitrate/1e3,h=x({},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),Jd(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(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,ep.default)(zD,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&(0,ep.default)(GD,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(Te(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(Te(this.params.source.url,u))}return;default:return Ly(e)}};this.textTracksManager=new nt(e.source.url),this.params=e;let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Dy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.video=_e(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Ue(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Cy(r=>r.map(({track:a})=>a)),$y(r=>!!r.length),qD()).subscribe(r=>this.droppedFramesManager.connect({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(FD(),Cy(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(OD({zeroTime:this.zeroTime$.pipe($y(Jd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Et(this.video,this.params.desiredState.isLooped,t)).add(Ne(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(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&&Vy(r),min:a&&Vy(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 Ly(r.to)}},t)).add(ND(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,UD(["init"])).pipe(_D(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}createLiveDashPlayer(){let e=new _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});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&&Jd(t)?t:Yt(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}),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;By(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;By(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.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(Te(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Oy=Na;var fe=(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 MC,assertNonNullable as LC,debounce as BC,ErrorCategory as KI,filter as Fp,filterChanged as nl,fromEvent as DC,isNonNullable as XI,map as Np,merge as ol,observableFrom as Up,once as JI,Subscription as $C}from"@vkontakte/videoplayer-shared/es2015";var Bu=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 Bu{constructor(){super(),this.listeners||Bu.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 Du(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 tp(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Du({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 WD=()=>"fetch"in window,qa=WD()&&Du({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),_y=qa?tp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,wt=qa?_y.fetch:window.fetch,HH=qa?_y.Request:window.Request,ae=qa?Ua:window.AbortController,jH=qa?Kr:window.AbortSignal;var Cp=U(Ha(),1);var ET=U(xT(),1);import{ErrorCategory as Ga}from"@vkontakte/videoplayer-shared/es2015";var $u=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,ET.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 He=(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 Lp,assertNonNullable as as,combine as ns,ErrorCategory as Xt,filter as Ju,filterChanged as En,fromEvent as Jt,interval as Bp,isNonNullable as wn,isNullable as jI,map as os,merge as hr,now as Dp,Subject as Zu,Subscription as $p,tap as hC,throttle as GI,ValueSubject as me}from"@vkontakte/videoplayer-shared/es2015";var Fu=U(xt(),1),rs=U(Ft(),1),Nu=U(Ha(),1);var B0=(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)},D0=s=>window.clearTimeout(s),wT=s=>typeof s=="function"&&(s==null?void 0:s.toString().endsWith("{ [native code] }")),PT=!wT(window.requestIdleCallback)||!wT(window.cancelIdleCallback),Xr=PT?B0:window.requestIdleCallback,Kt=PT?D0:window.cancelIdleCallback;var $I=U(Aa(),1);import{assertNever as $0,ErrorCategory as AT,Subject as kT}from"@vkontakte/videoplayer-shared/es2015";var C0=18,RT=!1;try{RT=z.browser.isSafari&&!!z.browser.safariVersion&&z.browser.safariVersion<=C0}catch(s){console.error(s)}var op=class{constructor(e){this.bufferFull$=new kT;this.error$=new kT;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:AT.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return I(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return I(this,null,function*(){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()})})}abort(e){return I(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};RT&&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:AT.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:$0(t)}}},MT=op;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 Oi,assertNonNullable as lt,ErrorCategory as dr,fromEvent as DI,getExponentialDelay as wp,isNonNullable as is,isNullable as je,now as _u,once as tC,Subject as iC,Subscription as rC,ValueSubject as pr}from"@vkontakte/videoplayer-shared/es2015";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),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 J{};var za=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 Wa=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 Qa=class extends J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ue=class extends J{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 J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xa=class extends J{constructor(e,t){super(e,t),this.data=this.content}};var ur=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 J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Za=class extends J{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 J{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 J{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var on=class extends J{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 J{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 J{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 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 O0={ftyp:Wa,moov:Qa,mvhd:Ya,moof:Ka,mdat:Xa,sidx:ur,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},gi=class s{constructor(e={}){this.options=x({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=O0[e];return i?new i(t,new s):new Zr(t,new s)}};var Vi=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 F0=new TextDecoder("ascii"),N0=s=>F0.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",U0=s=>{let e=new ur(s,new gi),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})},q0=(s,e)=>{let i=new gi().parse(s),r=new Vi(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)},H0=s=>{let t=new gi().parse(s),i=new Vi(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},j0=s=>{var r;let t=new gi().parse(s);return(r=new Vi(t).find("sidx"))==null?void 0:r.timescale},G0=(s,e)=>{let i=new gi().parse(s),a=new Vi(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},z0=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 gi().parse(s),r=new Vi(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},LT={validateData:N0,parseInit:z0,getIndexRange:()=>{},parseSegments:U0,parseFeedableSegmentChunk:q0,getChunkEndTime:G0,getServerLatencyTimestamps:H0,getTimescaleFromIndex:j0};var gn=U(xt(),1);import{assertNonNullable as lp,isNonNullable as CT,isNullable as Q0}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as W0}from"@vkontakte/videoplayer-shared/es2015";var BT={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"}},DT=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 BT,a=r?BT[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*Ze(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)*Ze(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Ze(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Ze(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 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:W0(e)}},lr=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=DT(i);if(!e(r))return;r.type==="master"&&lr(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},$T=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=DT(s);return lr(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 VT=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Y0=[231,22612,22743,167,171,163,160,175],K0=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return lr(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Nt(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=Nt(f,p):h===17545?r=Nt(f,p):h===21420&&l===475249515?u=Nt(f,p):h===374648427?lr(f,({tag:g,type:S,value:y})=>g===30321?(d=Nt(y,S)===1,!1):!0):a&&n&&(0,gn.default)(VT,h)&&(o=!0),!o}),lp(e,"Failed to parse webm Segment start"),lp(t,"Failed to parse webm Segment end"),lp(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}}}},X0=s=>{if(Q0(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},J0=(s,e)=>{let t=!1,i=!1,r=o=>CT(o.time)&&CT(o.position),a=[],n;return lr(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,gn.default)(VT,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}}})},Z0=s=>{let e=0,t=!1;try{lr(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,gn.default)(Y0,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},OT={validateData:$T,parseInit:K0,getIndexRange:X0,parseSegments:J0,parseFeedableSegmentChunk:Z0};var Sn=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return OT;case"mp4":return LT}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Ip=U(mp(),1),kI=U(Lr(),1),RI=U(bp(),1),MI=U(Ft(),1),xp=U(nr(),1);var SI=U(xt(),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,SI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as X$,isNullable as PI}from"@vkontakte/videoplayer-shared/es2015";var Cu=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var vI=s=>{var e;try{let t=Q$(),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 Q$(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
8
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
65
9
|
(-(?<script>[a-z]{4}))?
|
|
66
10
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
67
11
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
68
12
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
69
13
|
(?:-(?<privateuse>(?:${e})))?
|
|
70
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Ul=O(Nt(),1);import{videoSizeToQuality as EC}from"@vkontakte/videoplayer-shared/es2015";var gy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?_t(s):void 0)!=null?u:EC({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},vy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Sy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),yy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Hl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Ul.default)(i.split("."),0),isDefault:r}),jl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Ul.default)(r.split("."),0)}),Ql=a=>"url"in a,xe=a=>a.type==="template",La=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Iy=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},yt=(a,e)=>{let t=a;t=(0,Gl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Ey.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Gl.default)(t,n,(o,u)=>Ty(s)?o:Ty(u)?s:(0,xy.default)(s,parseInt(u,10),"0"))}return t},wy=(a,e)=>{var K,x,j,L,Q,N,Z,R,D,X,P,M,me,Ti,dt,Y,ye,Pe,we,tt,pt,Pt,zt,Ii,cr,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,sd,nd,od,ud,ld,cd,dd,pd,hd;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 te,Kt;return(Kt=(te=Qe.textContent)==null?void 0:te.trim())!=null?Kt:""}),o=(K=(0,Py.default)(n,0))!=null?K:"",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,te)=>C(w({},Qe),{[te.id]:te.children}),{}),T=y.reduce((Qe,te)=>C(w({},Qe),{[te.id]:te.getAttribute("duration")}),{});S?v=Iy(S):(0,Wl.default)(T).filter(Qe=>Qe).length&&!u?v=(0,Wl.default)(T).reduce((Qe,te)=>{var Kt;return Qe+((Kt=Iy(te))!=null?Kt:0)},0):b&&(v=parseInt(b,10));let $=0,F=(j=(x=s.getAttribute("profiles"))==null?void 0:x.split(","))!=null?j:[];for(let Qe of y.map(te=>te.id))for(let te of I[Qe]){let Kt=(L=te.getAttribute("id"))!=null?L:"id"+($++).toString(10),dr=(Q=te.getAttribute("mimeType"))!=null?Q:"",Jn=(N=te.getAttribute("codecs"))!=null?N:"",Zn=(Z=te.getAttribute("contentType"))!=null?Z:dr==null?void 0:dr.split("/")[0],zT=(D=(R=te.getAttribute("profiles"))==null?void 0:R.split(","))!=null?D:[],md=(P=by((X=te.getAttribute("lang"))!=null?X:""))!=null?P:{},es=(Ti=(me=(M=te.querySelector("Label"))==null?void 0:M.textContent)==null?void 0:me.trim())!=null?Ti:void 0,KT=te.querySelectorAll("Representation"),XT=te.querySelector("SegmentTemplate"),JT=(Y=(dt=te.querySelector("Role"))==null?void 0:dt.getAttribute("value"))!=null?Y:void 0,Ei=Zn,se={id:Kt,language:md.language,isDefault:JT==="main",label:es,codecs:Jn,hdr:Ei==="video"&&Fl(Jn),mime:dr,representations:[]};for(let ee of KT){let wt=(ye=ee.getAttribute("lang"))!=null?ye:void 0,pr=(we=(Pe=es!=null?es:te.getAttribute("label"))!=null?Pe:ee.getAttribute("label"))!=null?we:void 0,ts=(Pt=(pt=(tt=ee.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:pt.trim())!=null?Pt:"",Xt=new URL(ts||o,e).toString(),At=(zt=ee.getAttribute("mimeType"))!=null?zt:dr,is=(cr=(Ii=ee.getAttribute("codecs"))!=null?Ii:Jn)!=null?cr:"",rs;if(Zn==="text"){let kt=ee.getAttribute("id")||"",as=((Mc=md.privateuse)==null?void 0:Mc.includes("x-auto"))||kt.includes("_auto"),Jt=ee.querySelector("SegmentTemplate");if(Jt){let hr={representationId:(Cc=ee.getAttribute("id"))!=null?Cc:void 0,bandwidth:(Dc=ee.getAttribute("bandwidth"))!=null?Dc:void 0},ss=parseInt((Vc=ee.getAttribute("bandwidth"))!=null?Vc:"",10)/1e3,ns=(Bc=parseInt((Oc=Jt.getAttribute("startNumber"))!=null?Oc:"",10))!=null?Bc:1,xi=parseInt((_c=Jt.getAttribute("timescale"))!=null?_c:"",10),eo=(Nc=Jt.querySelectorAll("SegmentTimeline S"))!=null?Nc:[],Pi=Jt.getAttribute("media");if(!Pi)continue;let os=[],us=0,ls="",wi=0,mr=ns,Te=0;for(let Ge of eo){let Zt=parseInt((Fc=Ge.getAttribute("d"))!=null?Fc:"",10),Fe=parseInt((qc=Ge.getAttribute("r"))!=null?qc:"",10)||0,Rt=parseInt((Uc=Ge.getAttribute("t"))!=null?Uc:"",10);Te=Number.isFinite(Rt)?Rt:Te;let ei=Zt/xi*1e3,$t=Te/xi*1e3;for(let it=0;it<Fe+1;it++){let Lt=yt(Pi,C(w({},hr),{segmentNumber:mr.toString(10),segmentTime:(Te+it*Zt).toString(10)})),Ai=($t!=null?$t:0)+it*ei,br=Ai+ei;mr++,os.push({time:{from:Ai,to:br},url:Lt})}Te+=(Fe+1)*Zt,us+=(Fe+1)*ei}wi=Te/xi*1e3,ls=yt(Pi,C(w({},hr),{segmentNumber:mr.toString(10),segmentTime:Te.toString(10)}));let fr={time:{from:wi,to:1/0},url:ls},ht={type:"template",baseUrl:Xt,segmentTemplateUrl:Pi,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:fr,timescale:xi};rs={id:kt,kind:"text",segmentReference:ht,profiles:[],duration:v,bitrate:ss,mime:"",codecs:"",width:0,height:0,isAuto:as}}else rs={id:kt,isAuto:as,kind:"text",url:Xt}}else{let kt=(jc=(Hc=ee.getAttribute("contentType"))!=null?Hc:At==null?void 0:At.split("/")[0])!=null?jc:Zn,as=(Gc=(Qc=te.getAttribute("profiles"))==null?void 0:Qc.split(","))!=null?Gc:[],Jt=parseInt((Wc=ee.getAttribute("width"))!=null?Wc:"",10),hr=parseInt((Yc=ee.getAttribute("height"))!=null?Yc:"",10),ss=parseInt((zc=ee.getAttribute("bandwidth"))!=null?zc:"",10)/1e3,ns=(Kc=ee.getAttribute("frameRate"))!=null?Kc:"",xi=(Xc=ee.getAttribute("quality"))!=null?Xc:void 0,eo=ns?fy(ns):void 0,Pi=(Jc=ee.getAttribute("id"))!=null?Jc:"id"+($++).toString(10),os=kt==="video"?`${hr}p`:kt==="audio"?`${ss}Kbps`:is,us=`${Pi}@${os}`,ls=[...F,...zT,...as],wi,mr=ee.querySelector("SegmentBase"),Te=(Zc=ee.querySelector("SegmentTemplate"))!=null?Zc:XT;if(mr){let ht=(td=(ed=ee.querySelector("SegmentBase Initialization"))==null?void 0:ed.getAttribute("range"))!=null?td:"",[Ge,Zt]=ht.split("-").map(Lt=>parseInt(Lt,10)),Fe={from:Ge,to:Zt},Rt=(id=ee.querySelector("SegmentBase"))==null?void 0:id.getAttribute("indexRange"),[ei,$t]=Rt?Rt.split("-").map(Lt=>parseInt(Lt,10)):[],it=Rt?{from:ei,to:$t}:void 0;wi={type:"byteRange",url:Xt,initRange:Fe,indexRange:it}}else if(Te){let ht={representationId:(rd=ee.getAttribute("id"))!=null?rd:void 0,bandwidth:(ad=ee.getAttribute("bandwidth"))!=null?ad:void 0},Ge=parseInt((sd=Te.getAttribute("timescale"))!=null?sd:"",10),Zt=(nd=Te.getAttribute("initialization"))!=null?nd:"",Fe=Te.getAttribute("media"),Rt=(ud=parseInt((od=Te.getAttribute("startNumber"))!=null?od:"",10))!=null?ud:1,ei=yt(Zt,ht);if(!Fe)throw new ReferenceError("No media attribute in SegmentTemplate");let $t=(ld=Te.querySelectorAll("SegmentTimeline S"))!=null?ld:[],it=[],Lt=0,Ai="",br=0;if($t.length){let cs=Rt,We=0;for(let ki of $t){let rt=parseInt((cd=ki.getAttribute("d"))!=null?cd:"",10),ti=parseInt((dd=ki.getAttribute("r"))!=null?dd:"",10)||0,ds=parseInt((pd=ki.getAttribute("t"))!=null?pd:"",10);We=Number.isFinite(ds)?ds:We;let to=rt/Ge*1e3,io=We/Ge*1e3;for(let ps=0;ps<ti+1;ps++){let eI=yt(Fe,C(w({},ht),{segmentNumber:cs.toString(10),segmentTime:(We+ps*rt).toString(10)})),fd=(io!=null?io:0)+ps*to,tI=fd+to;cs++,it.push({time:{from:fd,to:tI},url:eI})}We+=(ti+1)*rt,Lt+=(ti+1)*to}br=We/Ge*1e3,Ai=yt(Fe,C(w({},ht),{segmentNumber:cs.toString(10),segmentTime:We.toString(10)}))}else if(xC(v)){let We=parseInt((hd=Te.getAttribute("duration"))!=null?hd:"",10)/Ge*1e3,ki=Math.ceil(v/We),rt=0;for(let ti=1;ti<ki;ti++){let ds=yt(Fe,C(w({},ht),{segmentNumber:ti.toString(10),segmentTime:rt.toString(10)}));it.push({time:{from:rt,to:rt+We},url:ds}),rt+=We}br=rt,Ai=yt(Fe,C(w({},ht),{segmentNumber:ki.toString(10),segmentTime:rt.toString(10)}))}let ZT={time:{from:br,to:1/0},url:Ai};wi={type:"template",baseUrl:Xt,segmentTemplateUrl:Fe,initUrl:ei,totalSegmentsDurationMs:Lt,segments:it,nextSegmentBeyondManifest:ZT,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!kt||!At)continue;let fr={video:"video",audio:"audio",text:"text"}[kt];if(!fr)continue;Ei||(Ei=fr),rs={id:us,kind:fr,segmentReference:wi,profiles:ls,duration:v,bitrate:ss,mime:At,codecs:is,width:Jt,height:hr,fps:eo,quality:xi}}se.language||(se.language=wt),se.label||(se.label=pr),se.mime||(se.mime=At),se.codecs||(se.codecs=is),se.hdr||(se.hdr=Ei==="video"&&Fl(is)),se.representations.push(rs)}if(Ei){let ee=r[Ei].find(wt=>wt.id===se.id);if(ee&&se.representations.every(wt=>xe(wt.segmentReference)))for(let wt of ee.representations){let pr=se.representations.find(At=>At.id===wt.id),ts=pr==null?void 0:pr.segmentReference,Xt=wt.segmentReference;Xt.segments.push(...ts.segments),Xt.nextSegmentBeyondManifest=ts.nextSegmentBeyondManifest}else r[Ei].push(se)}}return{duration:v,streams:r,baseUrls:n,live:g}};var ky=O(qe(),1);import{isNonNullable as Ay}from"@vkontakte/videoplayer-shared/es2015";var oe=(a,e)=>Ay(a)&&Ay(e)&&a.readyState==="open"&&(0,ky.default)([...a.activeSourceBuffers],e);var Ma=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new bi(0);this.currentLowLatencySegmentLength$=new bi(0);this.currentSegmentLength$=new bi(0);this.onLastSegment$=new bi(!1);this.fullyBuffered$=new bi(!1);this.playingRepresentation$=new bi(void 0);this.playingRepresentationInit$=new bi(void 0);this.error$=new wC;this.gaps=[];this.subscription=new AC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ve;this.switchAbortController=new ve;this.destroyAbortController=new ve;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=jt(this.destroyAbortController.signal,function(e){return ue(this,null,function*(){let t=this.representations.get(e);Ce(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new xS(this.sourceBuffer),this.subscription.add(zl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Tt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Tt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(zl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Tt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!oe(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ml(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);Ce(i,"No init buffer for starting representation"),Ce(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=jt(this.destroyAbortController.signal,function(e,t=!1){return ue(this,null,function*(){if(!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Se(s)||Se(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!oe(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();ir(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new ms(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=jt(this.destroyAbortController.signal,function(e,t=!1){return ue(this,null,function*(){if(!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Ce(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Se(s)||Se(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Ce(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!oe(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();ir(n)&&(this.isLive||(this.bufferLimit=1/0,yield new ms(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=jt(this.destroyAbortController.signal,function(e){return ue(this,null,function*(){var u,l;let t=(u=(0,yn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!xe(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);Ce(r);let s=this.segments.get(i);Ce(s,"No segments for starting representation");let n=this.initData.get(i);if(Ce(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){!oe(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ve,jt(this.switchAbortController.signal,function(i,r=!1){return ue(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);Ce(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Se(o)||Se(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Ce(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!oe(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();ir(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(){!Se(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return E(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ve,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Se(e)||Se(this.downloadingRepresentationId)||Se(this.playingRepresentationId)||Se(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer)||ir(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Ce(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);ir(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)&&Ml(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,Sn.default)(u,r))c="high";else{let d=(0,rr.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,rr.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;ir(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,yn.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,yn.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||!xe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>C(w({},p),{status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,rr.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;Ce(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(!xe(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=yt(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&&aa&&aa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&aa&&aa(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,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&&oe(this.mediaSource,this.sourceBuffer)&&!(Ut(this.sourceBuffer.buffered,h)&&Ut(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}loadSegments(e,t,i="auto"){return E(this,null,function*(){xe(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return E(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield jt(o,function(){return ue(this,null,function*(){let c=Kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=vn(),!c)return;let d=new DataView(c),h=$a(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?yield Promise.all(l):yield 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]),La(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())xe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return E(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield jt(n,function(){return ue(this,null,function*(){let u=Kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),zl(window,"online").pipe(PC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=vn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),La(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(xe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,rr.default)(e,0).byte.from,to:(0,rr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>E(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Tt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!xe(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=vn();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Tt.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,Sn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return E(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!oe(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=$a(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return E(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!oe(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-i,h=c.byte.to-i,p=h-d+1,m=d<r,b=h<=r;if(!m)continue;let g=$a(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!(Se(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer))){!this.isLive&&U.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ut(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ut(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Tt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ql(e.segment)&&(e.segment.size=e.fedBytes);for(let 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=$l(()=>(0,Ry.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return E(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?jt(this.destroyAbortController.signal,function(){return ue(this,null,function*(){let o=Kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,$a(e.mime),r)).then(o=>E(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&xe(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:Tt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return E(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return E(this,null,function*(){if(!this.sourceBuffer||!oe(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Se(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(w({},u.time)),r=n(r);let l=Ql(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,Sn.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?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return E(this,null,function*(){if(!this.sourceBuffer||!oe(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||!oe(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||!oe(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Se(e)?0:Ji(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!oe(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||!oe(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=$l(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Tt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Se(this.sourceBuffer)||!oe(this.mediaSource,this.sourceBuffer)||Se(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:Tt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Ca=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var $y=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 Da,assertNever as My,fromEvent as Cy,merge as kC,now as Va,Subscription as RC,Subject as Dy,ValueSubject as Xl,flattenObject as ar,ErrorCategory as Oa}from"@vkontakte/videoplayer-shared/es2015";var Ly=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var In=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Xl(void 0);this.lastConnectionReused$=new Xl(void 0);this.lastRequestFirstBytes$=new Xl(void 0);this.recoverableError$=new Dy;this.error$=new Dy;this.abortAllController=new ve;this.subscription=new RC;this.fetchManifest=Da(this.abortAllController.signal,function(e){return ue(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Ca(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ly(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Tn);return r?(t.log("success",ar({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ar({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Da(this.abortAllController.signal,function(l){return ue(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var L,Q;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let N=new URL(c,location.href);N.searchParams.append("bytes",`${i.from}-${i.to}`),c=N.toString();break}default:My(t)}this.requestQuic&&(c=Ca(c));let p=this.abortAllController.signal,m;if(n){let N=new ve;if(m=kC(Cy(this.abortAllController.signal,"abort"),Cy(n,"abort")).subscribe(()=>{try{N.abort()}catch(Z){Tn(Z)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(Z){Tn(Z)}p=N.signal}let b=Va();h.log("startRequest",ar({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:p}),v=Va();if(!g)return h.error("error",{message:"No response in request"}),h.end(),m==null||m.unsubscribe(),null;if((L=this.throughputEstimator)==null||L.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:N}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){m==null||m.unsubscribe();let N=Va(),Z={requestStartedAt:b,requestEndedAt:N,duration:N-b};return h.log("endRequest",ar(Z)),h.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),I=S.getReader();o&&((Q=this.throughputEstimator)==null||Q.trackStream(y,u));let T=0,$=new Uint8Array(0),F=!1,q=N=>{m==null||m.unsubscribe(),F=!0,Tn(N)},K=Da(p,function(R){return ue(this,arguments,function*({done:N,value:Z}){if(T===0&&this.lastRequestFirstBytes$.next(Va()-b),p.aborted){m==null||m.unsubscribe();return}if(!N&&Z){let D=new Uint8Array($.length+Z.length);D.set($),D.set(Z,$.length),$=D,T+=Z.byteLength,r==null||r(new DataView($.buffer),T),yield I==null?void 0:I.read().then(K,q)}})}.bind(this));yield I==null?void 0:I.read().then(K,q),m==null||m.unsubscribe();let x=Va(),j={failed:F,requestStartedAt:b,requestEndedAt:x,duration:x-b};return F?(h.error("endRequest",ar(j)),h.end(),null):(h.log("endRequest",ar(j)),h.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Da(this.abortAllController.signal,function(e,t,i){return ue(this,null,function*(){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=Da(this.abortAllController.signal,function(e,t){return ue(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>C(w({},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}=$y(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return E(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:My(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return E(this,null,function*(){let i=yield lt(e,t);if(i.ok)return i;let r=yield i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Oa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Oa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Oa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Oa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Oa.FATAL})}})}},Tn=a=>{if(!La(a))throw a};var gi=(a,e,t)=>t*e+(1-t)*a,Jl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Vy=(a,e,t,i)=>{let r=0,s=t,n=Jl(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 $C,ValueSubject as Oy}from"@vkontakte/videoplayer-shared/es2015";var Qt=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 Oy(e.initial),this.debounced$=new Oy(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=at(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)&&($C(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var En=class extends Qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=gi(this.slow,e,this.params.emaAlphaSlow),this.fast=gi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xn=class extends Qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Jl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=gi(this.emaSmoothed,e,this.params.emaAlpha);let i=Vy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Pn=class extends Qt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?gi(this.smoothed,t,this.params.emaAlpha):t}};var vi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new En({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new xn({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 Pn(w({initial:e,label:"liveEdgeDelay"},t))}};var Zl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as LC,ValueSubject as MC}from"@vkontakte/videoplayer-shared/es2015";var Ba=class a{constructor(e,t){this.currentRepresentation$=new MC(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(!LC(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(C(w({},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&&xe(t.segmentReference))}};var An=O(Nt(),1);import{assertNever as kn}from"@vkontakte/videoplayer-shared/es2015";var By=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=U.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 kn(c)}})},wn=a=>{let{webmDecodingInfo:e}=U.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:kn(a)}return[t,i]},_y=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...wn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(U.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",...wn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...wn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...wn(a),...r,"HLS","HLS_ONDEMAND"];default:kn(e)}return U.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Ny=({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=U.device.isMac&&U.browser.isSafari;if(U.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:kn(a)}else U.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"]},ec=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Fy=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,An.default)(t.value.split("."),0)}for(let t of a){let i=(0,An.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,An.default)(e.value.split("."),0)};var qC=["timeupdate","progress","play","seeked","stalled","waiting"],UC=["timeupdate","progress","loadeddata","playing","seeked"];var Ln=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Hy;this.representationSubscription=new Hy;this.state$=new B("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new $n;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.isActiveLive$=new re(!1);this.isLowLatency$=new re(!1);this.liveDuration$=new re(0);this.liveSeekableDuration$=new re(0);this.liveAvailabilityStartTime$=new re(0);this.liveStreamStatus$=new re(void 0);this.bufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.fetcherRecoverableError$=new $n;this.fetcherError$=new $n;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new $n;this.gapWatchdogActive=!1;this.destroyController=new ve;this.initManifest=ic(this.destroyController.signal,function(e,t,i){return ue(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ge(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:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ic(this.destroyController.signal,function(){return ue(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=wy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=vS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let 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=Je())==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=Fy(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);U.display.isHDR&&p&&m?r.video=r.video.filter(g=>g.hdr):b&&(r.video=r.video.filter(g=>!g.hdr))}}let s=C(w({},t),{streams:r});return this.tracer.log("updateManifestEnd",Na(s)),s})}.bind(this));this.initRepresentations=ic(this.destroyController.signal,function(e,t,i){return ue(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",Na({initialVideo:e,initialAudio:t,sourceHls:i})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(It(p,"error").pipe(Rn(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Ng():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&an())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 Ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Fa(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new Ma("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ba.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ba(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(Si(...UC.map(p=>It(this.element,p))).pipe(or(p=>this.element?Ji(this.element.buffered,this.element.currentTime*1e3):0),_a(),NC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Si(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(_a()).subscribe(m=>this.liveStreamEndTimestamp=ac())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=rc(1e3).subscribe(m=>{let b=Xs(this.manifestUrlString,2);this.manifestUrlString=ge(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(It(this.element,"play").subscribe(m=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add(nr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(or(({isActiveLive:m,isLowLatency:b})=>m&&b),_a()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||Zl(this.element,1)})),this.representationSubscription.add(nr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Rn(({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(nr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Rn(({isLive:m})=>m),_a((m,b)=>b.bufferLength<m.bufferLength),or(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=Xs(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(nr({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),Zl(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,$;return($=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?$:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(nr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(FC(1e3)).subscribe(g=>E(this,[g],function*({liveLoadBufferLength:m,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,S=Xs(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,F=isFinite(m)?m:b,q=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),K=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(K);let x="none";if(q?x="active_low_latency":this.isLowLatency$.getValue()&&K?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),x="active_low_latency"):S!==0&&F<I?x="live_forward_buffering":F<I+$&&(x="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),x==="live_forward_buffering"||x==="live_with_target_offset"){let j=p-(I+T),L=this.normolizeLiveOffset(Math.trunc(S+j/v)),Q=Math.abs(L-S),N=0;!m||Q<=this.tuning.dashCmafLive.offsetCalculationError?N=S:L>0&&Q>this.tuning.dashCmafLive.offsetCalculationError&&(N=L),this.manifestUrlString=ge(this.manifestUrlString,N,2)}(x==="live_with_target_offset"||x==="live_forward_buffering")&&(p=0,yield this.updateLive())}),m=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=Si(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(or(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Si(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(or(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=nr({allBuffersFull:l,someBufferEnded:c}).pipe(_a(),or(({allBuffersFull:p,someBufferEnded:m})=>p&&m),Rn(p=>p));if(this.representationSubscription.add(Si(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:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add(Si(...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,sc.default)((0,sc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let b=[];return m.duration&&b.push(m.duration),xe(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&b.push(m.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Fa(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=rc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.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 In({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=vi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,w({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return E(this,null,function*(){var r,s,n;sr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ac()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ge(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){sr(this.element),this.state$.setState("running"),this.subscription.add(Si(...qC.map(e=>It(this.element,e)),It(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(It(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(It(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ut(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,$,F;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=ac(),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 q=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(q).catch(K=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:K})}),r.liveLastOffset=q}else{let q=this.element.currentTime*1e3;($=this.videoBufferManager)==null||$.maintain(q),(F=this.audioBufferManager)==null||F.maintain(q),r.position=q}this.tracer.log("stallIntervalCallback",Na(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=rc(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return E(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return E(this,null,function*(){var r,s,n,o,u;sr(this.element),sr(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),Ut(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Uy(this.element)||Uy(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Na({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Fa(this.element)&&Fa(this.source)&&Fa(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=_C(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}updateLive(){return E(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),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=C(w({},i),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Na(i)))}}};var Mn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Cn=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/at(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=w({},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*at(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 jy=`attribute vec2 a_vertex;
|
|
14
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Sp=U(Ft(),1);import{videoSizeToQuality as Y$}from"@vkontakte/videoplayer-shared/es2015";var yI=({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:Y$({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},TI=({id:s,bitrate:e})=>({id:s,bitrate:e}),II=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),xI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),vp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Sp.default)(i.split("."),0),isDefault:r}),yp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Sp.default)(r.split("."),0)}),Tp=s=>"url"in s,tt=s=>s.type==="template",vn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var EI=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},cr=(s,e)=>{for(let t of s)if(e(t))return t;return null},K$=(s,e)=>{let t=0;return()=>{let i=Date.now();i-t>=e&&(s(),t=i)}},wI=s=>{let e=!1,t=K$(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}},Vu=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var AI=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},Si=(s,e)=>{let t=s;t=(0,Ip.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,kI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ip.default)(t,n,(o,u)=>PI(a)?o:PI(u)?a:(0,RI.default)(a,parseInt(u,10),"0"))}return t},LI=(s,e)=>{var q,P,$,M,B,A,C,k,O,ee,te,H,Pt,K,he,xe,ze,At,ei,kt,Ht,Pi,Ai,Ss,vs,ys,Ts,Is,xs,Es,ws,Ps,As,ks,Rs,Ms,Ls,Bs,Ds,$s,Cs,Vs,Os,_s,Fs,Ns,Us,qs,Hs,js,Gs,zs,Ws,Qs,Ys,Ks,Xs,Js,Zs,ea,ta;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 N,We;return(We=(N=ce.textContent)==null?void 0:N.trim())!=null?We:""}),o=(q=(0,MI.default)(n,0))!=null?q:"",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")],T=v.reduce((ce,N)=>D(x({},ce),{[N.id]:N.children}),{}),w=v.reduce((ce,N)=>D(x({},ce),{[N.id]:N.getAttribute("duration")}),{});y?S=AI(y):(0,xp.default)(w).filter(ce=>ce).length&&!u?S=(0,xp.default)(w).reduce((ce,N)=>{var We;return ce+((We=AI(N))!=null?We:0)},0):m&&(S=parseInt(m,10));let E=0,L=($=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?$:[];for(let ce of v.map(N=>N.id))for(let N of T[ce]){let We=(M=N.getAttribute("id"))!=null?M:"id"+(E++).toString(10),Rt=(B=N.getAttribute("mimeType"))!=null?B:"",Hi=(A=N.getAttribute("codecs"))!=null?A:"",ji=(C=N.getAttribute("contentType"))!=null?C:Rt==null?void 0:Rt.split("/")[0],$l=(O=(k=N.getAttribute("profiles"))==null?void 0:k.split(","))!=null?O:[],ia=(te=vI((ee=N.getAttribute("lang"))!=null?ee:""))!=null?te:{},ti=(K=(Pt=(H=N.querySelector("Label"))==null?void 0:H.textContent)==null?void 0:Pt.trim())!=null?K:void 0,Cl=N.querySelectorAll("Representation"),Vl=N.querySelector("SegmentTemplate"),Ol=(xe=(he=N.querySelector("Role"))==null?void 0:he.getAttribute("value"))!=null?xe:void 0,dt=ji,W={id:We,language:ia.language,isDefault:Ol==="main",label:ti,codecs:Hi,hdr:dt==="video"&&ts(Hi),mime:Rt,representations:[]};for(let F of Cl){let Ae=(ze=F.getAttribute("lang"))!=null?ze:void 0,Mt=(ei=(At=ti!=null?ti:N.getAttribute("label"))!=null?At:F.getAttribute("label"))!=null?ei:void 0,ii=(Pi=(Ht=(kt=F.querySelector("BaseURL"))==null?void 0:kt.textContent)==null?void 0:Ht.trim())!=null?Pi:"",Qe=new URL(ii||o,e).toString(),ke=(Ai=F.getAttribute("mimeType"))!=null?Ai:Rt,ri=(vs=(Ss=F.getAttribute("codecs"))!=null?Ss:Hi)!=null?vs:"",si;if(ji==="text"){let Re=F.getAttribute("id")||"",ai=((ys=ia.privateuse)==null?void 0:ys.includes("x-auto"))||Re.includes("_auto"),Ye=F.querySelector("SegmentTemplate");if(Ye){let Lt={representationId:(Ts=F.getAttribute("id"))!=null?Ts:void 0,bandwidth:(Is=F.getAttribute("bandwidth"))!=null?Is:void 0},ni=parseInt((xs=F.getAttribute("bandwidth"))!=null?xs:"",10)/1e3,oi=(ws=parseInt((Es=Ye.getAttribute("startNumber"))!=null?Es:"",10))!=null?ws:1,pt=parseInt((Ps=Ye.getAttribute("timescale"))!=null?Ps:"",10),Gi=(As=Ye.querySelectorAll("SegmentTimeline S"))!=null?As:[],ht=Ye.getAttribute("media");if(!ht)continue;let ui=[],li=0,ci="",ft=0,Bt=oi,ie=0;for(let de of Gi){let Ke=parseInt((ks=de.getAttribute("d"))!=null?ks:"",10),ne=parseInt((Rs=de.getAttribute("r"))!=null?Rs:"",10)||0,Me=parseInt((Ms=de.getAttribute("t"))!=null?Ms:"",10);ie=Number.isFinite(Me)?Me:ie;let Xe=Ke/pt*1e3,Le=ie/pt*1e3;for(let Se=0;Se<ne+1;Se++){let Be=Si(ht,D(x({},Lt),{segmentNumber:Bt.toString(10),segmentTime:(ie+Se*Ke).toString(10)})),mt=(Le!=null?Le:0)+Se*Xe,$t=mt+Xe;Bt++,ui.push({time:{from:mt,to:$t},url:Be})}ie+=(ne+1)*Ke,li+=(ne+1)*Xe}ft=ie/pt*1e3,ci=Si(ht,D(x({},Lt),{segmentNumber:Bt.toString(10),segmentTime:ie.toString(10)}));let Dt={time:{from:ft,to:1/0},url:ci},Ee={type:"template",baseUrl:Qe,segmentTemplateUrl:ht,initUrl:"",totalSegmentsDurationMs:li,segments:ui,nextSegmentBeyondManifest:Dt,timescale:pt};si={id:Re,kind:"text",segmentReference:Ee,profiles:[],duration:S,bitrate:ni,mime:"",codecs:"",width:0,height:0,isAuto:ai}}else si={id:Re,isAuto:ai,kind:"text",url:Qe}}else{let Re=(Bs=(Ls=F.getAttribute("contentType"))!=null?Ls:ke==null?void 0:ke.split("/")[0])!=null?Bs:ji,ai=($s=(Ds=N.getAttribute("profiles"))==null?void 0:Ds.split(","))!=null?$s:[],Ye=parseInt((Cs=F.getAttribute("width"))!=null?Cs:"",10),Lt=parseInt((Vs=F.getAttribute("height"))!=null?Vs:"",10),ni=parseInt((Os=F.getAttribute("bandwidth"))!=null?Os:"",10)/1e3,oi=(_s=F.getAttribute("frameRate"))!=null?_s:"",pt=(Fs=F.getAttribute("quality"))!=null?Fs:void 0,Gi=oi?Cu(oi):void 0,ht=(Ns=F.getAttribute("id"))!=null?Ns:"id"+(E++).toString(10),ui=Re==="video"?`${Lt}p`:Re==="audio"?`${ni}Kbps`:ri,li=`${ht}@${ui}`,ci=[...L,...$l,...ai],ft,Bt=F.querySelector("SegmentBase"),ie=(Us=F.querySelector("SegmentTemplate"))!=null?Us:Vl;if(Bt){let Ee=(Hs=(qs=F.querySelector("SegmentBase Initialization"))==null?void 0:qs.getAttribute("range"))!=null?Hs:"",[de,Ke]=Ee.split("-").map(Be=>parseInt(Be,10)),ne={from:de,to:Ke},Me=(js=F.querySelector("SegmentBase"))==null?void 0:js.getAttribute("indexRange"),[Xe,Le]=Me?Me.split("-").map(Be=>parseInt(Be,10)):[],Se=Me?{from:Xe,to:Le}:void 0;ft={type:"byteRange",url:Qe,initRange:ne,indexRange:Se}}else if(ie){let Ee={representationId:(Gs=F.getAttribute("id"))!=null?Gs:void 0,bandwidth:(zs=F.getAttribute("bandwidth"))!=null?zs:void 0},de=parseInt((Ws=ie.getAttribute("timescale"))!=null?Ws:"",10),Ke=(Qs=ie.getAttribute("initialization"))!=null?Qs:"",ne=ie.getAttribute("media"),Me=(Ks=parseInt((Ys=ie.getAttribute("startNumber"))!=null?Ys:"",10))!=null?Ks:1,Xe=Si(Ke,Ee);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Le=(Xs=ie.querySelectorAll("SegmentTimeline S"))!=null?Xs:[],Se=[],Be=0,mt="",$t=0;if(Le.length){let di=Me,pe=0;for(let bt of Le){let ve=parseInt((Js=bt.getAttribute("d"))!=null?Js:"",10),Je=parseInt((Zs=bt.getAttribute("r"))!=null?Zs:"",10)||0,pi=parseInt((ea=bt.getAttribute("t"))!=null?ea:"",10);pe=Number.isFinite(pi)?pi:pe;let zi=ve/de*1e3,Wi=pe/de*1e3;for(let hi=0;hi<Je+1;hi++){let Fl=Si(ne,D(x({},Ee),{segmentNumber:di.toString(10),segmentTime:(pe+hi*ve).toString(10)})),ra=(Wi!=null?Wi:0)+hi*zi,Nl=ra+zi;di++,Se.push({time:{from:ra,to:Nl},url:Fl})}pe+=(Je+1)*ve,Be+=(Je+1)*zi}$t=pe/de*1e3,mt=Si(ne,D(x({},Ee),{segmentNumber:di.toString(10),segmentTime:pe.toString(10)}))}else if(X$(S)){let pe=parseInt((ta=ie.getAttribute("duration"))!=null?ta:"",10)/de*1e3,bt=Math.ceil(S/pe),ve=0;for(let Je=1;Je<bt;Je++){let pi=Si(ne,D(x({},Ee),{segmentNumber:Je.toString(10),segmentTime:ve.toString(10)}));Se.push({time:{from:ve,to:ve+pe},url:pi}),ve+=pe}$t=ve,mt=Si(ne,D(x({},Ee),{segmentNumber:bt.toString(10),segmentTime:ve.toString(10)}))}let _l={time:{from:$t,to:1/0},url:mt};ft={type:"template",baseUrl:Qe,segmentTemplateUrl:ne,initUrl:Xe,totalSegmentsDurationMs:Be,segments:Se,nextSegmentBeyondManifest:_l,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Re||!ke)continue;let Dt={video:"video",audio:"audio",text:"text"}[Re];if(!Dt)continue;dt||(dt=Dt),si={id:li,kind:Dt,segmentReference:ft,profiles:ci,duration:S,bitrate:ni,mime:ke,codecs:ri,width:Ye,height:Lt,fps:Gi,quality:pt}}W.language||(W.language=Ae),W.label||(W.label=Mt),W.mime||(W.mime=ke),W.codecs||(W.codecs=ri),W.hdr||(W.hdr=dt==="video"&&ts(ri)),W.representations.push(si)}if(dt){let F=r[dt].find(Ae=>Ae.id===W.id);if(F&&W.representations.every(Ae=>tt(Ae.segmentReference)))for(let Ae of F.representations){let Mt=W.representations.find(ke=>ke.id===Ae.id),ii=Mt==null?void 0:Mt.segmentReference,Qe=Ae.segmentReference;Qe.segments.push(...ii.segments),Qe.nextSegmentBeyondManifest=ii.nextSegmentBeyondManifest}else r[dt].push(W)}}return{duration:S,streams:r,baseUrls:n,live:g}};import{isNonNullable as BI}from"@vkontakte/videoplayer-shared/es2015";var j=(s,e)=>BI(s)&&BI(e)&&s.readyState==="open"&&J$(s,e);function J$(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}import{fromEvent as Z$,Subscription as eC}from"@vkontakte/videoplayer-shared/es2015";var Ou=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new eC;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(Z$(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!j(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Vu(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var yn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new pr(0);this.currentLowLatencySegmentLength$=new pr(0);this.currentSegmentLength$=new pr(0);this.onLastSegment$=new pr(!1);this.fullyBuffered$=new pr(!1);this.playingRepresentation$=new pr(void 0);this.playingRepresentationInit$=new pr(void 0);this.error$=new iC;this.gaps=[];this.subscription=new rC;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.sourceBufferBufferedDiff=null;this.startWith=Oi(this.destroyAbortController.signal,function(e){return Q(this,null,function*(){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 MT(this.sourceBuffer),this.sourceBufferBufferedDiff=new Ou(this.mediaSource,this.sourceBuffer),this.subscription.add(DI(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:dr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!j(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Jr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=fe(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);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=Oi(this.destroyAbortController.signal,function(e,t=!1){return Q(this,null,function*(){if(!j(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(je(a)||je(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||!j(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,yield new Qi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Oi(this.destroyAbortController.signal,function(e,t=!1){return Q(this,null,function*(){if(!j(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(je(a)||je(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||!j(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,yield new Qi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Oi(this.destroyAbortController.signal,function(e){return Q(this,null,function*(){var u,l;let t=(u=(0,Nu.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||!tt(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){!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Oi(this.switchAbortController.signal,function(i,r=!1){return Q(this,null,function*(){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(je(o)||je(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||!j(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(){!je(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return I(this,null,function*(){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(je(e)||je(this.downloadingRepresentationId)||je(this.playingRepresentationId)||je(this.sourceBuffer)||!j(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=fe(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=fe(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,Fu.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!=null&&u.length)&&fe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,rs.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-fe(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,persistent:!0}),i=a.time.to;is(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}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,Nu.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,Nu.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||!tt(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>D(x({},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){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!tt(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=Si(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,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&Kt&&Kt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Kt&&Kt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),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&&j(this.mediaSource,this.sourceBuffer)&&!(He(this.sourceBuffer.buffered,h)&&He(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}loadSegments(e,t,i="auto"){return I(this,null,function*(){tt(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return I(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Oi(o,function(){return Q(this,null,function*(){let d=wp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=_u(),!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?yield Promise.all(l):yield 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())tt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return I(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Oi(n,function(){return Q(this,null,function*(){let u=wp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),DI(window,"online").pipe(tC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=_u(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),vn(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(tt(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:(o,u)=>I(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=_u(),yield 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:dr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!tt(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=_u();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:dr.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,Fu.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return I(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!j(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=Sn(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return I(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!j(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let{segment:d}=l,c=d.byte.from-i,h=d.byte.to-i,p=h-c+1,f=c<r,m=h<=r;if(f){if(d.status==="downloading"&&m){d.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(g,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?g:Sn(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(d.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}}})}onSegmentFullyAppended(e,t){if(!(je(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer))){!this.isLive&&z.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(He(this.sourceBuffer.buffered,e.segment.time.from,100)&&He(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:dr.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",Tp(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,$I.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return I(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Oi(this.destroyAbortController.signal,function(){return Q(this,null,function*(){let o=wp(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(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&&tt(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:dr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return I(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return I(this,null,function*(){if(!this.sourceBuffer||!j(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||je(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(x({},o.time));let u=Tp(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,Fu.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=EI(r),(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1})}abortBuffer(){return I(this,null,function*(){if(!this.sourceBuffer||!j(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||!j(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||!j(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||!j(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||je(e)?0:fe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!j(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(a=>{if(a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.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||!j(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||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:dr.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(je(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer)||je(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Vu(this.sourceBuffer.buffered),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=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],h=e[d+1];u||(u=c-t<=n&&h+t>=o),(n>=c&&n<h-t||o>c+t&&o<=h)&&(l+=1)}u||(l===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:dr.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var _i=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Uu=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 sC,now as Pp,Subject as OI,ValueSubject as Ap,ErrorCategory as In,SubscriptionRemovable as aC}from"@vkontakte/videoplayer-shared/es2015";var qu=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var ju=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1,useEnableSubtitlesParam:r=!1}){this.lastConnectionType$=new Ap(void 0);this.lastConnectionReused$=new Ap(void 0);this.lastRequestFirstBytes$=new Ap(void 0);this.recoverableError$=new OI;this.error$=new OI;this.abortAllController=new ae;this.subscription=new aC;this.fetchManifest=Tn(this.abortAllController.signal,function(e){return Q(this,null,function*(){let t=e;this.requestQuic&&(t=_i(t)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(t=qu(t));let i=yield this.doFetch(t,{signal:this.abortAllController.signal}).catch(Hu);return i?(this.onHeadersReceived(i.headers),i.text()):null})}.bind(this));this.fetch=Tn(this.abortAllController.signal,function(l){return Q(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var q,P;let d=e,c=new Headers;if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let $=new URL(d,location.href);$.searchParams.append("bytes",`${i.from}-${i.to}`),d=$.toString();break}default:CI(t)}this.requestQuic&&(d=_i(d));let h=this.abortAllController.signal,p;if(n){let $=new ae;if(p=sC(VI(this.abortAllController.signal,"abort"),VI(n,"abort")).subscribe(()=>{try{$.abort()}catch(M){Hu(M)}}),this.abortAllController.signal.aborted||n.aborted)try{$.abort()}catch(M){Hu(M)}h=$.signal}let f=Pp(),m=yield this.doFetch(d,{priority:a,headers:c,signal:h}),g=Pp();if(!m)return this.unsubscribeAbortSubscription(p),null;if((q=this.throughputEstimator)==null||q.addRawRtt(g-f),!m.ok||!m.body)return this.unsubscribeAbortSubscription(p),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!r&&!o)return this.unsubscribeAbortSubscription(p),m.arrayBuffer();let[S,y]=m.body.tee(),v=S.getReader();o&&((P=this.throughputEstimator)==null||P.trackStream(y,u));let T=0,w=new Uint8Array(0),E=!1,L=$=>{this.unsubscribeAbortSubscription(p),E=!0,Hu($)},_=Tn(h,function(B){return Q(this,arguments,function*({done:$,value:M}){if(T===0&&this.lastRequestFirstBytes$.next(Pp()-f),h.aborted){this.unsubscribeAbortSubscription(p);return}if(!$&&M){let A=new Uint8Array(w.length+M.length);A.set(w),A.set(M,w.length),w=A,T+=M.byteLength,r==null||r(new DataView(w.buffer),T),yield v==null?void 0:v.read().then(_,L)}})}.bind(this));return yield v==null?void 0:v.read().then(_,L),this.unsubscribeAbortSubscription(p),E?null:w.buffer})}.bind(this));this.fetchByteRangeRepresentation=Tn(this.abortAllController.signal,function(e,t,i){return Q(this,null,function*(){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,function(e,t){return Q(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>D(x({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.useEnableSubtitlesParam=r}onHeadersReceived(e){let{type:t,reused:i}=Uu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return I(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:CI(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}doFetch(e,t){return I(this,null,function*(){let i=yield wt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:In.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:In.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:In.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:In.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:In.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Hu=s=>{if(!vn(s))throw s};var vi=(s,e,t)=>t*e+(1-t)*s,kp=(s,e)=>s.reduce((t,i)=>t+i,0)/e,_I=(s,e,t,i)=>{let r=0,a=t,n=kp(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 nC,ValueSubject as FI}from"@vkontakte/videoplayer-shared/es2015";var Fi=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new FI(e.initial),this.debounced$=new FI(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Ze(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.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(nC(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed))}};var Gu=class extends Fi{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 zu=class extends Fi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=kp(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 Wu=class extends Fi{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 Gu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new zu({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 Wu(x({initial:e,label:"liveEdgeDelay"},t))}};var ss=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as oC,ValueSubject as uC}from"@vkontakte/videoplayer-shared/es2015";var xn=class s{constructor(e,t){this.currentRepresentation$=new uC(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(!oC(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(D(x({},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&&tt(t.segmentReference))}};var Yu=U(Ft(),1);import{assertNever as Ku}from"@vkontakte/videoplayer-shared/es2015";var NI=(s,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:a,codecs:n,nativeHlsSupported:o}=z.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 Ku(d)}})},Qu=s=>{let{webmDecodingInfo:e}=z.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:Ku(s)}return[t,i]},UI=({webmCodec:s,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Qu(s),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(z.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",...Qu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Qu(s),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Qu(s),...r,"HLS","HLS_ONDEMAND"];default:Ku(e)}return z.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=z.device.isMac&&z.browser.isSafari;if(z.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:Ku(s)}else z.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Rp=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Xu=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,Yu.default)(t.value.split("."),0)}for(let t of s){let i=(0,Yu.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,Yu.default)(e.value.split("."),0)};var fC=["timeupdate","progress","play","seeked","stalled","waiting"],mC=["timeupdate","progress","loadeddata","playing","seeked"];var el=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new $p;this.representationSubscription=new $p;this.state$=new G("none");this.currentVideoRepresentation$=new me(void 0);this.currentVideoRepresentationInit$=new me(void 0);this.currentAudioRepresentation$=new me(void 0);this.currentVideoSegmentLength$=new me(0);this.currentAudioSegmentLength$=new me(0);this.error$=new Zu;this.lastConnectionType$=new me(void 0);this.lastConnectionReused$=new me(void 0);this.lastRequestFirstBytes$=new me(void 0);this.currentLiveTextRepresentation$=new me(null);this.isLive$=new me(!1);this.isActiveLive$=new me(!1);this.isLowLatency$=new me(!1);this.liveDuration$=new me(0);this.liveSeekableDuration$=new me(0);this.liveAvailabilityStartTime$=new me(0);this.liveStreamStatus$=new me(void 0);this.bufferLength$=new me(0);this.liveLatency$=new me(void 0);this.liveLoadBufferLength$=new me(0);this.livePositionFromPlayer$=new me(0);this.currentStallDuration$=new me(0);this.videoLastDataObtainedTimestamp$=new me(0);this.fetcherRecoverableError$=new Zu;this.fetcherError$=new Zu;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Zu;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initedPruneBufferCallback=!1;this.initManifest=Lp(this.destroyController.signal,function(e,t,i){return Q(this,null,function*(){var r;this.element=e,this.manifestUrlString=Te(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=Lp(this.destroyController.signal,function(){return Q(this,null,function*(){var n,o;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Xt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=LI(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=$u(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=Tt())==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=Xu(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);z.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}return D(x({},t),{streams:r})})}.bind(this));this.initRepresentations=Lp(this.destroyController.signal,function(e,t,i){return Q(this,null,function*(){var h;as(this.manifest),as(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new $p,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Jt(p,"error").pipe(Ju(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?cu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Hr())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],wn(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)}xn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new xn(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(hr(...mC.map(p=>Jt(this.element,p))).pipe(os(p=>this.element?fe(this.element.buffered,this.element.currentTime*1e3):0),En(),hC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(hr(Jt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(En()).subscribe(f=>this.liveStreamEndTimestamp=Dp())),this.subscription.add(Jt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Bp(1e3).subscribe(f=>{let m=Li(this.manifestUrlString,2);this.manifestUrlString=Te(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Jt(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(ns({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(os(({isActiveLive:f,isLowLatency:m})=>f&&m),En()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ss(this.element,1)})),this.representationSubscription.add(ns({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ju(({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(ns({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ju(({isLive:f})=>f),En((f,m)=>m.bufferLength<f.bufferLength),os(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Li(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ns({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,T=f-S;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(T)>y&&(w=1+Math.sign(T)*v),ss(this.element,w)})),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(T=>{var w,E;return(E=(w=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?E:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(ns({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(GI(1e3)).subscribe(g=>I(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,y=Li(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,L=isFinite(f)?f:m,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),q=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(q);let P="none";if(_?P="active_low_latency":this.isLowLatency$.getValue()&&q?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),P="active_low_latency"):y!==0&&L<T?P="live_forward_buffering":L<T+E&&(P="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let $=p-(T+w),M=this.normolizeLiveOffset(Math.trunc(y+$/S)),B=Math.abs(M-y),A=0;!f||B<=this.tuning.dashCmafLive.offsetCalculationError?A=y:M>0&&B>this.tuning.dashCmafLive.offsetCalculationError&&(A=M),this.manifestUrlString=Te(this.manifestUrlString,A,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:Xt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=hr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(os(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=hr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(os(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=ns({allBuffersFull:l,someBufferEnded:d}).pipe(En(),os(({allBuffersFull:p,someBufferEnded:f})=>p&&f),Ju(p=>p));if(this.representationSubscription.add(hr(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(hr(...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,Cp.default)((0,Cp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],f=>f.representations),f=>{let m=[];return f.duration&&m.push(f.duration),tt(f.segmentReference)&&f.segmentReference.totalSegmentsDurationMs&&m.push(f.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&wn(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.bind(this));this.tick=()=>{var t,i,r,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=Bp(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.fetcher=new ju({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=yi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator))}seekLive(e){return I(this,null,function*(){var r,a,n;as(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Dp()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Te(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){as(this.element),this.state$.setState("running"),this.subscription.add(hr(...fC.filter(e=>e!=="timeupdate").map(e=>Jt(this.element,e)),Jt(window,"online"),Jt(this.element,"timeupdate").pipe(GI(300))).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Xt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Jt(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(Jt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&He(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,y,v,T,w,E,L;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=Dp(),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=(w=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?w: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 _=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(_).catch(q=>{this.error$.next({id:"stallIntervalCallback",category:Xt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:q})}),r.liveLastOffset=_}else{let _=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(_),(L=this.audioBufferManager)==null||L.maintain(_),r.position=_}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Bp(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()}switchRepresentation(e,t,i=!1){return I(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return I(this,null,function*(){var r,a,n,o,u;as(this.element),as(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),He(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(jI(this.element)||jI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3)})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;wn(this.element)&&wn(this.source)&&wn(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return I(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.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)(o.persistent||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}}};var tl=class{constructor(e,t){this.fov=e,this.orientation=t}};var il=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/Ze(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=x({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,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*Ze(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 WI=`attribute vec2 a_vertex;
|
|
71
15
|
attribute vec2 a_texel;
|
|
72
16
|
|
|
73
17
|
varying vec2 v_texel;
|
|
@@ -78,7 +22,7 @@ void main(void) {
|
|
|
78
22
|
// save texel vector to pass to fragment shader
|
|
79
23
|
v_texel = a_texel;
|
|
80
24
|
}
|
|
81
|
-
`;var
|
|
25
|
+
`;var QI=`#ifdef GL_ES
|
|
82
26
|
precision highp float;
|
|
83
27
|
precision highp int;
|
|
84
28
|
#else
|
|
@@ -121,6 +65,13 @@ void main(void) {
|
|
|
121
65
|
// sample using new coordinates
|
|
122
66
|
gl_FragColor = texture2D(u_texture, tc);
|
|
123
67
|
}
|
|
124
|
-
`;var Dn=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Mn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Cn(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(jy,this.gl.VERTEX_SHADER),i=this.createShader(Qy,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 QC,now as Gy,Subscription as GC,filter as WC,combine as Wy,debounce as YC,ValueSubject as nc,isNonNullable as zC}from"@vkontakte/videoplayer-shared/es2015";var oc=class{constructor(){this.isSeeked$=new nc(!1);this.isBuffering$=new nc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new GC;this.severeStallOccurred$=new nc(!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(Wy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(YC(this.qualityLimitsOnStall.stallDurationToBeCount),WC(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Wy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(QC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Gy(),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,zC(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=Gy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Yy=oc;import{combine as KC,map as XC,observeElementSize as JC,Subscription as ZC,ValueSubject as uc,noop as eD}from"@vkontakte/videoplayer-shared/es2015";var Vn=class{constructor(){this.subscription=new ZC;this.pipSize$=new uc(void 0);this.videoSize$=new uc(void 0);this.elementSize$=new uc(void 0);this.pictureInPictureWindowRemoveEventListener=eD}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(JC(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(KC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(XC(({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 yi=class{constructor(e){this.subscription=new nD;this.videoState=new B("stopped");this.droppedFramesManager=new mn;this.stallsManager=new Yy;this.elementSizeManager=new Vn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wr;this.audioTrackSwitchHistory=new Wr;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"),k(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"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return iD(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Dn(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 He(e.source.url),this.params=e,this.video=Ae(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(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ln({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Le(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:zy.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(lc(l=>!!l.length),Xy()).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(cc(l=>l.to.state!=="none"),qa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(qa()),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(lc(Ky),Xy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(cc(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(ot(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ue(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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(rD(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of c.audio){h.push(Hl(p));let m=[];for(let b of p.representations){let g=vy(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(jl(h));let p=[];for(let m of h.representations){let b=gy(C(w({},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=Sy(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(On(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$,sD(this.video,"progress")).pipe(lc(()=>this.videoTracksMap.size>0)).subscribe(()=>E(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Jy.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});Ky(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();yield 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(qa()).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(jl(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qa()).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(Hl(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(cc(({to:l})=>l==="ready"),qa());this.subscription.add(On(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,dc(["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(On(o,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=On(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dc(["init"])).pipe(aD(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var F,q,K,x,j,L,Q,N,Z,R,D,X,P;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(F=e.videoTrack.getState())==null?void 0:F.id,n=[...this.videoTracksMap.keys()].find(({id:M})=>M===r),o=t.currentVideoTrack$.getValue(),u=((x=(K=e.videoStream.getState())!=null?K:n&&((q=this.videoTracksMap.get(n))==null?void 0:q.stream))!=null?x:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:M})=>M===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Ji(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=(j=e.audioStream.getState())!=null?j:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(L=[...this.audioStreamsMap.keys()].find(({id:M})=>M===(b==null?void 0:b.id)))!=null?L:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!i){let M=cn(n,c,(Q=this.audioStreamsMap.get(g))!=null?Q:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(N=M==null?void 0:M.bitrate)!=null?N:-1/0)}if(o){let M=cn(o,c,(Z=this.audioStreamsMap.get(g))!=null?Z:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(R=M==null?void 0:M.bitrate)!=null?R:-1/0)}}let S=qt(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&&hv(y,c,(D=this.audioStreamsMap.get(g))!=null?D:[],{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=(X=this.videoTracksMap.get(y))==null?void 0:X.representation,$=I&&((P=this.audioTracksMap.get(I))==null?void 0:P.representation);if(T&&$)return[T,$];if(T&&!$&&this.audioTracksMap.size===0)return[T,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zy.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),ke(this.video),this.tracer.end()}};var Ua=class extends yi{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 pc,merge as Zy,filter as eT,filterChanged as oD,isNullable as hc,map as tT,ValueSubject as mc,isNonNullable as uD}from"@vkontakte/videoplayer-shared/es2015";var Ha=class extends yi{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 mc(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(tT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(pc({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(tT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(eT(o=>uD(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(pc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Zy(i.playbackRateState$,new mc(1))}).pipe(eT(({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||hc(l)||(e=o-l)})).add(pc({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Zy(i.playbackRateState$,new mc(1))}).pipe(oD((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||hc(o)||hc(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=yy(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 rT=O(Ks(),1);import{assertNever as ja,assertNonNullable as iT,debounce as lD,ErrorCategory as Bn,filter as cD,isNonNullable as dD,isNullable as pD,map as _n,merge as hD,Observable as mD,observableFrom as fD,Subscription as bD,videoSizeToQuality as gD}from"@vkontakte/videoplayer-shared/es2015";var et={};var ur=(a,e)=>new mD(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Qa=class{constructor(e){this.subscription=new bD;this.videoState=new B("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:ja(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ja(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ja(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ja(e)}break;default:ja(t)}};this.textTracksManager=new He(e.source.url),this.video=Ae(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(de(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ke(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Bn.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rT.default)(import("hls.js").then(r=>{e||(et.Hls=r.default,et.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){iT(et.Hls,"hls.js not loaded"),this.hls=new et.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){iT(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Bn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Le(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(ot(this.video,e.isLooped,i)),this.subscription.add(Re(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ue(this.video,e.playbackRate,r.playbackRateState$,i)),s(je(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(_n(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ur(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Bn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(ur(this.hls,et.Events.MANIFEST_PARSED).pipe(_n(({levels:l})=>l.reduce((c,d)=>{var S,y;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(y=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?y:gD({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(ur(this.hls,et.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(ur(this.hls,et.Events.LEVEL_LOADING).pipe(_n(({url:l})=>de(l))),t.hostname$),s(ur(this.hls,et.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(Vt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ur(this.hls,et.Events.LEVEL_SWITCHED).pipe(_n(({level:l})=>n(this.hls.levels[l])));o.pipe(cD(dD)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Vt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(pD(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=hD(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,fD(["init"])).pipe(lD(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return E(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:t})))||(this.videoState.setState("paused"),k(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"),k(this.params.desiredState.playbackState,"stopped",!0)}};var aT="X-Playback-Duration",fc=a=>E(void 0,null,function*(){var r;let e=yield lt(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(aT)?parseInt(e.headers.get(aT),10):void 0});import{assertNever as kD,combine as RD,debounce as $D,ErrorCategory as qn,filter as LD,filterChanged as MD,isNonNullable as oT,isNullable as Un,map as uT,merge as CD,observableFrom as DD,Subscription as VD,ValueSubject as vc,VideoQuality as OD}from"@vkontakte/videoplayer-shared/es2015";var gc=O(hu(),1);import{videoSizeToQuality as vD,getExponentialDelay as SD}from"@vkontakte/videoplayer-shared/es2015";var yD=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=vD({width:t,height:i})}return e!=null?e:null},TD=(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(ED(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([C(w({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return E(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ve;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return E(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:AD.WTF,thrown:t,message:e})}};var Ga=class{constructor(e){this.subscription=new VD;this.videoState=new B("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new vc([]);this.liveOffset=new hi;this.manifestStartTime$=new vc(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"),k(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"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(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"&&k(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"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return kD(t)}};var i;this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:OD.INVARIANT,url:this.params.source.url};let t=(r,s)=>Nn(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 Fn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new He(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:qn.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:qn.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(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new vc((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:qn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Le(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(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),s(je(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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(MD(),uT(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&&oT(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(de(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(RD({startTime:this.manifestStartTime$.pipe(LD(oT)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(uT(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=CD(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,DD(["init"])).pipe($D(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),ke(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Un(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=ge(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),fc(n).then(c=>{var d;if(!Un(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Un(h)||!isFinite(h))&<(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();fc(g).then(v=>{Un(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:qn.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=ge(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 BD,debounce as _D,ErrorCategory as Sc,fromEvent as yc,isNonNullable as ND,isNullable as FD,map as lT,merge as cT,observableFrom as dT,Subscription as qD,ValueSubject as UD,VideoQuality as HD}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new qD;this.videoState=new B("stopped");this.manifests$=new UD([]);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"),k(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"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return BD(t)}};this.textTracksManager=new He(e.source.url),this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:HD.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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Nn(ge(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:Sc.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:Sc.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Le(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(lT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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&&ND(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(de(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(lT(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)),!U.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(cT(yc(o,"addtrack"),yc(o,"removetrack"),yc(o,"change"),dT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=cT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,dT(["init"])).pipe(_D(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var s,n;let e=this.selectManifest();if(FD(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(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Sc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var mT=O(_i(),1),Tc=O(zi(),1),fT=O(Nt(),1);import{assertNever as jD,assertNonNullable as pT,debounce as QD,ErrorCategory as hT,isHigherOrEqual as GD,isLowerOrEqual as WD,isNonNullable as YD,merge as zD,observableFrom as KD,Subscription as XD,map as JD}from"@vkontakte/videoplayer-shared/es2015";var Ya=class{constructor(e){this.subscription=new XD;this.videoState=new B("stopped");this.trackUrls={};this.textTracksManager=new He;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"),k(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"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return jD(e)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),(0,mT.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,Tc.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:hT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Le(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(JD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),s(je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(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&&YD(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=zD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,KD(["init"])).pipe(QD(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),ke(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;pT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];pT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ca(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hT.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=qt(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,Tc.default)(this.trackUrls).map(d=>d.track);if(!r||!s||Gr({limits:e,lowestAvailableQuality:(c=(0,fT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?WD(r,e.max):!0,u=e.min?GD(r,e.min):!0;o&&u||i(e)}};import{assertNever as gT,debounce as i0,merge as vT,observableFrom as r0,Subscription as a0,map as ST,ValueSubject as s0,ErrorCategory as Ec,VideoQuality as n0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as ZD}from"@vkontakte/videoplayer-shared/es2015";var bT=["stun:videostun.mycdn.me:80"],e0=1e3,t0=3,Ic=()=>null,Hn=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=Ic;this.externalStopCallback=Ic;this.externalErrorCallback=Ic;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return E(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return E(this,null,function*(){try{let e={iceServers:[{urls:bT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return E(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return E(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:ZD.WTF,message:e.message})}onPeerConnectionStream(e){return E(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return E(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),e0)}normalizeOptions(e={}){let t={stunServerList:bT,maxRetryNumber:t0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var za=class{constructor(e){this.videoState=new B("stopped");this.maxSeekBackTime$=new s0(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"),k(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"),k(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"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return gT(e)}};this.subscription=new a0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ae(e.container,e.tuning),this.liveStreamClient=new Hn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ke(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ec.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(vT(this.videoState.stateChangeStarted$.pipe(ST(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ST(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Le(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(je(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(Re(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 gT(n.to)}},i)).add(vT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r0(["init"])).pipe(i0(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(de(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:n0.INVARIANT}),this.video.srcObject=e,k(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:Ec.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ec.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ka=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 Ja,assertNonNullable as Gt,ErrorCategory as jn,filter as PT,isNonNullable as wT,isNullable as h0,map as m0,merge as f0,once as b0,Subject as he,Subscription as AT,ValueSubject as _,flattenObject as kT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as o0,map as yT,Subscription as u0,Subject as l0}from"@vkontakte/videoplayer-shared/es2015";var TT=a=>new o0(e=>{let t=new u0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(yT(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(yT(({type:l})=>l!==void 0)),n=new l0,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 c0,Subscription as d0,combine as p0,filter as ET,once as xT}from"@vkontakte/videoplayer-shared/es2015";function IT(){return new(window.AudioContext||window.webkitAudioContext)}var Xa=class Xa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ve;this.subscriptions=new d0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(ET(s=>!!s.type),xT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){U.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(p0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(ET(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),xT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return E(this,null,function*(){let{volumeMultiplier:t}=this,i=IT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Xa.errorId,category:c0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Xa.errorId} exception`,thrown:e})}};Xa.errorId="VolumeMultiplierManager";var lr=Xa;var g0={chunkDuration:5e3,maxParallelRequests:5},Za=class{constructor(e){this.current$=new _({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;this.providerOutput={position$:new _(0),duration$:new _(1/0),volume$:new _({muted:!1,volume:1}),availableVideoStreams$:new _([]),currentVideoStream$:new _(void 0),availableVideoTracks$:new _([]),currentVideoTrack$:new _(void 0),availableAudioStreams$:new _([]),currentAudioStream$:new _(void 0),availableAudioTracks$:new _([]),currentVideoSegmentLength$:new _(0),currentAudioSegmentLength$:new _(0),isAudioAvailable$:new _(!0),autoVideoTrackLimitingAvailable$:new _(!1),autoVideoTrackLimits$:new _(void 0),currentBuffer$:new _(void 0),isBuffering$:new _(!0),error$:new he,fetcherError$:new he,fetcherRecoverableError$:new he,warning$:new he,willSeekEvent$:new he,soundProhibitedEvent$:new he,seekedEvent$:new he,loopedEvent$:new he,endedEvent$:new he,firstBytesEvent$:new he,loadedMetadataEvent$:new he,firstFrameEvent$:new he,canplay$:new he,isLive$:new _(void 0),isLiveEnded$:new _(null),isLowLatency$:new _(!1),canChangePlaybackSpeed$:new _(!0),liveTime$:new _(void 0),liveBufferTime$:new _(void 0),liveLatency$:new _(void 0),severeStallOccurred$:new he,availableTextTracks$:new _([]),currentTextTrack$:new _(void 0),hostname$:new _(void 0),httpConnectionType$:new _(void 0),httpConnectionReused$:new _(void 0),inPiP$:new _(!1),inFullscreen$:new _(!1),element$:new _(void 0),elementVisible$:new _(!0),availableSources$:new _(void 0),is3DVideo$:new _(!1),playbackState$:new _(""),getCurrentTime$:new _(null)};this.subscription=new AT;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=By([...Ny(this.params.tuning),..._y(this.params.tuning)],this.params.tuning).filter(l=>wT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,xc.default)(r,l)),...t.filter(l=>(0,xc.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",kT(s)),this.screenFormatsIterator=new Ka(s);let n=[...ec(!0),...ec(!1)];this.chromecastFormatsIterator=new Ka(n.filter(l=>wT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&lr.isSupported()&&(this.volumeMultiplierManager=new lr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(h0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:jn.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 Ja(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 Gt(u),new Ua(C(w({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ha(C(w({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Gt(u),U.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Wa(C(w({},o),{source:u})):new Qa(C(w({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ga(C(w({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ya(C(w({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Gt(u),new $v(C(w({},o),{source:u,config:C(w({},g0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Gt(u),new za({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 Ja(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 Gt(o),new Fr({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 Ja(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ja(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 Ja(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 C(w({},e),{url:i(e.url)})}return(0,$T.default)((0,RT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new AT,t=!1,i=0;return e.add(f0(this.providerOutput.error$.pipe(PT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),TT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(m0(r=>({id:`ProviderHangup:${r}`,category:jn.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(PT(({to:s})=>s==="playing"),b0()).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===jn.NETWORK,u=r.category===jn.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=C(w({},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",kT(n))})),e}};import{fromEvent as Qn,once as v0,combine as S0,Subscription as LT,ValueSubject as Pc,map as y0,filter as T0,isNonNullable as Gn,now as Ne,safeStorage as wc}from"@vkontakte/videoplayer-shared/es2015";var I0=5e3,MT="one_video_throughput",CT="one_video_rtt",Et=window.navigator.connection,DT=()=>{let a=Et==null?void 0:Et.downlink;if(Gn(a)&&a!==10)return a*1e3},VT=()=>{let a=Et==null?void 0:Et.rtt;if(Gn(a)&&a!==3e3)return a},OT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Ac=class a{constructor(e){this.subscription=new LT;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(MT)||(e.useBrowserEstimation?DT():void 0)||I0,i=(s=(r=a.load(CT))!=null?r:e.useBrowserEstimation?VT():void 0)!=null?s:0;if(this.throughput$=new Pc(t),this.rtt$=new Pc(i),this.rttAdjustedThroughput$=new Pc(OT(t,i,e.rttPenaltyRequestSize)),this.throughput=vi.getSmoothedValue(t,-1,e),this.rtt=vi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=DT();u&&this.throughput.next(u);let l=VT();Gn(l)&&this.rtt.next(l)};Et&&"onchange"in Et&&this.subscription.add(Qn(Et,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{wc.set(MT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{wc.set(CT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(S0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(y0(({throughput:n,rtt:o})=>OT(n,o,e.rttPenaltyRequestSize)),T0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Ne(),r=new LT;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Qn(e,"progress").pipe(v0()).subscribe(s=>{t=s.loaded,i=Ne()}));break;case 1:case 0:r.add(Qn(e,"loadstart").subscribe(()=>{t=0,i=Ne()}));break}r.add(Qn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ne(),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=Ne(),n=0,o=Ne(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>E(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(r,Ne()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ne();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Ne()}else n+=d.byteLength;o=Ne()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ne()-o,this.concurrentDownloads.size),n=0,o=Ne());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=wc.get(e);if(Gn(t))return(i=parseInt(t,10))!=null?i:void 0}},BT=Ac;import{fillWithDefault as E0,VideoQuality as Wn}from"@vkontakte/videoplayer-shared/es2015";var _T={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:Wn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Wn.Q_720P,trafficSavingLimit:Wn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Wn.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},NT=a=>{var e;return C(w({},E0(a,_T)),{configName:[...(e=a.configName)!=null?e:[],..._T.configName]})};import{assertNonNullable as Yn,combine as xt,ErrorCategory as zn,filter as V,filterChanged as z,fromEvent as Rc,isNonNullable as HT,isNullable as $0,Logger as L0,map as W,mapTo as jT,merge as Wt,now as Kn,once as H,Subject as J,Subscription as QT,tap as $c,ValueSubject as A,isHigher as M0,isInvariantQuality as GT,flattenObject as Yt,throttle as Lc,getTraceSubscriptionMethod as WT,Tracer as C0,InternalsExposure as D0}from"@vkontakte/videoplayer-shared/es2015";import{merge as x0,map as P0,filter as FT,isNonNullable as w0}from"@vkontakte/videoplayer-shared/es2015";var kc=({seekState:a,position$:e})=>x0(a.stateChangeEnded$.pipe(P0(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),FT(w0)),e.pipe(FT(()=>a.getState().state==="none")));import{assertNonNullable as A0}from"@vkontakte/videoplayer-shared/es2015";var qT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return A0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as k0,once as R0}from"@vkontakte/videoplayer-shared/es2015";var UT=(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(k0(r=>r.length>0),R0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var Xn=class{constructor(e={configName:[]},t=C0.createRootTracer(!1)){this.subscription=new QT;this.logger=new L0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new A(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new B("stopped"),seekState:new B({state:"none"}),volume:new B({volume:1,muted:!1}),videoTrack:new B(void 0),videoStream:new B(void 0),audioStream:new B(void 0),autoVideoTrackSwitching:new B(!0),autoVideoTrackLimits:new B({}),isLooped:new B(!1),isLowLatency:new B(!1),playbackRate:new B(1),externalTextTracks:new B([]),internalTextTracks:new B([]),currentTextTrack:new B(void 0),textTrackCuesSettings:new B({}),cameraOrientation:new B({x:0,y:0})};this.info={playbackState$:new A(void 0),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),predefinedQualityLimitType$:new A("unknown"),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),isLiveEnded$:new A(null),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new J,ready$:new J,started$:new J,playing$:new J,paused$:new J,stopped$:new J,willStart$:new J,willResume$:new J,willPause$:new J,willStop$:new J,willDestruct$:new J,watchCoverageRecord$:new J,watchCoverageLive$:new J,managedError$:new J,fatalError$:new J,fetcherRecoverableError$:new J,ended$:new J,looped$:new J,seeked$:new J,willSeek$:new J,autoplaySoundProhibited$:new J,firstBytes$:new J,loadedMetadata$:new J,firstFrame$:new J,canplay$:new J,log$:new J,fetcherError$:new J,severeStallOccured$:new J};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:ev,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=NT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new BT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new D0("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,YT.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:zn.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 l,c,d;let u=e,{container:n}=u,o=vd(u,["container"]);this.tracer.log("initVideo",Yt(o)),this.domContainer=qT(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new Za({sources:e.sources,meta:(c=e.meta)!=null?c:{},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.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?U.isInited$.pipe(V(n=>!!n),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Rc(document,"visibilitychange").pipe(H()).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(V(e=>!!e),H()).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(V(e=>!!e),H()).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(V(e=>!!e),H()).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(V(e=>!!e),H()).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(V(i=>!!i),H()).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(V(t=>!!t),H()).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(V(i=>!!i),H()).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(V(t=>!!t),H()).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(V(t=>!!t),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{Yn(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(V(i=>i.length>0),H()).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(V(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Yt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).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(V(t=>!!t),H()).subscribe(()=>{var i;Yn(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(V(t=>!!t),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Yt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>w({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),H()).subscribe(()=>{var t;UT(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(V(t=>!!t),H()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",w({},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(V(t=>!!t),H()).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(V(i=>!!i),H()).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(V(t=>!!t),H()).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(V(i=>!!i),H()).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(V(e=>e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if($0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return HT(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(Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(W(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(dl({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(V(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=Kn(),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",Yt(n)),n.state==="requested"?this.desiredState.seekState.setState(C(w({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:zn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(H()).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",Yt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(W(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(W(n=>n.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(xt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(W(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>GT(u)?1:GT(l)?-1:M0(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(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(V(n=>HT(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(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(W(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe($c(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(xt({hasLiveOffsetByPaused:Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(W(n=>n.to),z(),W(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(xt({atLiveEdge:xt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:kc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(W(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),z(),$c(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(W(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(xt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(W(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),z(),$c(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(W(n=>n.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(W(n=>n.volume),z()).subscribe(this.info.volume$)).add(kc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Wt(e.providerOutput.endedEvent$.pipe(jT(!0)),e.providerOutput.seekedEvent$.pipe(jT(!1))).pipe(z()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(W(n=>({id:n?`No${n}`:"NoProviders",category:zn.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(H(),W(n=>n!=null?n:Kn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),W(()=>Kn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),W(()=>Kn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new A(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(V(({to:n})=>n==="playing"),H()).subscribe(()=>i.next(!1)));let r=0,s=Wt(e.providerOutput.isBuffering$,t,i).pipe(W(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),z());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(Wt(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(Wt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(W(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new QT;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(V(i=>i.length>0),H()).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=qt(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(Wt(this.desiredState.videoTrack.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(W(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(W(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(W(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Yn(this.providerContainer),Yn(e),Zg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Jg(i)),this.providerContainer.current$.subscribe(({type:i})=>Qr("provider",i)),e.duration$.subscribe(i=>Qr("duration",i)),e.availableVideoTracks$.pipe(V(i=>!!i.length),H()).subscribe(i=>Qr("tracks",i)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(W(i=>i==null?void 0:i.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(i=>this.subscription.add(i)),Qr("codecs",U.video.supportedCodecs)}initTracerSubscription(){let e=WT(this.tracer.log.bind(this.tracer)),t=WT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(z()).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(xt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(V(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(V(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(V(i=>i>0),z()).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(xt({currentBuffer:this.info.currentBuffer$.pipe(V(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(Lc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(xt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(V(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Lc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),V(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),V(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),V(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(xt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(V(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Lc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),V(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=()=>E(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:zn.DOM,message:String(r)})})});this.subscription.add(Wt(Rc(document,"visibilitychange"),Rc(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",Yt({quality:t,availableTracks:Yt(e),track:Yt(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&&!Jr()}};import{Subscription as t9,Observable as i9,Subject as r9,ValueSubject as a9,VideoQuality as s9}from"@vkontakte/videoplayer-shared/es2015";var n9=`@vkontakte/videoplayer-core@${Sd}`;export{fs as ChromecastState,so as HttpConnectionType,i9 as Observable,De as PlaybackState,Xn as Player,bs as PredefinedQualityLimits,n9 as SDK_VERSION,r9 as Subject,t9 as Subscription,no as Surface,Sd as VERSION,a9 as ValueSubject,mt as VideoFormat,s9 as VideoQuality,U as clientChecker,Hr as isMobile};
|
|
68
|
+
`;var us=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 tl(this.params.fov,this.params.orientation),this.cameraRotationManager=new il(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(WI,this.gl.VERTEX_SHADER),i=this.createShader(QI,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 SC,now as Pn,once as vC,Subscription as yC,ValueSubject as Vp,isNonNullable as TC,safeStorage as YI,filterChanged as IC}from"@vkontakte/videoplayer-shared/es2015";var rl="stalls_manager_metrics",xC="stalls_manager_abr_params",Op=class{constructor(){this.isSeeked$=new Vp(!1);this.isBuffering$=new Vp(!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 yC;this.severeStallOccurred$=new Vp(!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}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Pn(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(Pn()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}updateStoredAbrParams(){let e=[],t=this.getStoredData(rl,"[]");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(rl,[]),this.setStoredData(xC,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(rl,"[]"),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(rl,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(vC()).subscribe(t=>this.providerStartWatchingTimestamp=Pn())),this.subscription.add(this.currentStallDuration$.pipe(IC()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(SC(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=Pn(),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,TC(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&Pn()-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}))}},sl=Op;import{combine as EC,map as wC,observeElementSize as PC,Subscription as AC,ValueSubject as _p,noop as kC}from"@vkontakte/videoplayer-shared/es2015";var al=class{constructor(){this.subscription=new AC;this.pipSize$=new _p(void 0);this.videoSize$=new _p(void 0);this.elementSize$=new _p(void 0);this.pictureInPictureWindowRemoveEventListener=kC}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(PC(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(EC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(wC(({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 fr=class{constructor(e){this.subscription=new $C;this.videoState=new G("stopped");this.droppedFramesManager=new Yr;this.stallsManager=new sl;this.elementSizeManager=new al;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ci;this.audioTrackSwitchHistory=new Ci;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 MC(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new us(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=_e(e.container,e.tuning),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new el({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=Ue(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:KI.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(Fp(c=>!!c.length),JI()).subscribe(c=>{this.droppedFramesManager.connect({video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Np(c=>c.to.state!=="none"),nl());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(Fp(XI),JI()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Np(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(c=>{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(Et(this.video,t.isLooped,r)),this.subscription.add(Ne(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(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:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let h=this.player.getStreams();if(LC(h,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let m of h.audio){f.push(vp(m));let g=[];for(let S of m.representations){let y=TI(S);g.push(y),this.audioTracksMap.set(y,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(f)}let p=[];for(let f of h.video){p.push(yp(f));let m=[];for(let g of f.representations){let S=yI(D(x({},g),{streamId:f.id}));S&&(m.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,m)}this.params.output.availableVideoStreams$.next(p);for(let f of h.text)for(let m of f.representations){let g=II(f,m);this.textTracksMap.set(g,{stream:f,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&wI(o)||null;this.subscription.add(ol(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$,DC(this.video,"progress")).pipe(Fp(()=>this.videoTracksMap.size>0)).subscribe(()=>I(this,null,function*(){let c=this.player.state$.getState(),h=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||h||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:f}=this.selectedRepresentations;if(!p)return;let m=cr(this.videoTracksMap.keys(),S=>{var y;return((y=this.videoTracksMap.get(S))==null?void 0:y.representation.id)===p.id});XI(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")yield this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",p.id),f){let S=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",f.id,S)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(nl()).subscribe(c=>{let h=cr(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(yp(f))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(nl()).subscribe(c=>{let h=cr(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!h){e.currentAudioStream$.next(void 0);return}let[p,{stream:f}]=h,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(vp(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var h,p;if(c!=null&&c.is3dVideo&&((h=this.params.tuning.spherical)!=null&&h.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.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 l=t.playbackState.stateChangeStarted$.pipe(Np(({to:c})=>c==="ready"),nl());this.subscription.add(ol(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Up(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(ol(l,this.player.state$.stateChangeEnded$,Up(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=ol(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Up(["init"])).pipe(BC(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var _,q,P,$,M,B,A,C,k,O,ee,te;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?$a:Da,t=this.params.tuning.useNewAutoSelectVideoTrack?ku:Au,i=this.params.tuning.useNewAutoSelectVideoTrack?Yt:Pu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(_=r.videoTrack.getState())==null?void 0:_.id,u=cr(this.videoTracksMap.keys(),H=>H.id===o),l=a.currentVideoTrack$.getValue(),d=(($=(P=r.videoStream.getState())!=null?P:u&&((q=this.videoTracksMap.get(u))==null?void 0:q.stream))!=null?$:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=cr(this.videoStreamsMap.keys(),H=>H.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=fe(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=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(S==null?void 0:S.id)&&cr(this.audioStreamsMap.keys(),H=>H.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(y){if(u&&!n){let H=e(u,h,(B=this.audioStreamsMap.get(y))!=null?B:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(A=H==null?void 0:H.bitrate)!=null?A:-1/0)}if(l){let H=e(l,h,(C=this.audioStreamsMap.get(y))!=null?C:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=H==null?void 0:H.bitrate)!=null?k:-1/0)}}let T=u;(n||!T)&&(T=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}));let w=y&&t(T,h,(O=this.audioStreamsMap.get(y))!=null?O:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate}),E=(ee=this.videoTracksMap.get(T))==null?void 0:ee.representation,L=w&&((te=this.audioTracksMap.get(w))==null?void 0:te.representation);E&&L?(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=L):E&&!L&&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(){qe(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:KI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Fe(this.video)}};var An=class extends fr{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 qp,merge as ZI,filter as ex,filterChanged as CC,isNullable as Hp,map as tx,ValueSubject as jp,isNonNullable as VC}from"@vkontakte/videoplayer-shared/es2015";var kn=class extends fr{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 jp(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(tx(o=>o.to)).subscribe(this.player.isLowLatency$)).add(qp({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(tx(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(ex(o=>VC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(qp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:ZI(i.playbackRateState$,new jp(1))}).pipe(ex(({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||Hp(l)||(e=o-l)})).add(qp({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:ZI(i.playbackRateState$,new jp(1))}).pipe(CC((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||Hp(o)||Hp(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=xI(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 PV,assertNonNullable as AV,debounce as kV,ErrorCategory as Lx,filter as Bx,filterChanged as gl,fromEvent as RV,isNonNullable as Dx,map as ph,merge as Sl,observableFrom as hh,once as $x,Subscription as MV}from"@vkontakte/videoplayer-shared/es2015";var ch=U(Ha(),1);import{abortable as nh,assertNonNullable as hs,combine as fs,ErrorCategory as Zt,filter as hl,filterChanged as oo,flattenObject as uo,fromEvent as Ei,getTraceSubscriptionMethod as mV,interval as oh,isNonNullable as lo,isNullable as Mx,map as ms,merge as vr,now as uh,Subject as fl,Subscription as lh,tap as bV,throttle as gV,ValueSubject as be}from"@vkontakte/videoplayer-shared/es2015";var ll=U(xt(),1),ds=U(Ft(),1),cl=U(Ha(),1);var wx=U(Aa(),1);import{assertNever as OC,ErrorCategory as ix,Subject as rx}from"@vkontakte/videoplayer-shared/es2015";var _C=18,sx=!1;try{sx=z.browser.isSafari&&!!z.browser.safariVersion&&z.browser.safariVersion<=_C}catch(s){console.error(s)}var Gp=class{constructor(e){this.bufferFull$=new rx;this.error$=new rx;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:ix.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return I(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return I(this,null,function*(){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()})})}abort(e){return I(this,null,function*(){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};sx&&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:ix.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:OC(t)}}},ax=Gp;import{abortable as Ui,assertNonNullable as ct,ErrorCategory as xi,fromEvent as ih,getExponentialDelay as rh,isNonNullable as cs,isNullable as Ge,now as ul,once as nV,Subject as oV,Subscription as uV,ValueSubject as Sr}from"@vkontakte/videoplayer-shared/es2015";var Z=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 ls=class extends Z{};var Rn=class extends Z{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 Mn=class extends Z{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 Ln=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var le=class extends Z{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Bn=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 Dn=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var $n=class extends Z{constructor(e,t){super(e,t),this.data=this.content}};var mr=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 Cn=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Vn=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var On=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 _n=class extends le{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Fn=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 Nn=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Un=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 qn=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Hn=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var jn=class extends le{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Gn=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var zn=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 Wn=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 Qn=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 Yn=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Kn=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 Xn=class extends Z{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var NC={ftyp:Mn,moov:Ln,mvhd:Bn,moof:Dn,mdat:$n,sidx:mr,trak:Cn,mdia:Nn,mfhd:jn,tkhd:Un,traf:Gn,tfhd:zn,tfdt:Wn,trun:Qn,minf:qn,sv3d:Vn,st3d:On,prhd:_n,proj:Hn,equi:Fn,uuid:Rn,stbl:Yn,stsd:Kn,avc1:Xn,unknown:ls},Ti=class s{constructor(e={}){this.options=x({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=NC[e];return i?new i(t,new s):new ls(t,new s)}};var Ni=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 qC=new TextDecoder("ascii"),HC=s=>qC.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",jC=s=>{let e=new mr(s,new Ti),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})},GC=(s,e)=>{let i=new Ti().parse(s),r=new Ni(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)},zC=s=>{let t=new Ti().parse(s),i=new Ni(t),r={},a=i.findAll("uuid");return a.length?a[a.length-1]:r},WC=s=>{var r;let t=new Ti().parse(s);return(r=new Ni(t).find("sidx"))==null?void 0:r.timescale},QC=(s,e)=>{let i=new Ti().parse(s),a=new Ni(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},YC=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 Ti().parse(s),r=new Ni(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},nx={validateData:HC,parseInit:YC,getIndexRange:()=>{},parseSegments:jC,parseFeedableSegmentChunk:GC,getChunkEndTime:QC,getServerLatencyTimestamps:zC,getTimescaleFromIndex:WC};var Zn=U(xt(),1);import{assertNonNullable as Wp,isNonNullable as cx,isNullable as XC}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as KC}from"@vkontakte/videoplayer-shared/es2015";var ox={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"}},ux=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=Jn(s,t),r=i in ox,a=r?ox[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=Jn(u),c=l*Ze(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}},Jn=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Ze(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Ze(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Ze(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},Ut=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return Jn(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:KC(e)}},br=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=ux(i);if(!e(r))return;r.type==="master"&&br(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},lx=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=ux(s);return br(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Ut(o,n):a===17026?t=Ut(o,n):a===17029&&(i=Ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var dx=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],JC=[231,22612,22743,167,171,163,160,175],ZC=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,d=!1,c=0;return br(s,({tag:h,type:p,value:f,valueSize:m})=>{if(h===21419){let g=Ut(f,p);l=Jn(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=Ut(f,p):h===17545?r=Ut(f,p):h===21420&&l===475249515?u=Ut(f,p):h===374648427?br(f,({tag:g,type:S,value:y})=>g===30321?(d=Ut(y,S)===1,!1):!0):a&&n&&(0,Zn.default)(dx,h)&&(o=!0),!o}),Wp(e,"Failed to parse webm Segment start"),Wp(t,"Failed to parse webm Segment end"),Wp(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}}}},eV=s=>{if(XC(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},tV=(s,e)=>{let t=!1,i=!1,r=o=>cx(o.time)&&cx(o.position),a=[],n;return br(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=Ut(l,u));break;case 183:break;case 241:n&&(n.position=Ut(l,u));break;default:t&&(0,Zn.default)(dx,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}}})},iV=s=>{let e=0,t=!1;try{br(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Zn.default)(JC,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=(0,Zn.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},px={validateData:lx,parseInit:ZC,getIndexRange:eV,parseSegments:tV,parseFeedableSegmentChunk:iV};var eo=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return px;case"mp4":return nx}}throw new ReferenceError(`Unsupported mime type ${s}`)};var Zp=U(mp(),1),Tx=U(Lr(),1),Ix=U(bp(),1),xx=U(Ft(),1),eh=U(nr(),1);import{isNonNullable as aV,isNullable as vx}from"@vkontakte/videoplayer-shared/es2015";var hx=s=>{var e;try{let t=rV(),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 rV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
69
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
|
|
70
|
+
(-(?<script>[a-z]{4}))?
|
|
71
|
+
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
72
|
+
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
73
|
+
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
74
|
+
(?:-(?<privateuse>(?:${e})))?
|
|
75
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Yp=U(Ft(),1);import{videoSizeToQuality as sV}from"@vkontakte/videoplayer-shared/es2015";var fx=({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:sV({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},mx=({id:s,bitrate:e})=>({id:s,bitrate:e}),bx=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),gx=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Kp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Yp.default)(i.split("."),0),isDefault:r}),Xp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Yp.default)(r.split("."),0)}),Jp=s=>"url"in s,it=s=>s.type==="template",to=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Sx=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},gr=(s,e)=>{for(let t of s)if(e(t))return t;return null};var yx=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},Ii=(s,e)=>{let t=s;t=(0,Zp.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,Tx.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Zp.default)(t,n,(o,u)=>vx(a)?o:vx(u)?a:(0,Ix.default)(a,parseInt(u,10),"0"))}return t},Ex=(s,e)=>{var q,P,$,M,B,A,C,k,O,ee,te,H,Pt,K,he,xe,ze,At,ei,kt,Ht,Pi,Ai,Ss,vs,ys,Ts,Is,xs,Es,ws,Ps,As,ks,Rs,Ms,Ls,Bs,Ds,$s,Cs,Vs,Os,_s,Fs,Ns,Us,qs,Hs,js,Gs,zs,Ws,Qs,Ys,Ks,Xs,Js,Zs,ea,ta;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 N,We;return(We=(N=ce.textContent)==null?void 0:N.trim())!=null?We:""}),o=(q=(0,xx.default)(n,0))!=null?q:"",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")],T=v.reduce((ce,N)=>D(x({},ce),{[N.id]:N.children}),{}),w=v.reduce((ce,N)=>D(x({},ce),{[N.id]:N.getAttribute("duration")}),{});y?S=yx(y):(0,eh.default)(w).filter(ce=>ce).length&&!u?S=(0,eh.default)(w).reduce((ce,N)=>{var We;return ce+((We=yx(N))!=null?We:0)},0):m&&(S=parseInt(m,10));let E=0,L=($=(P=a.getAttribute("profiles"))==null?void 0:P.split(","))!=null?$:[];for(let ce of v.map(N=>N.id))for(let N of T[ce]){let We=(M=N.getAttribute("id"))!=null?M:"id"+(E++).toString(10),Rt=(B=N.getAttribute("mimeType"))!=null?B:"",Hi=(A=N.getAttribute("codecs"))!=null?A:"",ji=(C=N.getAttribute("contentType"))!=null?C:Rt==null?void 0:Rt.split("/")[0],$l=(O=(k=N.getAttribute("profiles"))==null?void 0:k.split(","))!=null?O:[],ia=(te=hx((ee=N.getAttribute("lang"))!=null?ee:""))!=null?te:{},ti=(K=(Pt=(H=N.querySelector("Label"))==null?void 0:H.textContent)==null?void 0:Pt.trim())!=null?K:void 0,Cl=N.querySelectorAll("Representation"),Vl=N.querySelector("SegmentTemplate"),Ol=(xe=(he=N.querySelector("Role"))==null?void 0:he.getAttribute("value"))!=null?xe:void 0,dt=ji,W={id:We,language:ia.language,isDefault:Ol==="main",label:ti,codecs:Hi,hdr:dt==="video"&&ts(Hi),mime:Rt,representations:[]};for(let F of Cl){let Ae=(ze=F.getAttribute("lang"))!=null?ze:void 0,Mt=(ei=(At=ti!=null?ti:N.getAttribute("label"))!=null?At:F.getAttribute("label"))!=null?ei:void 0,ii=(Pi=(Ht=(kt=F.querySelector("BaseURL"))==null?void 0:kt.textContent)==null?void 0:Ht.trim())!=null?Pi:"",Qe=new URL(ii||o,e).toString(),ke=(Ai=F.getAttribute("mimeType"))!=null?Ai:Rt,ri=(vs=(Ss=F.getAttribute("codecs"))!=null?Ss:Hi)!=null?vs:"",si;if(ji==="text"){let Re=F.getAttribute("id")||"",ai=((ys=ia.privateuse)==null?void 0:ys.includes("x-auto"))||Re.includes("_auto"),Ye=F.querySelector("SegmentTemplate");if(Ye){let Lt={representationId:(Ts=F.getAttribute("id"))!=null?Ts:void 0,bandwidth:(Is=F.getAttribute("bandwidth"))!=null?Is:void 0},ni=parseInt((xs=F.getAttribute("bandwidth"))!=null?xs:"",10)/1e3,oi=(ws=parseInt((Es=Ye.getAttribute("startNumber"))!=null?Es:"",10))!=null?ws:1,pt=parseInt((Ps=Ye.getAttribute("timescale"))!=null?Ps:"",10),Gi=(As=Ye.querySelectorAll("SegmentTimeline S"))!=null?As:[],ht=Ye.getAttribute("media");if(!ht)continue;let ui=[],li=0,ci="",ft=0,Bt=oi,ie=0;for(let de of Gi){let Ke=parseInt((ks=de.getAttribute("d"))!=null?ks:"",10),ne=parseInt((Rs=de.getAttribute("r"))!=null?Rs:"",10)||0,Me=parseInt((Ms=de.getAttribute("t"))!=null?Ms:"",10);ie=Number.isFinite(Me)?Me:ie;let Xe=Ke/pt*1e3,Le=ie/pt*1e3;for(let Se=0;Se<ne+1;Se++){let Be=Ii(ht,D(x({},Lt),{segmentNumber:Bt.toString(10),segmentTime:(ie+Se*Ke).toString(10)})),mt=(Le!=null?Le:0)+Se*Xe,$t=mt+Xe;Bt++,ui.push({time:{from:mt,to:$t},url:Be})}ie+=(ne+1)*Ke,li+=(ne+1)*Xe}ft=ie/pt*1e3,ci=Ii(ht,D(x({},Lt),{segmentNumber:Bt.toString(10),segmentTime:ie.toString(10)}));let Dt={time:{from:ft,to:1/0},url:ci},Ee={type:"template",baseUrl:Qe,segmentTemplateUrl:ht,initUrl:"",totalSegmentsDurationMs:li,segments:ui,nextSegmentBeyondManifest:Dt,timescale:pt};si={id:Re,kind:"text",segmentReference:Ee,profiles:[],duration:S,bitrate:ni,mime:"",codecs:"",width:0,height:0,isAuto:ai}}else si={id:Re,isAuto:ai,kind:"text",url:Qe}}else{let Re=(Bs=(Ls=F.getAttribute("contentType"))!=null?Ls:ke==null?void 0:ke.split("/")[0])!=null?Bs:ji,ai=($s=(Ds=N.getAttribute("profiles"))==null?void 0:Ds.split(","))!=null?$s:[],Ye=parseInt((Cs=F.getAttribute("width"))!=null?Cs:"",10),Lt=parseInt((Vs=F.getAttribute("height"))!=null?Vs:"",10),ni=parseInt((Os=F.getAttribute("bandwidth"))!=null?Os:"",10)/1e3,oi=(_s=F.getAttribute("frameRate"))!=null?_s:"",pt=(Fs=F.getAttribute("quality"))!=null?Fs:void 0,Gi=oi?Cu(oi):void 0,ht=(Ns=F.getAttribute("id"))!=null?Ns:"id"+(E++).toString(10),ui=Re==="video"?`${Lt}p`:Re==="audio"?`${ni}Kbps`:ri,li=`${ht}@${ui}`,ci=[...L,...$l,...ai],ft,Bt=F.querySelector("SegmentBase"),ie=(Us=F.querySelector("SegmentTemplate"))!=null?Us:Vl;if(Bt){let Ee=(Hs=(qs=F.querySelector("SegmentBase Initialization"))==null?void 0:qs.getAttribute("range"))!=null?Hs:"",[de,Ke]=Ee.split("-").map(Be=>parseInt(Be,10)),ne={from:de,to:Ke},Me=(js=F.querySelector("SegmentBase"))==null?void 0:js.getAttribute("indexRange"),[Xe,Le]=Me?Me.split("-").map(Be=>parseInt(Be,10)):[],Se=Me?{from:Xe,to:Le}:void 0;ft={type:"byteRange",url:Qe,initRange:ne,indexRange:Se}}else if(ie){let Ee={representationId:(Gs=F.getAttribute("id"))!=null?Gs:void 0,bandwidth:(zs=F.getAttribute("bandwidth"))!=null?zs:void 0},de=parseInt((Ws=ie.getAttribute("timescale"))!=null?Ws:"",10),Ke=(Qs=ie.getAttribute("initialization"))!=null?Qs:"",ne=ie.getAttribute("media"),Me=(Ks=parseInt((Ys=ie.getAttribute("startNumber"))!=null?Ys:"",10))!=null?Ks:1,Xe=Ii(Ke,Ee);if(!ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Le=(Xs=ie.querySelectorAll("SegmentTimeline S"))!=null?Xs:[],Se=[],Be=0,mt="",$t=0;if(Le.length){let di=Me,pe=0;for(let bt of Le){let ve=parseInt((Js=bt.getAttribute("d"))!=null?Js:"",10),Je=parseInt((Zs=bt.getAttribute("r"))!=null?Zs:"",10)||0,pi=parseInt((ea=bt.getAttribute("t"))!=null?ea:"",10);pe=Number.isFinite(pi)?pi:pe;let zi=ve/de*1e3,Wi=pe/de*1e3;for(let hi=0;hi<Je+1;hi++){let Fl=Ii(ne,D(x({},Ee),{segmentNumber:di.toString(10),segmentTime:(pe+hi*ve).toString(10)})),ra=(Wi!=null?Wi:0)+hi*zi,Nl=ra+zi;di++,Se.push({time:{from:ra,to:Nl},url:Fl})}pe+=(Je+1)*ve,Be+=(Je+1)*zi}$t=pe/de*1e3,mt=Ii(ne,D(x({},Ee),{segmentNumber:di.toString(10),segmentTime:pe.toString(10)}))}else if(aV(S)){let pe=parseInt((ta=ie.getAttribute("duration"))!=null?ta:"",10)/de*1e3,bt=Math.ceil(S/pe),ve=0;for(let Je=1;Je<bt;Je++){let pi=Ii(ne,D(x({},Ee),{segmentNumber:Je.toString(10),segmentTime:ve.toString(10)}));Se.push({time:{from:ve,to:ve+pe},url:pi}),ve+=pe}$t=ve,mt=Ii(ne,D(x({},Ee),{segmentNumber:bt.toString(10),segmentTime:ve.toString(10)}))}let _l={time:{from:$t,to:1/0},url:mt};ft={type:"template",baseUrl:Qe,segmentTemplateUrl:ne,initUrl:Xe,totalSegmentsDurationMs:Be,segments:Se,nextSegmentBeyondManifest:_l,timescale:de}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Re||!ke)continue;let Dt={video:"video",audio:"audio",text:"text"}[Re];if(!Dt)continue;dt||(dt=Dt),si={id:li,kind:Dt,segmentReference:ft,profiles:ci,duration:S,bitrate:ni,mime:ke,codecs:ri,width:Ye,height:Lt,fps:Gi,quality:pt}}W.language||(W.language=Ae),W.label||(W.label=Mt),W.mime||(W.mime=ke),W.codecs||(W.codecs=ri),W.hdr||(W.hdr=dt==="video"&&ts(ri)),W.representations.push(si)}if(dt){let F=r[dt].find(Ae=>Ae.id===W.id);if(F&&W.representations.every(Ae=>it(Ae.segmentReference)))for(let Ae of F.representations){let Mt=W.representations.find(ke=>ke.id===Ae.id),ii=Mt==null?void 0:Mt.segmentReference,Qe=Ae.segmentReference;Qe.segments.push(...ii.segments),Qe.nextSegmentBeyondManifest=ii.nextSegmentBeyondManifest}else r[dt].push(W)}}return{duration:S,streams:r,baseUrls:n,live:g}};var io=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Sr(0);this.currentLowLatencySegmentLength$=new Sr(0);this.currentSegmentLength$=new Sr(0);this.onLastSegment$=new Sr(!1);this.fullyBuffered$=new Sr(!1);this.playingRepresentation$=new Sr(void 0);this.playingRepresentationInit$=new Sr(void 0);this.error$=new oV;this.gaps=[];this.subscription=new uV;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=Ui(this.destroyAbortController.signal,function(e){return Q(this,null,function*(){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 ax(this.sourceBuffer),this.subscription.add(ih(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:xi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:xi.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(ih(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:xi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!j(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Jr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=fe(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=Ui(this.destroyAbortController.signal,function(e,t=!1){return Q(this,null,function*(){if(!j(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(Ge(a)||Ge(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||!j(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();cs(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new Qi(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Ui(this.destroyAbortController.signal,function(e,t=!1){return Q(this,null,function*(){if(!j(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(Ge(a)||Ge(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||!j(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();cs(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Qi(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Ui(this.destroyAbortController.signal,function(e){return Q(this,null,function*(){var u,l;let t=(u=(0,cl.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);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){!j(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ae,Ui(this.switchAbortController.signal,function(i,r=!1){return Q(this,null,function*(){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(Ge(o)||Ge(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||!j(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();cs(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(){!Ge(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return I(this,null,function*(){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(Ge(e)||Ge(this.downloadingRepresentationId)||Ge(this.playingRepresentationId)||Ge(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer)||cs(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);cs(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=fe(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=fe(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,ll.default)(u,r))d="high";else{let c=(0,ds.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)&&fe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ds.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-fe(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;cs(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,cl.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,cl.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=>D(x({},p),{status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(a=(0,ds.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(!it(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=Ii(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&&Kt&&Kt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Kt&&Kt(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&&j(this.mediaSource,this.sourceBuffer)&&!(He(this.sourceBuffer.buffered,h)&&He(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}loadSegments(e,t,i="auto"){return I(this,null,function*(){it(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return I(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield Ui(o,function(){return Q(this,null,function*(){let d=rh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=ul(),!d)return;let c=new DataView(d),h=eo(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?yield Promise.all(l):yield 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]),to(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}loadByteRangeSegments(e,t,i="auto"){return I(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield Ui(n,function(){return Q(this,null,function*(){let u=rh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),ih(window,"online").pipe(nV()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=ul(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),to(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,ds.default)(e,0).byte.from,to:(0,ds.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>I(this,null,function*(){if(!a.aborted)try{this.lastDataObtainedTimestampMs=ul(),yield 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:xi.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=ul();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:xi.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,ll.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return I(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!j(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(a.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=eo(o.mime).parseFeedableSegmentChunk(d,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",u.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return I(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!j(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){if(l.representationId!==t)continue;if(a.aborted){yield n();continue}let{segment:d}=l,c=d.byte.from-i,h=d.byte.to-i,p=h-c+1,f=c<r,m=h<=r;if(f){if(d.status==="downloading"&&m){d.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);(yield this.sourceBufferTaskQueue.append(g,a))&&!a.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(p,r-c),l.loadedBytes>l.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?g:eo(u.mime).parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(d.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,a))&&!a.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):yield n())}}}})}onSegmentFullyAppended(e,t){if(!(Ge(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer))){!this.isLive&&z.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(He(this.sourceBuffer.buffered,e.segment.time.from,100)&&He(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:xi.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",Jp(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,wx.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return I(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Ui(this.destroyAbortController.signal,function(){return Q(this,null,function*(){let o=rh(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,eo(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&&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:xi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return I(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,i=!1){return I(this,null,function*(){if(!this.sourceBuffer||!j(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ge(e))return!1;let r=[],a=0,n=o=>{var l;if(a>=t)return;r.push(x({},o.time));let u=Jp(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,ll.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=Sx(r),(yield Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1})}abortBuffer(){return I(this,null,function*(){if(!this.sourceBuffer||!j(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||!j(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||!j(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||!j(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ge(e)?0:fe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!j(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||!j(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:xi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ge(this.sourceBuffer)||!j(this.mediaSource,this.sourceBuffer)||Ge(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:xi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as ro,assertNever as Px,fromEvent as Ax,merge as lV,now as so,Subject as kx,ValueSubject as sh,flattenObject as ps,ErrorCategory as ao,SubscriptionRemovable as cV}from"@vkontakte/videoplayer-shared/es2015";var pl=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.lastConnectionType$=new sh(void 0);this.lastConnectionReused$=new sh(void 0);this.lastRequestFirstBytes$=new sh(void 0);this.recoverableError$=new kx;this.error$=new kx;this.abortAllController=new ae;this.subscription=new cV;this.fetchManifest=ro(this.abortAllController.signal,function(e){return Q(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=_i(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=qu(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(dl);return r?(t.log("success",ps({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ps({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=ro(this.abortAllController.signal,function(l){return Q(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var B,A,C;let d=e,c=new Headers,h=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(d,location.href);k.searchParams.append("bytes",`${i.from}-${i.to}`),d=k.toString();break}default:Px(t)}this.requestQuic&&(d=_i(d));let p=this.abortAllController.signal,f;if(n){let k=new ae;if(f=lV(Ax(this.abortAllController.signal,"abort"),Ax(n,"abort")).subscribe(()=>{try{k.abort()}catch(O){dl(O)}}),this.abortAllController.signal.aborted||n.aborted)try{k.abort()}catch(O){dl(O)}p=k.signal}let m=so();h.log("startRequest",ps({url:d,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(d,{priority:a,headers:c,signal:p}),S=so();if(!g)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(f),null;if((B=this.throughputEstimator)==null||B.addRawRtt(S-m),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let k=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:k}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let k=so(),O={requestStartedAt:m,requestEndedAt:k,duration:k-m};return h.log("endRequest",ps(O)),h.end(),g.arrayBuffer()}let y=g.body;if(o){let k;[y,k]=g.body.tee(),(A=this.throughputEstimator)==null||A.trackStream(k,u)}let v=y.getReader(),T,w=parseInt((C=g.headers.get("content-length"))!=null?C:"",10);Number.isFinite(w)&&(T=w),!T&&i&&(T=i.to-i.from+1);let E=0,L=T?new Uint8Array(T):new Uint8Array(0),_=!1,q=k=>{this.unsubscribeAbortSubscription(f),_=!0,dl(k)},P=ro(p,function(ee){return Q(this,arguments,function*({done:k,value:O}){if(E===0&&this.lastRequestFirstBytes$.next(so()-m),p.aborted){this.unsubscribeAbortSubscription(f);return}if(!k&&O){if(T)L.set(O,E),E+=O.byteLength;else{let te=new Uint8Array(L.length+O.length);te.set(L),te.set(O,L.length),L=te,E+=O.byteLength}r==null||r(new DataView(L.buffer),E),yield v==null?void 0:v.read().then(P,q)}})}.bind(this));yield v==null?void 0:v.read().then(P,q),this.unsubscribeAbortSubscription(f);let $=so(),M={failed:_,requestStartedAt:m,requestEndedAt:$,duration:$-m};return _?(h.error("endRequest",ps(M)),h.end(),null):(h.log("endRequest",ps(M)),h.end(),L.buffer)})}.bind(this));this.fetchByteRangeRepresentation=ro(this.abortAllController.signal,function(e,t,i){return Q(this,null,function*(){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=ro(this.abortAllController.signal,function(e,t){return Q(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>D(x({},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}=Uu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return I(this,null,function*(){var a,n;let{type:r}=e;switch(r){case"byteRange":return(a=yield this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:Px(r)}})}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}doFetch(e,t){return I(this,null,function*(){let i=yield wt(e,t);if(i.ok)return i;let r=yield i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:ao.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:ao.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:ao.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:ao.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:ao.FATAL})}})}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},dl=s=>{if(!to(s))throw s};import{isNullable as dV,ValueSubject as pV}from"@vkontakte/videoplayer-shared/es2015";var no=class s{constructor(e,t){this.currentRepresentation$=new pV(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(!dV(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(D(x({},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 SV=["timeupdate","progress","play","seeked","stalled","waiting"],vV=["timeupdate","progress","loadeddata","playing","seeked"];var ml=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new lh;this.representationSubscription=new lh;this.state$=new G("none");this.currentVideoRepresentation$=new be(void 0);this.currentVideoRepresentationInit$=new be(void 0);this.currentAudioRepresentation$=new be(void 0);this.currentVideoSegmentLength$=new be(0);this.currentAudioSegmentLength$=new be(0);this.error$=new fl;this.lastConnectionType$=new be(void 0);this.lastConnectionReused$=new be(void 0);this.lastRequestFirstBytes$=new be(void 0);this.currentLiveTextRepresentation$=new be(null);this.isLive$=new be(!1);this.isActiveLive$=new be(!1);this.isLowLatency$=new be(!1);this.liveDuration$=new be(0);this.liveSeekableDuration$=new be(0);this.liveAvailabilityStartTime$=new be(0);this.liveStreamStatus$=new be(void 0);this.bufferLength$=new be(0);this.liveLatency$=new be(void 0);this.liveLoadBufferLength$=new be(0);this.livePositionFromPlayer$=new be(0);this.currentStallDuration$=new be(0);this.videoLastDataObtainedTimestamp$=new be(0);this.fetcherRecoverableError$=new fl;this.fetcherError$=new fl;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new fl;this.gapWatchdogActive=!1;this.destroyController=new ae;this.initManifest=nh(this.destroyController.signal,function(e,t,i){return Q(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=Te(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:Zt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=nh(this.destroyController.signal,function(){return Q(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Zt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Ex(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=$u(e))!=null?n:{id:"ManifestParsing",category:Zt.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=Tt())==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=Xu(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);z.display.isHDR&&p&&f?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let a=D(x({},t),{streams:r});return this.tracer.log("updateManifestEnd",uo(a)),a})}.bind(this));this.initRepresentations=nh(this.destroyController.signal,function(e,t,i){return Q(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",uo({initialVideo:e,initialAudio:t,sourceHls:i})),hs(this.manifest),hs(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new lh,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Ei(p,"error").pipe(hl(f=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Zt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?cu():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&Hr())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 io("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],lo(t)){let p=this.manifest.streams.audio.reduce((f,m)=>[...f,...m.representations],[]);this.audioBufferManager=new io("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}no.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new no(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(vr(...vV.map(p=>Ei(this.element,p))).pipe(ms(p=>this.element?fe(this.element.buffered,this.element.currentTime*1e3):0),oo(),bV(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(vr(Ei(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(oo()).subscribe(f=>this.liveStreamEndTimestamp=uh())),this.subscription.add(Ei(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=oh(1e3).subscribe(f=>{let m=Li(this.manifestUrlString,2);this.manifestUrlString=Te(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Ei(this.element,"play").subscribe(f=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(fs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(ms(({isActiveLive:f,isLowLatency:m})=>f&&m),oo()).subscribe(f=>{this.isManualDecreasePlaybackInLive()||ss(this.element,1)})),this.representationSubscription.add(fs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(hl(({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(fs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(hl(({isLive:f})=>f),oo((f,m)=>m.bufferLength<f.bufferLength),ms(({rtt:f,bufferLength:m,segmentServerLatency:g})=>{let S=Li(this.manifestUrlString,2);return(f/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(fs({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,T=f-S;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(T)>y&&(w=1+Math.sign(T)*v),ss(this.element,w)})),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(T=>{var w,E;return(E=(w=T.getLiveSegmentsToLoadState(this.manifest))==null?void 0:w.to)!=null?E:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(fs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gV(1e3)).subscribe(g=>I(this,[g],function*({liveLoadBufferLength:f,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let S=this.element.playbackRate,y=Li(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,L=isFinite(f)?f:m,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),q=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(q);let P="none";if(_?P="active_low_latency":this.isLowLatency$.getValue()&&q?(this.bufferManagers.forEach($=>$.proceedLowLatencyLive()),P="active_low_latency"):y!==0&&L<T?P="live_forward_buffering":L<T+E&&(P="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let $=p-(T+w),M=this.normolizeLiveOffset(Math.trunc(y+$/S)),B=Math.abs(M-y),A=0;!f||B<=this.tuning.dashCmafLive.offsetCalculationError?A=y:M>0&&B>this.tuning.dashCmafLive.offsetCalculationError&&(A=M),this.manifestUrlString=Te(this.manifestUrlString,A,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,yield this.updateLive())}),f=>{this.error$.next({id:"updateLive",category:Zt.VIDEO_PIPELINE,thrown:f,message:"Failed to update live with subscription"})}))}let l=vr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ms(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=vr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ms(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=fs({allBuffersFull:l,someBufferEnded:d}).pipe(oo(),ms(({allBuffersFull:p,someBufferEnded:f})=>p&&f),hl(p=>p));if(this.representationSubscription.add(vr(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:Zt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(vr(...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,ch.default)((0,ch.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&&lo(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=oh(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:Zt.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 pl({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,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return I(this,null,function*(){var r,a,n;hs(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?uh()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=Te(this.manifestUrlString,i,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(a=this.audioBufferManager)==null?void 0:a.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){hs(this.element),this.state$.setState("running"),this.subscription.add(vr(...SV.map(e=>Ei(this.element,e)),Ei(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Zt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ei(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(Ei(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&He(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,m,g,S,y,v,T,w,E,L;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=uh(),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=(w=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?w: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 _=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(_).catch(q=>{this.error$.next({id:"stallIntervalCallback",category:Zt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:q})}),r.liveLastOffset=_}else{let _=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(_),(L=this.audioBufferManager)==null||L.maintain(_),r.position=_}this.tracer.log("stallIntervalCallback",uo(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=oh(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:Zt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return I(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return I(this,null,function*(){var r,a,n,o,u;hs(this.element),hs(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),He(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Mx(this.element)||Mx(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",uo({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;lo(this.element)&&lo(this.source)&&lo(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=mV(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}updateLive(){return I(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.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",uo({isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime,jumpTo:n,resultCurrentTime:this.element.currentTime})))}}};import{combine as yV,map as TV,observeElementSize as IV,Subscription as xV,ValueSubject as dh,noop as EV}from"@vkontakte/videoplayer-shared/es2015";var bl=class{constructor(){this.subscription=new xV;this.pipSize$=new dh(void 0);this.videoSize$=new dh(void 0);this.elementSize$=new dh(void 0);this.pictureInPictureWindowRemoveEventListener=EV}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(IV(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(yV({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(TV(({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 yr=class{constructor(e){this.subscription=new MV;this.videoState=new G("stopped");this.droppedFramesManager=new Yr;this.stallsManager=new sl;this.elementSizeManager=new bl;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ci;this.audioTrackSwitchHistory=new Ci;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 PV(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new us(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=_e(e.container,e.tuning),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new ml({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=Ue(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,a=o=>{e.error$.next({id:r,category:Lx.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(Bx(l=>!!l.length),$x()).subscribe(l=>{this.droppedFramesManager.connect({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(ph(l=>l.to.state!=="none"),gl());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(Bx(Dx),$x()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(ph(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(Et(this.video,t.isLooped,r)),this.subscription.add(Ne(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(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(AV(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of d.audio){h.push(Kp(p));let f=[];for(let m of p.representations){let g=mx(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(Xp(h));let p=[];for(let f of h.representations){let m=fx(D(x({},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=bx(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(Sl(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$,RV(this.video,"progress")).subscribe(()=>I(this,null,function*(){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=gr(this.videoTracksMap.keys(),m=>{var g;return((g=this.videoTracksMap.get(m))==null?void 0:g.representation.id)===c.id});Dx(p)&&(this.stallsManager.lastVideoTrackSelected=p);let f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),l==="manifest_ready")yield this.player.initRepresentations(c.id,h==null?void 0:h.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",c.id),h){let m=!!t.audioStream.getTransition();yield 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(gl()).subscribe(l=>{let d=gr(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(Xp(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(gl()).subscribe(l=>{let d=gr(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(Kp(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(ph(({to:l})=>l==="ready"),gl());this.subscription.add(Sl(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,hh(["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(Sl(o,this.player.state$.stateChangeEnded$,hh(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Sl(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,hh(["init"])).pipe(kV(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var _,q,P,$,M,B,A,C,k,O,ee,te;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?$a:Da,t=this.params.tuning.useNewAutoSelectVideoTrack?ku:Au,i=this.params.tuning.useNewAutoSelectVideoTrack?Yt:Pu,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(_=r.videoTrack.getState())==null?void 0:_.id,u=gr(this.videoTracksMap.keys(),H=>H.id===o),l=a.currentVideoTrack$.getValue(),d=(($=(P=r.videoStream.getState())!=null?P:u&&((q=this.videoTracksMap.get(u))==null?void 0:q.stream))!=null?$:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=gr(this.videoStreamsMap.keys(),H=>H.id===d.id),h=c&&this.videoStreamsMap.get(c);if(!h)return;let p=fe(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=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(S==null?void 0:S.id)&&gr(this.audioStreamsMap.keys(),H=>H.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(y){if(u&&!n){let H=e(u,h,(B=this.audioStreamsMap.get(y))!=null?B:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(A=H==null?void 0:H.bitrate)!=null?A:-1/0)}if(l){let H=e(l,h,(C=this.audioStreamsMap.get(y))!=null?C:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=H==null?void 0:H.bitrate)!=null?k:-1/0)}}let T=u;(n||!T)&&(T=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}));let w=y&&t(T,h,(O=this.audioStreamsMap.get(y))!=null?O:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate}),E=(ee=this.videoTracksMap.get(T))==null?void 0:ee.representation,L=w&&((te=this.audioTracksMap.get(w))==null?void 0:te.representation);E&&L?(this.selectedRepresentations.video=E,this.selectedRepresentations.audio=L):E&&!L&&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(){qe(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:Lx.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),Fe(this.video),this.tracer.end()}};var co=class extends yr{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 fh,merge as Cx,filter as Vx,filterChanged as LV,isNullable as mh,map as Ox,ValueSubject as bh,isNonNullable as BV}from"@vkontakte/videoplayer-shared/es2015";var po=class extends yr{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 bh(1);a(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(Ox(o=>o.to)).subscribe(this.player.isLowLatency$)).add(fh({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Ox(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(Vx(o=>BV(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(fh({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Cx(i.playbackRateState$,new bh(1))}).pipe(Vx(({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||mh(l)||(e=o-l)})).add(fh({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Cx(i.playbackRateState$,new bh(1))}).pipe(LV((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||mh(o)||mh(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=gx(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 Fx=U(Aa(),1);import{assertNever as ho,assertNonNullable as _x,debounce as DV,ErrorCategory as vl,filter as $V,isNonNullable as CV,isNullable as VV,map as yl,merge as OV,Observable as _V,observableFrom as FV,Subscription as NV,videoSizeToQuality as UV}from"@vkontakte/videoplayer-shared/es2015";var qt={};var bs=(s,e)=>new _V(t=>{let i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)}),fo=class{constructor(e){this.subscription=new NV;this.videoState=new G("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:ho(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ho(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ho(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:ho(e)}break;default:ho(t)}};this.textTracksManager=new nt(e.source.url),this.video=_e(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Pe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:vl.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Fx.default)(import("hls.js").then(r=>{e||(qt.Hls=r.default,qt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){_x(qt.Hls,"hls.js not loaded"),this.hls=new qt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){_x(qt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:vl.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=Ue(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(Et(this.video,e.isLooped,i)),this.subscription.add(Ne(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(at(this.video,e.playbackRate,r.playbackRateState$,i)),a(ut(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(yl(l=>l.to)),this.params.output.playbackState$),this.subscription.add(bs(this.hls,qt.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:vl.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(bs(this.hls,qt.Events.MANIFEST_PARSED).pipe(yl(({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:UV({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(bs(this.hls,qt.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(bs(this.hls,qt.Events.LEVEL_LOADING).pipe(yl(({url:l})=>Pe(l))),t.hostname$),a(bs(this.hls,qt.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=bs(this.hls,qt.Events.LEVEL_SWITCHED).pipe(yl(({level:l})=>n(this.hls.levels[l])));o.pipe($V(CV)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Bi(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(VV(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=OV(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,FV(["init"])).pipe(DV(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return I(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vl.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 Nx="X-Playback-Duration",gh=s=>I(void 0,null,function*(){var r;let e=yield wt(s),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Nx)?parseInt(e.headers.get(Nx),10):void 0});import{assertNever as JV,combine as ZV,debounce as eO,ErrorCategory as xl,filter as tO,filterChanged as iO,isNonNullable as Hx,isNullable as El,map as jx,merge as rO,observableFrom as sO,Subscription as aO,ValueSubject as yh,VideoQuality as nO}from"@vkontakte/videoplayer-shared/es2015";var vh=U(Yc(),1);import{videoSizeToQuality as qV,getExponentialDelay as HV}from"@vkontakte/videoplayer-shared/es2015";var jV=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=qV({width:t,height:i})}return e!=null?e:null},GV=(s,e)=>{var a,n;let t=s.split(`
|
|
76
|
+
`),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,vh.default)(l[1].split(",").map(y=>y.split("="))),h=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,p=jV(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(T=>parseInt(T,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,vh.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}},zV=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),Sh=0,Ux=(r,...a)=>I(void 0,[r,...a],function*(s,e=s,t,i){let o=yield(yield wt(s,i)).text();Sh+=1;try{let{qualityManifests:u,textTracks:l}=GV(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(Sh<=t.manifestRetryMaxCount)return yield zV(HV(Sh-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ux(s,e,t)}return{qualityManifests:[],textTracks:[]}}),Tl=Ux;import{isNonNullable as WV,Subscription as QV,throttle as YV,ValueSubject as qx,Subject as KV,ErrorCategory as XV}from"@vkontakte/videoplayer-shared/es2015";var Il=class{constructor(e,t,i,r,a){this.subscription=new QV;this.abortControllers={destroy:new ae,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new qx(null);this.getCurrentTime$=new qx(null);this.error$=new KV;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(YV(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return I(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return I(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return I(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield wt(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(`
|
|
77
|
+
`),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(WV(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([D(x({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return I(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ae;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return I(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:XV.WTF,thrown:t,message:e})}};var mo=class{constructor(e){this.subscription=new aO;this.videoState=new G("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new yh([]);this.liveOffset=new or;this.manifestStartTime$=new yh(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 JV(t)}};var i;this.params=e,this.video=_e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:nO.INVARIANT,url:this.params.source.url};let t=(r,a)=>Tl(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 Il(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:xl.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:xl.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(Pe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new yh((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:xl.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Ue(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(Ne(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(iO(),jx(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&&Hx(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(Pe(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(ZV({startTime:this.manifestStartTime$.pipe(tO(Hx)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(jx(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=rO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,sO(["init"])).pipe(eO(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),Fe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(El(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=Te(r.toString(),this.liveOffset.getTotalOffset(),a);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),gh(n).then(d=>{var c;if(!El(d))this.maxSeekBackTime$.next(d);else{let h=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(El(h)||!isFinite(h))&&wt(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();gh(g).then(S=>{El(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){qe(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:xl.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=Te(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 oO,debounce as uO,ErrorCategory as Th,fromEvent as Ih,isNonNullable as lO,isNullable as cO,map as Gx,merge as zx,observableFrom as Wx,Subscription as dO,ValueSubject as pO,VideoQuality as hO}from"@vkontakte/videoplayer-shared/es2015";var bo=class{constructor(e){this.subscription=new dO;this.videoState=new G("stopped");this.manifests$=new pO([]);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 oO(t)}};this.textTracksManager=new nt(e.source.url),this.params=e,this.video=_e(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:hO.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Tl(Te(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:Th.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:Th.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Ue(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(Gx(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Et(this.video,t.isLooped,i)),this.subscription.add(Ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(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&&lO(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(Pe(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(Gx(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)),!z.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(zx(Ih(o,"addtrack"),Ih(o,"removetrack"),Ih(o,"change"),Wx(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=zx(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Wx(["init"])).pipe(uO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Fe(this.video)}prepare(){var a,n;let e=this.selectManifest();if(cO(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(){qe(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:Th.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Kx=U(Lr(),1),xh=U(nr(),1),Xx=U(Ft(),1);import{assertNever as fO,assertNonNullable as Qx,debounce as mO,ErrorCategory as Yx,isHigherOrEqual as bO,isLowerOrEqual as gO,isNonNullable as SO,merge as vO,observableFrom as yO,Subscription as TO,map as IO}from"@vkontakte/videoplayer-shared/es2015";var go=class{constructor(e){this.subscription=new TO;this.videoState=new G("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 fO(e)}};this.params=e,this.video=_e(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Kx.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,xh.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:Yx.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Ue(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(IO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Et(this.video,t.isLooped,i)),this.subscription.add(Ne(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(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&&SO(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=vO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,yO(["init"])).pipe(mO(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),Fe(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;Qx(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Qx(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=_i(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Pe(t))}playIfAllowed(){qe(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:Yx.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=Yt(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});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,a=!!(e.max||e.min),n=(0,xh.default)(this.trackUrls).map(c=>c.track);if(!r||!a||jr(e,n[0].quality,(d=(0,Xx.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?gO(r,e.max):!0,u=e.min?bO(r,e.min):!0;o&&u||i(e)}};import{assertNever as Zx,debounce as PO,merge as AO,observableFrom as kO,Subscription as RO,ValueSubject as MO,ErrorCategory as wh,VideoQuality as LO}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as xO}from"@vkontakte/videoplayer-shared/es2015";var Jx=["stun:videostun.mycdn.me:80"],EO=1e3,wO=3,Eh=()=>null,wl=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=Eh;this.externalStopCallback=Eh;this.externalErrorCallback=Eh;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return I(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return I(this,null,function*(){try{let e={iceServers:[{urls:Jx}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return I(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return I(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:xO.WTF,message:e.message})}onPeerConnectionStream(e){return I(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return I(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),EO)}normalizeOptions(e={}){let t={stunServerList:Jx,maxRetryNumber:wO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var So=class{constructor(e){this.videoState=new G("stopped");this.maxSeekBackTime$=new MO(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 Zx(e)}};this.subscription=new RO,this.params=e,this.video=_e(e.container,e.tuning),this.liveStreamClient=new wl(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:wh.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})},r=Ue(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(Ne(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Zx(n.to)}},i)).add(AO(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,kO(["init"])).pipe(PO(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(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:LO.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:wh.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){qe(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:wh.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var vo=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 To,assertNonNullable as qi,ErrorCategory as Pl,filter as aE,isNonNullable as nE,isNullable as _O,map as FO,merge as NO,once as UO,Subject as Ce,Subscription as oE,ValueSubject as Y}from"@vkontakte/videoplayer-shared/es2015";import{Observable as BO,map as eE,Subscription as DO,Subject as $O}from"@vkontakte/videoplayer-shared/es2015";var tE=s=>new BO(e=>{let t=new DO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(eE(({from:l,to:d})=>`${l}-${d}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(eE(({type:l})=>l!==void 0)),n=new $O,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 CO,Subscription as VO,combine as OO,filter as rE,once as sE}from"@vkontakte/videoplayer-shared/es2015";function iE(){return new(window.AudioContext||window.webkitAudioContext)}var yo=class yo{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ae;this.subscriptions=new VO;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(rE(a=>!!a.type),sE()).subscribe(({type:a})=>this.subscribe(a)))}subscribe(e){z.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(OO({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(rE(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),sE()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return I(this,null,function*(){let{volumeMultiplier:t}=this,i=iE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let 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:yo.errorId,category:CO.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${yo.errorId} exception`,thrown:e})}};yo.errorId="VolumeMultiplierManager";var gs=yo;var qO={chunkDuration:5e3,maxParallelRequests:5},Io=class{constructor(e){this.current$=new Y({type:void 0});this.providerError$=new Ce;this.noAvailableProvidersError$=new Ce;this.volumeMultiplierError$=new Ce;this.providerOutput={position$:new Y(0),duration$:new Y(1/0),volume$:new Y({muted:!1,volume:1}),availableVideoStreams$:new Y([]),currentVideoStream$:new Y(void 0),availableVideoTracks$:new Y([]),currentVideoTrack$:new Y(void 0),availableAudioStreams$:new Y([]),currentAudioStream$:new Y(void 0),availableAudioTracks$:new Y([]),currentVideoSegmentLength$:new Y(0),currentAudioSegmentLength$:new Y(0),isAudioAvailable$:new Y(!0),autoVideoTrackLimitingAvailable$:new Y(!1),autoVideoTrackLimits$:new Y(void 0),currentBuffer$:new Y(void 0),isBuffering$:new Y(!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 Y(void 0),isLiveEnded$:new Y(null),isLowLatency$:new Y(!1),canChangePlaybackSpeed$:new Y(!0),liveTime$:new Y(void 0),liveBufferTime$:new Y(void 0),liveLatency$:new Y(void 0),severeStallOccurred$:new Ce,availableTextTracks$:new Y([]),currentTextTrack$:new Y(void 0),hostname$:new Y(void 0),httpConnectionType$:new Y(void 0),httpConnectionReused$:new Y(void 0),inPiP$:new Y(!1),inFullscreen$:new Y(!1),element$:new Y(void 0),elementVisible$:new Y(!0),availableSources$:new Y(void 0),is3DVideo$:new Y(!1),playbackState$:new Y(""),getCurrentTime$:new Y(null)};this.subscription=new oE;this.volumeMultiplierManager=null;this.params=e;let t=NI([...qI(this.params.tuning),...UI(this.params.tuning)],this.params.tuning).filter(l=>nE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,Ph.default)(r,l)),...t.filter(l=>(0,Ph.default)(r,l))]:a=t,this.screenFormatsIterator=new vo(a);let n=[...Rp(!0),...Rp(!1)];this.chromecastFormatsIterator=new vo(n.filter(l=>nE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&gs.isSupported()&&(this.volumeMultiplierManager=new gs(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(_O(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Pl.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;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(e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return To(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 qi(u),this.params.tuning.useNewDashProvider?new co(D(x({},o),{source:u,sourceHls:l})):new An(D(x({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qi(u),this.params.tuning.useNewDashProvider?new po(D(x({},o),{source:u})):new kn(D(x({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return qi(u),z.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new bo(D(x({},o),{source:u})):new fo(D(x({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return qi(u),new mo(D(x({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return qi(u),new go(D(x({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return qi(u),new Oy(D(x({},o),{source:u,config:D(x({},qO),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return qi(u),new So({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 To(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 qi(o),new ka({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 To(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return To(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 To(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 D(x({},e),{url:i(e.url)})}return(0,lE.default)((0,uE.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new oE,t=!1,i=0;return e.add(NO(this.providerOutput.error$.pipe(aE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),tE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(FO(r=>({id:`ProviderHangup:${r}`,category:Pl.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(aE(({to:a})=>a==="playing"),UO()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination;if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=r.category===Pl.NETWORK,o=r.category===Pl.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<this.params.tuning.providerErrorLimit&&!o;l?(i++,this.reinitProvider()):u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(a!=null?a:"SCREEN"))}})),e}};import{fromEvent as Al,once as HO,combine as jO,Subscription as cE,ValueSubject as Ah,map as GO,filter as zO,isNonNullable as kl,now as It,safeStorage as kh}from"@vkontakte/videoplayer-shared/es2015";var WO=5e3,dE="one_video_throughput",pE="one_video_rtt",wi=window.navigator.connection,hE=()=>{let s=wi==null?void 0:wi.downlink;if(kl(s)&&s!==10)return s*1e3},fE=()=>{let s=wi==null?void 0:wi.rtt;if(kl(s)&&s!==3e3)return s},mE=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},Rh=class s{constructor(e){this.subscription=new cE;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=s.load(dE)||(e.useBrowserEstimation?hE():void 0)||WO,i=(a=(r=s.load(pE))!=null?r:e.useBrowserEstimation?fE():void 0)!=null?a:0;if(this.throughput$=new Ah(t),this.rtt$=new Ah(i),this.rttAdjustedThroughput$=new Ah(mE(t,i,e.rttPenaltyRequestSize)),this.throughput=yi.getSmoothedValue(t,-1,e),this.rtt=yi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=hE();u&&this.throughput.next(u);let l=fE();kl(l)&&this.rtt.next(l)};wi&&"onchange"in wi&&this.subscription.add(Al(wi,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{kh.set(dE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{kh.set(pE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(jO({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(GO(({throughput:n,rtt:o})=>mE(n,o,e.rttPenaltyRequestSize)),zO(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=It(),r=new cE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Al(e,"progress").pipe(HO()).subscribe(a=>{t=a.loaded,i=It()}));break;case 1:case 0:r.add(Al(e,"loadstart").subscribe(()=>{t=0,i=It()}));break}r.add(Al(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=It(),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=It(),n=0,o=It(),u=d=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=h=>I(this,[h],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(r,It()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=It();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-a;m&&this.addRawSpeed(n,m,1,t),n=c.byteLength,a=It()}else n+=c.byteLength;o=It()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&It()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,It()-o,this.concurrentDownloads.size),n=0,o=It());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(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=kh.get(e);if(kl(t))return(i=parseInt(t,10))!=null?i:void 0}},bE=Rh;import{fillWithDefault as QO,VideoQuality as Rl}from"@vkontakte/videoplayer-shared/es2015";var gE={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:Rl.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Rl.Q_720P,trafficSavingLimit:Rl.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:Rl.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,vktvAbrThrottle:null},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},SE=s=>{var e;return D(x({},QO(s,gE)),{configName:[...(e=s.configName)!=null?e:[],...gE.configName]})};import{assertNonNullable as Ml,combine as xo,ErrorCategory as Ll,filter as re,filterChanged as rt,fromEvent as Lh,isNonNullable as IE,isNullable as t_,map as ge,mapTo as xE,merge as Tr,now as Bl,once as X,Subject as se,Subscription as EE,tap as Bh,ValueSubject as V,isHigher as i_,isInvariantQuality as wE,InternalsExposure as r_}from"@vkontakte/videoplayer-shared/es2015";import{merge as YO,map as KO,filter as vE,isNonNullable as XO}from"@vkontakte/videoplayer-shared/es2015";var Mh=({seekState:s,position$:e})=>YO(s.stateChangeEnded$.pipe(KO(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),vE(XO)),e.pipe(vE(()=>s.getState().state==="none")));import{assertNonNullable as JO}from"@vkontakte/videoplayer-shared/es2015";var yE=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return JO(e,`Wrong container or containerId {${s.container}}`),e};import{filter as ZO,once as e_}from"@vkontakte/videoplayer-shared/es2015";var TE=(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(ZO(r=>r.length>0),e_()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};var Dl=class{constructor(e={configName:[]}){this.subscription=new EE;this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new V(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new V(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new G("stopped"),seekState:new G({state:"none"}),volume:new G({volume:1,muted:!1}),videoTrack:new G(void 0),videoStream:new G(void 0),audioStream:new G(void 0),autoVideoTrackSwitching:new G(!0),autoVideoTrackLimits:new G({}),isLooped:new G(!1),isLowLatency:new G(!1),playbackRate:new G(1),externalTextTracks:new G([]),internalTextTracks:new G([]),currentTextTrack:new G(void 0),textTrackCuesSettings:new G({}),cameraOrientation:new G({x:0,y:0})};this.info={playbackState$:new V(void 0),position$:new V(0),duration$:new V(1/0),muted$:new V(!1),volume$:new V(1),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableQualities$:new V([]),availableQualitiesFps$:new V({}),currentQuality$:new V(void 0),isAutoQualityEnabled$:new V(!0),autoQualityLimitingAvailable$:new V(!1),autoQualityLimits$:new V({}),predefinedQualityLimitType$:new V("unknown"),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),isAudioAvailable$:new V(!0),currentPlaybackRate$:new V(1),currentBuffer$:new V({start:0,end:0}),isBuffering$:new V(!0),isStalled$:new V(!1),isEnded$:new V(!1),isLooped$:new V(!1),isLive$:new V(void 0),isLiveEnded$:new V(null),canChangePlaybackSpeed$:new V(void 0),atLiveEdge$:new V(void 0),atLiveDurationEdge$:new V(void 0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),currentFormat$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),throughputEstimation$:new V(void 0),rttEstimation$:new V(void 0),videoBitrate$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),surface$:new V("none"),chromecastState$:new V("NOT_AVAILABLE"),chromecastDeviceName$:new V(void 0),intrinsicVideoSize$:new V(void 0),availableSources$:new V(void 0),is3DVideo$:new V(!1),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0)};this.events={inited$:new se,ready$:new se,started$:new se,playing$:new se,paused$:new se,stopped$:new se,willStart$:new se,willResume$:new se,willPause$:new se,willStop$:new se,willDestruct$:new se,watchCoverageRecord$:new se,watchCoverageLive$:new se,managedError$:new se,fatalError$:new se,fetcherRecoverableError$:new se,ended$:new se,looped$:new se,seeked$:new se,willSeek$:new se,autoplaySoundProhibited$:new se,firstBytes$:new se,loadedMetadata$:new se,firstFrame$:new se,canplay$:new se,log$:new se,fetcherError$:new se,severeStallOccured$:new se};this.experimental={element$:new V(void 0),tuningConfigName$:new V([]),enableDebugTelemetry$:new V(!1),getCurrentTime$:new V(null)};if(this.tuning=SE(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Lo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast}),this.throughputEstimator=new bE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new r_("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{let a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){let u=n.map(c=>JSON.stringify(c,(h,p)=>{let f=typeof p;return(0,PE.default)(["number","string","boolean"],f)?p:p===null?null:`<${f}>`})),l=`Player.${String(i)}`,d=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Ll.WTF,message:d,thrown:o}),o}}}})}initVideo(e){var a;this.config=e,(a=this.internalsExposure)==null||a.expose({config:e,tuning:this.tuning});let t=()=>{var n,o,u;this.domContainer=yE(e),this.chromecastInitializer.contentId=(n=e.meta)==null?void 0:n.videoId,this.providerContainer=new Io({sources:e.sources,meta:(o=e.meta)!=null?o:{},failoverHosts:(u=e.failoverHosts)!=null?u:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?z.isInited$.pipe(re(n=>!!n),X()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?Lh(document,"visibilitychange").pipe(X()).subscribe(r):r(),this}destroy(){var e,t;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(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(re(e=>!!e),X()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(re(e=>!!e),X()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(re(e=>!!e),X()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(re(e=>!!e),X()).subscribe(()=>{let e=this.desiredState.playbackState;e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(re(i=>!!i),X()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),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(re(t=>!!t),X()).subscribe(()=>{let t=this.info.duration$.getValue();isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(re(i=>!!i),X()).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.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).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.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:a,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).subscribe(()=>{Ml(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),X()).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(re(t=>!!t),X()).subscribe(()=>{this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).subscribe(()=>{this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).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(re(t=>!!t),X()).subscribe(()=>{var i;Ml(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).subscribe(()=>{this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>x({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).subscribe(()=>{var t;TE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e)})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).subscribe(()=>{this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).subscribe(()=>{this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(re(i=>!!i),X()).subscribe(()=>{let i=this.getScene3D();i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(re(t=>!!t),X()).subscribe(()=>{let t=this.getScene3D();t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(re(i=>!!i),X()).subscribe(()=>{let i=this.getScene3D();if(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(re(e=>e),X()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(re(e=>!!e),X()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(t_(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return IE(i)?i/1e3:e.currentTime}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(Tr(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(ge(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(ge(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(ge(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(ge(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(ge(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(zd(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(re(({from:e})=>e==="stopped"),X()).subscribe(()=>{this.initedAt=Bl(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();n.state==="requested"?this.desiredState.seekState.setState(D(x({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ll.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(X()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(ge(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(ge(n=>n.destination),rt()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(xo({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(ge(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>wE(u)?1:wE(l)?-1:i_(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(rt()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(re(n=>IE(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(rt((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(rt((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(rt()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(rt()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(rt()).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(ge(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(Bh(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(xo({hasLiveOffsetByPaused:Tr(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(ge(n=>n.to),rt(),ge(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(xo({atLiveEdge:xo({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Mh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(ge(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),rt(),Bh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(ge(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(xo({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(ge(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),rt(),Bh(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(ge(n=>n.muted),rt()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(ge(n=>n.volume),rt()).subscribe(this.info.volume$)).add(Mh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Tr(e.providerOutput.endedEvent$.pipe(xE(!0)),e.providerOutput.seekedEvent$.pipe(xE(!1))).pipe(rt()).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(ge(n=>({id:n?`No${n}`:"NoProviders",category:Ll.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(X(),ge(n=>n!=null?n:Bl()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(X(),ge(()=>Bl()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(X(),ge(()=>Bl()-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 V(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new V(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(re(({to:n})=>n==="playing"),X()).subscribe(()=>i.next(!1)));let r=0,a=Tr(e.providerOutput.isBuffering$,t,i).pipe(ge(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),rt());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(Tr(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(Tr(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(ge(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 EE;this.subscription.add(t),this.subscription.add(e.current$.pipe(rt((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(re(i=>i.length>0),X()).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=Yt(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})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Ml(this.providerContainer),Ml(e),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart)}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=()=>I(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ll.DOM,message:String(r)})})});this.subscription.add(Tr(Lh(document,"visibilitychange"),Lh(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);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 mte,Observable as bte,Subject as gte,ValueSubject as Ste,VideoQuality as vte}from"@vkontakte/videoplayer-shared/es2015";var yte=`@vkontakte/videoplayer-core@${Vh}`;export{Eo as ChromecastState,ql as HttpConnectionType,bte as Observable,st as PlaybackState,Dl as Player,wo as PredefinedQualityLimits,yte as SDK_VERSION,gte as Subject,mte as Subscription,Hl as Surface,Vh as VERSION,Ste as ValueSubject,fi as VideoFormat,vte as VideoQuality,z as clientChecker,La as isMobile};
|