@vkontakte/videoplayer-core 2.0.122 → 2.0.123-dev.483e1429.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 +23 -23
- package/es2015.esm.js +20 -20
- package/es2018.cjs.js +23 -23
- package/es2018.esm.js +21 -21
- package/esnext.cjs.js +24 -24
- package/esnext.esm.js +25 -25
- package/evergreen.esm.js +21 -21
- package/package.json +2 -2
- package/types/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +8 -7
- package/types/providers/DashProvider/baseDashProvider.d.ts +1 -1
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -1
- package/types/providers/DashProvider/lib/player.d.ts +1 -1
- package/types/providers/DashProvider/lib/sourceBufferTaskQueue.d.ts +1 -0
- package/types/utils/buffer/isSourceBufferValid.d.ts +3 -0
- package/types/utils/tuningConfig.d.ts +2 -1
package/es2015.esm.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.123-dev.483e1429.0
|
|
3
|
+
* Wed, 18 Dec 2024 02:21:18 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-123/doc/
|
|
5
5
|
*/
|
|
6
|
-
var _T=Object.create;var Gn=Object.defineProperty,NT=Object.defineProperties,FT=Object.getOwnPropertyDescriptor,qT=Object.getOwnPropertyDescriptors,UT=Object.getOwnPropertyNames,ns=Object.getOwnPropertySymbols,HT=Object.getPrototypeOf,Qn=Object.prototype.hasOwnProperty,jc=Object.prototype.propertyIsEnumerable;var jT=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var et=Math.pow,Hc=(a,e,t)=>e in a?Gn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,P=(a,e)=>{for(var t in e||(e={}))Qn.call(e,t)&&Hc(a,t,e[t]);if(ns)for(var t of ns(e))jc.call(e,t)&&Hc(a,t,e[t]);return a},M=(a,e)=>NT(a,qT(e));var Gc=(a,e)=>{var t={};for(var r in a)Qn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&ns)for(var r of ns(a))e.indexOf(r)<0&&jc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var GT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of UT(e))!Qn.call(a,i)&&i!==t&&Gn(a,i,{get:()=>e[i],enumerable:!(r=FT(e,i))||r.enumerable});return a};var F=(a,e,t)=>(t=a!=null?_T(HT(a)):{},GT(e||!a||!a.__esModule?Gn(t,"default",{value:a,enumerable:!0}):t,a));var k=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Wn=function(a,e){this[0]=a,this[1]=e},re=(a,e,t)=>{var r=(n,o,u,l)=>{try{var d=t[n](o),c=(o=d.value)instanceof Wn,p=d.done;Promise.resolve(c?o[0]:o).then(h=>c?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[jT("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Z=m((Kn,Wc)=>{"use strict";var pi=function(a){return a&&a.Math===Math&&a};Wc.exports=pi(typeof globalThis=="object"&&globalThis)||pi(typeof window=="object"&&window)||pi(typeof self=="object"&&self)||pi(typeof global=="object"&&global)||pi(typeof Kn=="object"&&Kn)||function(){return this}()||Function("return this")()});var pe=m((fD,Yc)=>{"use strict";Yc.exports=function(a){try{return!!a()}catch(e){return!0}}});var hi=m((mD,zc)=>{"use strict";var QT=pe();zc.exports=!QT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Jn=m((bD,Zc)=>{"use strict";var WT=hi(),Xc=Function.prototype,Kc=Xc.apply,Jc=Xc.call;Zc.exports=typeof Reflect=="object"&&Reflect.apply||(WT?Jc.bind(Kc):function(){return Jc.apply(Kc,arguments)})});var se=m((gD,rd)=>{"use strict";var ed=hi(),td=Function.prototype,Xn=td.call,YT=ed&&td.bind.bind(Xn,Xn);rd.exports=ed?YT:function(a){return function(){return Xn.apply(a,arguments)}}});var Jt=m((vD,ad)=>{"use strict";var id=se(),zT=id({}.toString),KT=id("".slice);ad.exports=function(a){return KT(zT(a),8,-1)}});var Zn=m((SD,sd)=>{"use strict";var JT=Jt(),XT=se();sd.exports=function(a){if(JT(a)==="Function")return XT(a)}});var X=m((yD,nd)=>{"use strict";var eo=typeof document=="object"&&document.all;nd.exports=typeof eo=="undefined"&&eo!==void 0?function(a){return typeof a=="function"||a===eo}:function(a){return typeof a=="function"}});var ke=m((TD,od)=>{"use strict";var ZT=pe();od.exports=!ZT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Re=m((ID,ud)=>{"use strict";var eI=hi(),us=Function.prototype.call;ud.exports=eI?us.bind(us):function(){return us.apply(us,arguments)}});var to=m(dd=>{"use strict";var ld={}.propertyIsEnumerable,cd=Object.getOwnPropertyDescriptor,tI=cd&&!ld.call({1:2},1);dd.f=tI?function(e){var t=cd(this,e);return!!t&&t.enumerable}:ld});var fi=m((xD,pd)=>{"use strict";pd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var fd=m((PD,hd)=>{"use strict";var rI=se(),iI=pe(),aI=Jt(),ro=Object,sI=rI("".split);hd.exports=iI(function(){return!ro("z").propertyIsEnumerable(0)})?function(a){return aI(a)==="String"?sI(a,""):ro(a)}:ro});var wr=m((AD,md)=>{"use strict";md.exports=function(a){return a==null}});var Rt=m((wD,bd)=>{"use strict";var nI=wr(),oI=TypeError;bd.exports=function(a){if(nI(a))throw new oI("Can't call method on "+a);return a}});var Xt=m((kD,gd)=>{"use strict";var uI=fd(),lI=Rt();gd.exports=function(a){return uI(lI(a))}});var $e=m((RD,vd)=>{"use strict";var cI=X();vd.exports=function(a){return typeof a=="object"?a!==null:cI(a)}});var kr=m(($D,Sd)=>{"use strict";Sd.exports={}});var lt=m((LD,Td)=>{"use strict";var io=kr(),ao=Z(),dI=X(),yd=function(a){return dI(a)?a:void 0};Td.exports=function(a,e){return arguments.length<2?yd(io[a])||yd(ao[a]):io[a]&&io[a][e]||ao[a]&&ao[a][e]}});var mi=m((MD,Id)=>{"use strict";var pI=se();Id.exports=pI({}.isPrototypeOf)});var Zt=m((CD,Pd)=>{"use strict";var hI=Z(),Ed=hI.navigator,xd=Ed&&Ed.userAgent;Pd.exports=xd?String(xd):""});var no=m((DD,Ld)=>{"use strict";var $d=Z(),so=Zt(),Ad=$d.process,wd=$d.Deno,kd=Ad&&Ad.versions||wd&&wd.version,Rd=kd&&kd.v8,Qe,ls;Rd&&(Qe=Rd.split("."),ls=Qe[0]>0&&Qe[0]<4?1:+(Qe[0]+Qe[1]));!ls&&so&&(Qe=so.match(/Edge\/(\d+)/),(!Qe||Qe[1]>=74)&&(Qe=so.match(/Chrome\/(\d+)/),Qe&&(ls=+Qe[1])));Ld.exports=ls});var oo=m((OD,Cd)=>{"use strict";var Md=no(),fI=pe(),mI=Z(),bI=mI.String;Cd.exports=!!Object.getOwnPropertySymbols&&!fI(function(){var a=Symbol("symbol detection");return!bI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Md&&Md<41})});var uo=m((VD,Dd)=>{"use strict";var gI=oo();Dd.exports=gI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var lo=m((BD,Od)=>{"use strict";var vI=lt(),SI=X(),yI=mi(),TI=uo(),II=Object;Od.exports=TI?function(a){return typeof a=="symbol"}:function(a){var e=vI("Symbol");return SI(e)&&yI(e.prototype,II(a))}});var bi=m((_D,Vd)=>{"use strict";var EI=String;Vd.exports=function(a){try{return EI(a)}catch(e){return"Object"}}});var tt=m((ND,Bd)=>{"use strict";var xI=X(),PI=bi(),AI=TypeError;Bd.exports=function(a){if(xI(a))return a;throw new AI(PI(a)+" is not a function")}});var gi=m((FD,_d)=>{"use strict";var wI=tt(),kI=wr();_d.exports=function(a,e){var t=a[e];return kI(t)?void 0:wI(t)}});var Fd=m((qD,Nd)=>{"use strict";var co=Re(),po=X(),ho=$e(),RI=TypeError;Nd.exports=function(a,e){var t,r;if(e==="string"&&po(t=a.toString)&&!ho(r=co(t,a))||po(t=a.valueOf)&&!ho(r=co(t,a))||e!=="string"&&po(t=a.toString)&&!ho(r=co(t,a)))return r;throw new RI("Can't convert object to primitive value")}});var We=m((UD,qd)=>{"use strict";qd.exports=!0});var jd=m((HD,Hd)=>{"use strict";var Ud=Z(),$I=Object.defineProperty;Hd.exports=function(a,e){try{$I(Ud,a,{value:e,configurable:!0,writable:!0})}catch(t){Ud[a]=e}return e}});var vi=m((jD,Wd)=>{"use strict";var LI=We(),MI=Z(),CI=jd(),Gd="__core-js_shared__",Qd=Wd.exports=MI[Gd]||CI(Gd,{});(Qd.versions||(Qd.versions=[])).push({version:"3.38.0",mode:LI?"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 fo=m((GD,zd)=>{"use strict";var Yd=vi();zd.exports=function(a,e){return Yd[a]||(Yd[a]=e||{})}});var Rr=m((QD,Kd)=>{"use strict";var DI=Rt(),OI=Object;Kd.exports=function(a){return OI(DI(a))}});var Ye=m((WD,Jd)=>{"use strict";var VI=se(),BI=Rr(),_I=VI({}.hasOwnProperty);Jd.exports=Object.hasOwn||function(e,t){return _I(BI(e),t)}});var mo=m((YD,Xd)=>{"use strict";var NI=se(),FI=0,qI=Math.random(),UI=NI(1 .toString);Xd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+UI(++FI+qI,36)}});var he=m((zD,ep)=>{"use strict";var HI=Z(),jI=fo(),Zd=Ye(),GI=mo(),QI=oo(),WI=uo(),$r=HI.Symbol,bo=jI("wks"),YI=WI?$r.for||$r:$r&&$r.withoutSetter||GI;ep.exports=function(a){return Zd(bo,a)||(bo[a]=QI&&Zd($r,a)?$r[a]:YI("Symbol."+a)),bo[a]}});var ap=m((KD,ip)=>{"use strict";var zI=Re(),tp=$e(),rp=lo(),KI=gi(),JI=Fd(),XI=he(),ZI=TypeError,eE=XI("toPrimitive");ip.exports=function(a,e){if(!tp(a)||rp(a))return a;var t=KI(a,eE),r;if(t){if(e===void 0&&(e="default"),r=zI(t,a,e),!tp(r)||rp(r))return r;throw new ZI("Can't convert object to primitive value")}return e===void 0&&(e="number"),JI(a,e)}});var go=m((JD,sp)=>{"use strict";var tE=ap(),rE=lo();sp.exports=function(a){var e=tE(a,"string");return rE(e)?e:e+""}});var cs=m((XD,op)=>{"use strict";var iE=Z(),np=$e(),vo=iE.document,aE=np(vo)&&np(vo.createElement);op.exports=function(a){return aE?vo.createElement(a):{}}});var So=m((ZD,up)=>{"use strict";var sE=ke(),nE=pe(),oE=cs();up.exports=!sE&&!nE(function(){return Object.defineProperty(oE("div"),"a",{get:function(){return 7}}).a!==7})});var dp=m(cp=>{"use strict";var uE=ke(),lE=Re(),cE=to(),dE=fi(),pE=Xt(),hE=go(),fE=Ye(),mE=So(),lp=Object.getOwnPropertyDescriptor;cp.f=uE?lp:function(e,t){if(e=pE(e),t=hE(t),mE)try{return lp(e,t)}catch(r){}if(fE(e,t))return dE(!lE(cE.f,e,t),e[t])}});var yo=m((tO,pp)=>{"use strict";var bE=pe(),gE=X(),vE=/#|\.prototype\./,Si=function(a,e){var t=yE[SE(a)];return t===IE?!0:t===TE?!1:gE(e)?bE(e):!!e},SE=Si.normalize=function(a){return String(a).replace(vE,".").toLowerCase()},yE=Si.data={},TE=Si.NATIVE="N",IE=Si.POLYFILL="P";pp.exports=Si});var Lr=m((rO,fp)=>{"use strict";var hp=Zn(),EE=tt(),xE=hi(),PE=hp(hp.bind);fp.exports=function(a,e){return EE(a),e===void 0?a:xE?PE(a,e):function(){return a.apply(e,arguments)}}});var To=m((iO,mp)=>{"use strict";var AE=ke(),wE=pe();mp.exports=AE&&wE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var rt=m((aO,bp)=>{"use strict";var kE=$e(),RE=String,$E=TypeError;bp.exports=function(a){if(kE(a))return a;throw new $E(RE(a)+" is not an object")}});var er=m(vp=>{"use strict";var LE=ke(),ME=So(),CE=To(),ds=rt(),gp=go(),DE=TypeError,Io=Object.defineProperty,OE=Object.getOwnPropertyDescriptor,Eo="enumerable",xo="configurable",Po="writable";vp.f=LE?CE?function(e,t,r){if(ds(e),t=gp(t),ds(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Po in r&&!r[Po]){var i=OE(e,t);i&&i[Po]&&(e[t]=r.value,r={configurable:xo in r?r[xo]:i[xo],enumerable:Eo in r?r[Eo]:i[Eo],writable:!1})}return Io(e,t,r)}:Io:function(e,t,r){if(ds(e),t=gp(t),ds(r),ME)try{return Io(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new DE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Mr=m((nO,Sp)=>{"use strict";var VE=ke(),BE=er(),_E=fi();Sp.exports=VE?function(a,e,t){return BE.f(a,e,_E(1,t))}:function(a,e,t){return a[e]=t,a}});var te=m((oO,Tp)=>{"use strict";var yi=Z(),NE=Jn(),FE=Zn(),qE=X(),UE=dp().f,HE=yo(),Cr=kr(),jE=Lr(),Dr=Mr(),yp=Ye();vi();var GE=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return NE(a,this,arguments)};return e.prototype=a.prototype,e};Tp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?yi:i?yi[t]:yi[t]&&yi[t].prototype,o=r?Cr:Cr[t]||Dr(Cr,t,{})[t],u=o.prototype,l,d,c,p,h,f,b,g,S;for(p in e)l=HE(r?p:t+(i?".":"#")+p,a.forced),d=!l&&n&&yp(n,p),f=o[p],d&&(a.dontCallGetSet?(S=UE(n,p),b=S&&S.value):b=n[p]),h=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&d?g=jE(h,yi):a.wrap&&d?g=GE(h):s&&qE(h)?g=FE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Dr(g,"sham",!0),Dr(o,p,g),s&&(c=t+"Prototype",yp(Cr,c)||Dr(Cr,c,{}),Dr(Cr[c],p,h),a.real&&u&&(l||!u[p])&&Dr(u,p,h)))}});var Ep=m((uO,Ip)=>{"use strict";var QE=Math.ceil,WE=Math.floor;Ip.exports=Math.trunc||function(e){var t=+e;return(t>0?WE:QE)(t)}});var Ti=m((lO,xp)=>{"use strict";var YE=Ep();xp.exports=function(a){var e=+a;return e!==e||e===0?0:YE(e)}});var Ap=m((cO,Pp)=>{"use strict";var zE=Ti(),KE=Math.max,JE=Math.min;Pp.exports=function(a,e){var t=zE(a);return t<0?KE(t+e,0):JE(t,e)}});var Ao=m((dO,wp)=>{"use strict";var XE=Ti(),ZE=Math.min;wp.exports=function(a){var e=XE(a);return e>0?ZE(e,9007199254740991):0}});var Or=m((pO,kp)=>{"use strict";var ex=Ao();kp.exports=function(a){return ex(a.length)}});var wo=m((hO,$p)=>{"use strict";var tx=Xt(),rx=Ap(),ix=Or(),Rp=function(a){return function(e,t,r){var i=tx(e),s=ix(i);if(s===0)return!a&&-1;var n=rx(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};$p.exports={includes:Rp(!0),indexOf:Rp(!1)}});var Ii=m((fO,Lp)=>{"use strict";Lp.exports=function(){}});var Mp=m(()=>{"use strict";var ax=te(),sx=wo().includes,nx=pe(),ox=Ii(),ux=nx(function(){return!Array(1).includes()});ax({target:"Array",proto:!0,forced:ux},{includes:function(e){return sx(this,e,arguments.length>1?arguments[1]:void 0)}});ox("includes")});var $t=m((gO,Cp)=>{"use strict";var lx=lt();Cp.exports=lx});var Op=m((vO,Dp)=>{"use strict";Mp();var cx=$t();Dp.exports=cx("Array","includes")});var Bp=m((SO,Vp)=>{"use strict";var dx=Op();Vp.exports=dx});var it=m((yO,_p)=>{"use strict";var px=Bp();_p.exports=px});var fs=m((MO,Qp)=>{"use strict";var yx=fo(),Tx=mo(),Gp=yx("keys");Qp.exports=function(a){return Gp[a]||(Gp[a]=Tx(a))}});var Yp=m((CO,Wp)=>{"use strict";var Ix=pe();Wp.exports=!Ix(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ms=m((DO,Kp)=>{"use strict";var Ex=Ye(),xx=X(),Px=Rr(),Ax=fs(),wx=Yp(),zp=Ax("IE_PROTO"),$o=Object,kx=$o.prototype;Kp.exports=wx?$o.getPrototypeOf:function(a){var e=Px(a);if(Ex(e,zp))return e[zp];var t=e.constructor;return xx(t)&&e instanceof t?t.prototype:e instanceof $o?kx:null}});var bs=m((OO,Jp)=>{"use strict";Jp.exports={}});var eh=m((VO,Zp)=>{"use strict";var Rx=se(),Lo=Ye(),$x=Xt(),Lx=wo().indexOf,Mx=bs(),Xp=Rx([].push);Zp.exports=function(a,e){var t=$x(a),r=0,i=[],s;for(s in t)!Lo(Mx,s)&&Lo(t,s)&&Xp(i,s);for(;e.length>r;)Lo(t,s=e[r++])&&(~Lx(i,s)||Xp(i,s));return i}});var Mo=m((BO,th)=>{"use strict";th.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Co=m((_O,rh)=>{"use strict";var Cx=eh(),Dx=Mo();rh.exports=Object.keys||function(e){return Cx(e,Dx)}});var Do=m((NO,oh)=>{"use strict";var ah=ke(),Ox=pe(),sh=se(),Vx=ms(),Bx=Co(),_x=Xt(),Nx=to().f,nh=sh(Nx),Fx=sh([].push),qx=ah&&Ox(function(){var a=Object.create(null);return a[2]=2,!nh(a,2)}),ih=function(a){return function(e){for(var t=_x(e),r=Bx(t),i=qx&&Vx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!ah||(i?u in t:nh(t,u)))&&Fx(o,a?[u,t[u]]:t[u]);return o}};oh.exports={entries:ih(!0),values:ih(!1)}});var uh=m(()=>{"use strict";var Ux=te(),Hx=Do().entries;Ux({target:"Object",stat:!0},{entries:function(e){return Hx(e)}})});var ch=m((UO,lh)=>{"use strict";uh();var jx=kr();lh.exports=jx.Object.entries});var ph=m((HO,dh)=>{"use strict";var Gx=ch();dh.exports=Gx});var Vr=m((jO,hh)=>{"use strict";var Qx=ph();hh.exports=Qx});var tr=m((GO,fh)=>{"use strict";fh.exports={}});var gh=m((QO,bh)=>{"use strict";var Wx=Z(),Yx=X(),mh=Wx.WeakMap;bh.exports=Yx(mh)&&/native code/.test(String(mh))});var _o=m((WO,yh)=>{"use strict";var zx=gh(),Sh=Z(),Kx=$e(),Jx=Mr(),Oo=Ye(),Vo=vi(),Xx=fs(),Zx=bs(),vh="Object already initialized",Bo=Sh.TypeError,eP=Sh.WeakMap,gs,Ei,vs,tP=function(a){return vs(a)?Ei(a):gs(a,{})},rP=function(a){return function(e){var t;if(!Kx(e)||(t=Ei(e)).type!==a)throw new Bo("Incompatible receiver, "+a+" required");return t}};zx||Vo.state?(ze=Vo.state||(Vo.state=new eP),ze.get=ze.get,ze.has=ze.has,ze.set=ze.set,gs=function(a,e){if(ze.has(a))throw new Bo(vh);return e.facade=a,ze.set(a,e),e},Ei=function(a){return ze.get(a)||{}},vs=function(a){return ze.has(a)}):(rr=Xx("state"),Zx[rr]=!0,gs=function(a,e){if(Oo(a,rr))throw new Bo(vh);return e.facade=a,Jx(a,rr,e),e},Ei=function(a){return Oo(a,rr)?a[rr]:{}},vs=function(a){return Oo(a,rr)});var ze,rr;yh.exports={set:gs,get:Ei,has:vs,enforce:tP,getterFor:rP}});var qo=m((YO,Ih)=>{"use strict";var No=ke(),iP=Ye(),Th=Function.prototype,aP=No&&Object.getOwnPropertyDescriptor,Fo=iP(Th,"name"),sP=Fo&&function(){}.name==="something",nP=Fo&&(!No||No&&aP(Th,"name").configurable);Ih.exports={EXISTS:Fo,PROPER:sP,CONFIGURABLE:nP}});var xh=m(Eh=>{"use strict";var oP=ke(),uP=To(),lP=er(),cP=rt(),dP=Xt(),pP=Co();Eh.f=oP&&!uP?Object.defineProperties:function(e,t){cP(e);for(var r=dP(t),i=pP(t),s=i.length,n=0,o;s>n;)lP.f(e,o=i[n++],r[o]);return e}});var Uo=m((KO,Ph)=>{"use strict";var hP=lt();Ph.exports=hP("document","documentElement")});var Qo=m((JO,Mh)=>{"use strict";var fP=rt(),mP=xh(),Ah=Mo(),bP=bs(),gP=Uo(),vP=cs(),SP=fs(),wh=">",kh="<",jo="prototype",Go="script",$h=SP("IE_PROTO"),Ho=function(){},Lh=function(a){return kh+Go+wh+a+kh+"/"+Go+wh},Rh=function(a){a.write(Lh("")),a.close();var e=a.parentWindow.Object;return a=null,e},yP=function(){var a=vP("iframe"),e="java"+Go+":",t;return a.style.display="none",gP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Lh("document.F=Object")),t.close(),t.F},Ss,ys=function(){try{Ss=new ActiveXObject("htmlfile")}catch(e){}ys=typeof document!="undefined"?document.domain&&Ss?Rh(Ss):yP():Rh(Ss);for(var a=Ah.length;a--;)delete ys[jo][Ah[a]];return ys()};bP[$h]=!0;Mh.exports=Object.create||function(e,t){var r;return e!==null?(Ho[jo]=fP(e),r=new Ho,Ho[jo]=null,r[$h]=e):r=ys(),t===void 0?r:mP.f(r,t)}});var Br=m((XO,Ch)=>{"use strict";var TP=Mr();Ch.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:TP(a,e,t),a}});var Ko=m((ZO,Vh)=>{"use strict";var IP=pe(),EP=X(),xP=$e(),PP=Qo(),Dh=ms(),AP=Br(),wP=he(),kP=We(),zo=wP("iterator"),Oh=!1,ct,Wo,Yo;[].keys&&(Yo=[].keys(),"next"in Yo?(Wo=Dh(Dh(Yo)),Wo!==Object.prototype&&(ct=Wo)):Oh=!0);var RP=!xP(ct)||IP(function(){var a={};return ct[zo].call(a)!==a});RP?ct={}:kP&&(ct=PP(ct));EP(ct[zo])||AP(ct,zo,function(){return this});Vh.exports={IteratorPrototype:ct,BUGGY_SAFARI_ITERATORS:Oh}});var Ts=m((eV,_h)=>{"use strict";var $P=he(),LP=$P("toStringTag"),Bh={};Bh[LP]="z";_h.exports=String(Bh)==="[object z]"});var xi=m((tV,Nh)=>{"use strict";var MP=Ts(),CP=X(),Is=Jt(),DP=he(),OP=DP("toStringTag"),VP=Object,BP=Is(function(){return arguments}())==="Arguments",_P=function(a,e){try{return a[e]}catch(t){}};Nh.exports=MP?Is:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=_P(e=VP(a),OP))=="string"?t:BP?Is(e):(r=Is(e))==="Object"&&CP(e.callee)?"Arguments":r}});var qh=m((rV,Fh)=>{"use strict";var NP=Ts(),FP=xi();Fh.exports=NP?{}.toString:function(){return"[object "+FP(this)+"]"}});var Pi=m((iV,Hh)=>{"use strict";var qP=Ts(),UP=er().f,HP=Mr(),jP=Ye(),GP=qh(),QP=he(),Uh=QP("toStringTag");Hh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(jP(i,Uh)||UP(i,Uh,{configurable:!0,value:e}),r&&!qP&&HP(i,"toString",GP))}});var Gh=m((aV,jh)=>{"use strict";var WP=Ko().IteratorPrototype,YP=Qo(),zP=fi(),KP=Pi(),JP=tr(),XP=function(){return this};jh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=YP(WP,{next:zP(+!r,t)}),KP(a,i,!1,!0),JP[i]=XP,a}});var Wh=m((sV,Qh)=>{"use strict";var ZP=se(),eA=tt();Qh.exports=function(a,e,t){try{return ZP(eA(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var zh=m((nV,Yh)=>{"use strict";var tA=$e();Yh.exports=function(a){return tA(a)||a===null}});var Jh=m((oV,Kh)=>{"use strict";var rA=zh(),iA=String,aA=TypeError;Kh.exports=function(a){if(rA(a))return a;throw new aA("Can't set "+iA(a)+" as a prototype")}});var Jo=m((uV,Xh)=>{"use strict";var sA=Wh(),nA=$e(),oA=Rt(),uA=Jh();Xh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=sA(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return oA(i),uA(s),nA(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var cf=m((lV,lf)=>{"use strict";var lA=te(),cA=Re(),Es=We(),of=qo(),dA=X(),pA=Gh(),Zh=ms(),ef=Jo(),hA=Pi(),fA=Mr(),Xo=Br(),mA=he(),tf=tr(),uf=Ko(),bA=of.PROPER,gA=of.CONFIGURABLE,rf=uf.IteratorPrototype,xs=uf.BUGGY_SAFARI_ITERATORS,Ai=mA("iterator"),af="keys",wi="values",sf="entries",nf=function(){return this};lf.exports=function(a,e,t,r,i,s,n){pA(t,e,r);var o=function(S){if(S===i&&p)return p;if(!xs&&S&&S in d)return d[S];switch(S){case af:return function(){return new t(this,S)};case wi:return function(){return new t(this,S)};case sf:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[Ai]||d["@@iterator"]||i&&d[i],p=!xs&&c||o(i),h=e==="Array"&&d.entries||c,f,b,g;if(h&&(f=Zh(h.call(new a)),f!==Object.prototype&&f.next&&(!Es&&Zh(f)!==rf&&(ef?ef(f,rf):dA(f[Ai])||Xo(f,Ai,nf)),hA(f,u,!0,!0),Es&&(tf[u]=nf))),bA&&i===wi&&c&&c.name!==wi&&(!Es&&gA?fA(d,"name",wi):(l=!0,p=function(){return cA(c,this)})),i)if(b={values:o(wi),keys:s?p:o(af),entries:o(sf)},n)for(g in b)(xs||l||!(g in d))&&Xo(d,g,b[g]);else lA({target:e,proto:!0,forced:xs||l},b);return(!Es||n)&&d[Ai]!==p&&Xo(d,Ai,p,{name:i}),tf[e]=p,b}});var pf=m((cV,df)=>{"use strict";df.exports=function(a,e){return{value:a,done:e}}});var eu=m((dV,gf)=>{"use strict";var vA=Xt(),Zo=Ii(),hf=tr(),mf=_o(),SA=er().f,yA=cf(),Ps=pf(),TA=We(),IA=ke(),bf="Array Iterator",EA=mf.set,xA=mf.getterFor(bf);gf.exports=yA(Array,"Array",function(a,e){EA(this,{type:bf,target:vA(a),index:0,kind:e})},function(){var a=xA(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ps(void 0,!0);switch(a.kind){case"keys":return Ps(t,!1);case"values":return Ps(e[t],!1)}return Ps([t,e[t]],!1)},"values");var ff=hf.Arguments=hf.Array;Zo("keys");Zo("values");Zo("entries");if(!TA&&IA&&ff.name!=="values")try{SA(ff,"name",{value:"values"})}catch(a){}});var Sf=m((pV,vf)=>{"use strict";var PA=he(),AA=tr(),wA=PA("iterator"),kA=Array.prototype;vf.exports=function(a){return a!==void 0&&(AA.Array===a||kA[wA]===a)}});var tu=m((hV,Tf)=>{"use strict";var RA=xi(),yf=gi(),$A=wr(),LA=tr(),MA=he(),CA=MA("iterator");Tf.exports=function(a){if(!$A(a))return yf(a,CA)||yf(a,"@@iterator")||LA[RA(a)]}});var Ef=m((fV,If)=>{"use strict";var DA=Re(),OA=tt(),VA=rt(),BA=bi(),_A=tu(),NA=TypeError;If.exports=function(a,e){var t=arguments.length<2?_A(a):e;if(OA(t))return VA(DA(t,a));throw new NA(BA(a)+" is not iterable")}});var Af=m((mV,Pf)=>{"use strict";var FA=Re(),xf=rt(),qA=gi();Pf.exports=function(a,e,t){var r,i;xf(a);try{if(r=qA(a,"return"),!r){if(e==="throw")throw t;return t}r=FA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return xf(r),t}});var ws=m((bV,$f)=>{"use strict";var UA=Lr(),HA=Re(),jA=rt(),GA=bi(),QA=Sf(),WA=Or(),wf=mi(),YA=Ef(),zA=tu(),kf=Af(),KA=TypeError,As=function(a,e){this.stopped=a,this.result=e},Rf=As.prototype;$f.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=UA(e,r),l,d,c,p,h,f,b,g=function(v){return l&&kf(l,"normal",v),new As(!0,v)},S=function(v){return i?(jA(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(s)l=a.iterator;else if(n)l=a;else{if(d=zA(a),!d)throw new KA(GA(a)+" is not iterable");if(QA(d)){for(c=0,p=WA(a);p>c;c++)if(h=S(a[c]),h&&wf(Rf,h))return h;return new As(!1)}l=YA(a,d)}for(f=s?a.next:l.next;!(b=HA(f,l)).done;){try{h=S(b.value)}catch(v){kf(l,"throw",v)}if(typeof h=="object"&&h&&wf(Rf,h))return h}return new As(!1)}});var Mf=m((gV,Lf)=>{"use strict";var JA=ke(),XA=er(),ZA=fi();Lf.exports=function(a,e,t){JA?XA.f(a,e,ZA(0,t)):a[e]=t}});var Cf=m(()=>{"use strict";var ew=te(),tw=ws(),rw=Mf();ew({target:"Object",stat:!0},{fromEntries:function(e){var t={};return tw(e,function(r,i){rw(t,r,i)},{AS_ENTRIES:!0}),t}})});var Of=m((yV,Df)=>{"use strict";eu();Cf();var iw=kr();Df.exports=iw.Object.fromEntries});var Bf=m((TV,Vf)=>{"use strict";Vf.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 Nf=m(()=>{"use strict";eu();var aw=Bf(),sw=Z(),nw=Pi(),_f=tr();for(ks in aw)nw(sw[ks],ks),_f[ks]=_f.Array;var ks});var qf=m((xV,Ff)=>{"use strict";var ow=Of();Nf();Ff.exports=ow});var ru=m((PV,Uf)=>{"use strict";var uw=qf();Uf.exports=uw});var Hf=m(()=>{"use strict"});var iu=m((kV,jf)=>{"use strict";var ki=Z(),lw=Zt(),cw=Jt(),Rs=function(a){return lw.slice(0,a.length)===a};jf.exports=function(){return Rs("Bun/")?"BUN":Rs("Cloudflare-Workers")?"CLOUDFLARE":Rs("Deno/")?"DENO":Rs("Node.js/")?"NODE":ki.Bun&&typeof Bun.version=="string"?"BUN":ki.Deno&&typeof Deno.version=="object"?"DENO":cw(ki.process)==="process"?"NODE":ki.window&&ki.document?"BROWSER":"REST"}()});var $s=m((RV,Gf)=>{"use strict";var dw=iu();Gf.exports=dw==="NODE"});var Wf=m(($V,Qf)=>{"use strict";var pw=er();Qf.exports=function(a,e,t){return pw.f(a,e,t)}});var Kf=m((LV,zf)=>{"use strict";var hw=lt(),fw=Wf(),mw=he(),bw=ke(),Yf=mw("species");zf.exports=function(a){var e=hw(a);bw&&e&&!e[Yf]&&fw(e,Yf,{configurable:!0,get:function(){return this}})}});var Xf=m((MV,Jf)=>{"use strict";var gw=mi(),vw=TypeError;Jf.exports=function(a,e){if(gw(e,a))return a;throw new vw("Incorrect invocation")}});var su=m((CV,Zf)=>{"use strict";var Sw=se(),yw=X(),au=vi(),Tw=Sw(Function.toString);yw(au.inspectSource)||(au.inspectSource=function(a){return Tw(a)});Zf.exports=au.inspectSource});var ou=m((DV,am)=>{"use strict";var Iw=se(),Ew=pe(),em=X(),xw=xi(),Pw=lt(),Aw=su(),tm=function(){},rm=Pw("Reflect","construct"),nu=/^\s*(?:class|function)\b/,ww=Iw(nu.exec),kw=!nu.test(tm),Ri=function(e){if(!em(e))return!1;try{return rm(tm,[],e),!0}catch(t){return!1}},im=function(e){if(!em(e))return!1;switch(xw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return kw||!!ww(nu,Aw(e))}catch(t){return!0}};im.sham=!0;am.exports=!rm||Ew(function(){var a;return Ri(Ri.call)||!Ri(Object)||!Ri(function(){a=!0})||a})?im:Ri});var nm=m((OV,sm)=>{"use strict";var Rw=ou(),$w=bi(),Lw=TypeError;sm.exports=function(a){if(Rw(a))return a;throw new Lw($w(a)+" is not a constructor")}});var uu=m((VV,um)=>{"use strict";var om=rt(),Mw=nm(),Cw=wr(),Dw=he(),Ow=Dw("species");um.exports=function(a,e){var t=om(a).constructor,r;return t===void 0||Cw(r=om(t)[Ow])?e:Mw(r)}});var cm=m((BV,lm)=>{"use strict";var Vw=se();lm.exports=Vw([].slice)});var pm=m((_V,dm)=>{"use strict";var Bw=TypeError;dm.exports=function(a,e){if(a<e)throw new Bw("Not enough arguments");return a}});var lu=m((NV,hm)=>{"use strict";var _w=Zt();hm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(_w)});var vu=m((FV,Im)=>{"use strict";var Le=Z(),Nw=Jn(),Fw=Lr(),fm=X(),qw=Ye(),Tm=pe(),mm=Uo(),Uw=cm(),bm=cs(),Hw=pm(),jw=lu(),Gw=$s(),mu=Le.setImmediate,bu=Le.clearImmediate,Qw=Le.process,cu=Le.Dispatch,Ww=Le.Function,gm=Le.MessageChannel,Yw=Le.String,du=0,$i={},vm="onreadystatechange",Li,ir,pu,hu;Tm(function(){Li=Le.location});var gu=function(a){if(qw($i,a)){var e=$i[a];delete $i[a],e()}},fu=function(a){return function(){gu(a)}},Sm=function(a){gu(a.data)},ym=function(a){Le.postMessage(Yw(a),Li.protocol+"//"+Li.host)};(!mu||!bu)&&(mu=function(e){Hw(arguments.length,1);var t=fm(e)?e:Ww(e),r=Uw(arguments,1);return $i[++du]=function(){Nw(t,void 0,r)},ir(du),du},bu=function(e){delete $i[e]},Gw?ir=function(a){Qw.nextTick(fu(a))}:cu&&cu.now?ir=function(a){cu.now(fu(a))}:gm&&!jw?(pu=new gm,hu=pu.port2,pu.port1.onmessage=Sm,ir=Fw(hu.postMessage,hu)):Le.addEventListener&&fm(Le.postMessage)&&!Le.importScripts&&Li&&Li.protocol!=="file:"&&!Tm(ym)?(ir=ym,Le.addEventListener("message",Sm,!1)):vm in bm("script")?ir=function(a){mm.appendChild(bm("script"))[vm]=function(){mm.removeChild(this),gu(a)}}:ir=function(a){setTimeout(fu(a),0)});Im.exports={set:mu,clear:bu}});var Pm=m((qV,xm)=>{"use strict";var Em=Z(),zw=ke(),Kw=Object.getOwnPropertyDescriptor;xm.exports=function(a){if(!zw)return Em[a];var e=Kw(Em,a);return e&&e.value}});var Su=m((UV,wm)=>{"use strict";var Am=function(){this.head=null,this.tail=null};Am.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}}};wm.exports=Am});var Rm=m((HV,km)=>{"use strict";var Jw=Zt();km.exports=/ipad|iphone|ipod/i.test(Jw)&&typeof Pebble!="undefined"});var Lm=m((jV,$m)=>{"use strict";var Xw=Zt();$m.exports=/web0s(?!.*chrome)/i.test(Xw)});var _m=m((GV,Bm)=>{"use strict";var Nr=Z(),Zw=Pm(),Mm=Lr(),yu=vu().set,ek=Su(),tk=lu(),rk=Rm(),ik=Lm(),Tu=$s(),Cm=Nr.MutationObserver||Nr.WebKitMutationObserver,Dm=Nr.document,Om=Nr.process,Ls=Nr.Promise,xu=Zw("queueMicrotask"),_r,Iu,Eu,Ms,Vm;xu||(Mi=new ek,Ci=function(){var a,e;for(Tu&&(a=Om.domain)&&a.exit();e=Mi.get();)try{e()}catch(t){throw Mi.head&&_r(),t}a&&a.enter()},!tk&&!Tu&&!ik&&Cm&&Dm?(Iu=!0,Eu=Dm.createTextNode(""),new Cm(Ci).observe(Eu,{characterData:!0}),_r=function(){Eu.data=Iu=!Iu}):!rk&&Ls&&Ls.resolve?(Ms=Ls.resolve(void 0),Ms.constructor=Ls,Vm=Mm(Ms.then,Ms),_r=function(){Vm(Ci)}):Tu?_r=function(){Om.nextTick(Ci)}:(yu=Mm(yu,Nr),_r=function(){yu(Ci)}),xu=function(a){Mi.head||_r(),Mi.add(a)});var Mi,Ci;Bm.exports=xu});var Fm=m((QV,Nm)=>{"use strict";Nm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Cs=m((WV,qm)=>{"use strict";qm.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ar=m((YV,Um)=>{"use strict";var ak=Z();Um.exports=ak.Promise});var Fr=m((zV,Qm)=>{"use strict";var sk=Z(),Di=ar(),nk=X(),ok=yo(),uk=su(),lk=he(),Hm=iu(),ck=We(),Pu=no(),jm=Di&&Di.prototype,dk=lk("species"),Au=!1,Gm=nk(sk.PromiseRejectionEvent),pk=ok("Promise",function(){var a=uk(Di),e=a!==String(Di);if(!e&&Pu===66||ck&&!(jm.catch&&jm.finally))return!0;if(!Pu||Pu<51||!/native code/.test(a)){var t=new Di(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[dk]=r,Au=t.then(function(){})instanceof r,!Au)return!0}return!e&&(Hm==="BROWSER"||Hm==="DENO")&&!Gm});Qm.exports={CONSTRUCTOR:pk,REJECTION_EVENT:Gm,SUBCLASSING:Au}});var qr=m((KV,Ym)=>{"use strict";var Wm=tt(),hk=TypeError,fk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new hk("Bad Promise constructor");e=r,t=i}),this.resolve=Wm(e),this.reject=Wm(t)};Ym.exports.f=function(a){return new fk(a)}});var hb=m(()=>{"use strict";var mk=te(),bk=We(),Bs=$s(),Lt=Z(),Gr=Re(),zm=Br(),Km=Jo(),gk=Pi(),vk=Kf(),Sk=tt(),Vs=X(),yk=$e(),Tk=Xf(),Ik=uu(),tb=vu().set,Lu=_m(),Ek=Fm(),xk=Cs(),Pk=Su(),rb=_o(),_s=ar(),Mu=Fr(),ib=qr(),Ns="Promise",ab=Mu.CONSTRUCTOR,Ak=Mu.REJECTION_EVENT,wk=Mu.SUBCLASSING,wu=rb.getterFor(Ns),kk=rb.set,Ur=_s&&_s.prototype,sr=_s,Ds=Ur,sb=Lt.TypeError,ku=Lt.document,Cu=Lt.process,Ru=ib.f,Rk=Ru,$k=!!(ku&&ku.createEvent&&Lt.dispatchEvent),nb="unhandledrejection",Lk="rejectionhandled",Jm=0,ob=1,Mk=2,Du=1,ub=2,Os,Xm,Ck,Zm,lb=function(a){var e;return yk(a)&&Vs(e=a.then)?e:!1},cb=function(a,e){var t=e.value,r=e.state===ob,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{i?(r||(e.rejection===ub&&Ok(e),e.rejection=Du),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),d=!0)),u===a.promise?n(new sb("Promise-chain cycle")):(l=lb(u))?Gr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},db=function(a,e){a.notified||(a.notified=!0,Lu(function(){for(var t=a.reactions,r;r=t.get();)cb(r,a);a.notified=!1,e&&!a.rejection&&Dk(a)}))},pb=function(a,e,t){var r,i;$k?(r=ku.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Lt.dispatchEvent(r)):r={promise:e,reason:t},!Ak&&(i=Lt["on"+a])?i(r):a===nb&&Ek("Unhandled promise rejection",t)},Dk=function(a){Gr(tb,Lt,function(){var e=a.facade,t=a.value,r=eb(a),i;if(r&&(i=xk(function(){Bs?Cu.emit("unhandledRejection",t,e):pb(nb,e,t)}),a.rejection=Bs||eb(a)?ub:Du,i.error))throw i.value})},eb=function(a){return a.rejection!==Du&&!a.parent},Ok=function(a){Gr(tb,Lt,function(){var e=a.facade;Bs?Cu.emit("rejectionHandled",e):pb(Lk,e,a.value)})},Hr=function(a,e,t){return function(r){a(e,r,t)}},jr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Mk,db(a,!0))},$u=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new sb("Promise can't be resolved itself");var r=lb(e);r?Lu(function(){var i={done:!1};try{Gr(r,e,Hr($u,i,a),Hr(jr,i,a))}catch(s){jr(i,s,a)}}):(a.value=e,a.state=ob,db(a,!1))}catch(i){jr({done:!1},i,a)}}};if(ab&&(sr=function(e){Tk(this,Ds),Sk(e),Gr(Os,this);var t=wu(this);try{e(Hr($u,t),Hr(jr,t))}catch(r){jr(t,r)}},Ds=sr.prototype,Os=function(e){kk(this,{type:Ns,done:!1,notified:!1,parent:!1,reactions:new Pk,rejection:!1,state:Jm,value:void 0})},Os.prototype=zm(Ds,"then",function(e,t){var r=wu(this),i=Ru(Ik(this,sr));return r.parent=!0,i.ok=Vs(e)?e:!0,i.fail=Vs(t)&&t,i.domain=Bs?Cu.domain:void 0,r.state===Jm?r.reactions.add(i):Lu(function(){cb(i,r)}),i.promise}),Xm=function(){var a=new Os,e=wu(a);this.promise=a,this.resolve=Hr($u,e),this.reject=Hr(jr,e)},ib.f=Ru=function(a){return a===sr||a===Ck?new Xm(a):Rk(a)},!bk&&Vs(_s)&&Ur!==Object.prototype)){Zm=Ur.then,wk||zm(Ur,"then",function(e,t){var r=this;return new sr(function(i,s){Gr(Zm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Ur.constructor}catch(a){}Km&&Km(Ur,Ds)}mk({global:!0,constructor:!0,wrap:!0,forced:ab},{Promise:sr});gk(sr,Ns,!1,!0);vk(Ns)});var vb=m((ZV,gb)=>{"use strict";var Vk=he(),mb=Vk("iterator"),bb=!1;try{fb=0,Ou={next:function(){return{done:!!fb++}},return:function(){bb=!0}},Ou[mb]=function(){return this},Array.from(Ou,function(){throw 2})}catch(a){}var fb,Ou;gb.exports=function(a,e){try{if(!e&&!bb)return!1}catch(i){return!1}var t=!1;try{var r={};r[mb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Vu=m((eB,Sb)=>{"use strict";var Bk=ar(),_k=vb(),Nk=Fr().CONSTRUCTOR;Sb.exports=Nk||!_k(function(a){Bk.all(a).then(void 0,function(){})})});var yb=m(()=>{"use strict";var Fk=te(),qk=Re(),Uk=tt(),Hk=qr(),jk=Cs(),Gk=ws(),Qk=Vu();Fk({target:"Promise",stat:!0,forced:Qk},{all:function(e){var t=this,r=Hk.f(t),i=r.resolve,s=r.reject,n=jk(function(){var o=Uk(t.resolve),u=[],l=0,d=1;Gk(e,function(c){var p=l++,h=!1;d++,qk(o,t,c).then(function(f){h||(h=!0,u[p]=f,--d||i(u))},s)}),--d||i(u)});return n.error&&s(n.value),r.promise}})});var Ib=m(()=>{"use strict";var Wk=te(),Yk=We(),zk=Fr().CONSTRUCTOR,_u=ar(),Kk=lt(),Jk=X(),Xk=Br(),Tb=_u&&_u.prototype;Wk({target:"Promise",proto:!0,forced:zk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Yk&&Jk(_u)&&(Bu=Kk("Promise").prototype.catch,Tb.catch!==Bu&&Xk(Tb,"catch",Bu,{unsafe:!0}));var Bu});var Eb=m(()=>{"use strict";var Zk=te(),eR=Re(),tR=tt(),rR=qr(),iR=Cs(),aR=ws(),sR=Vu();Zk({target:"Promise",stat:!0,forced:sR},{race:function(e){var t=this,r=rR.f(t),i=r.reject,s=iR(function(){var n=tR(t.resolve);aR(e,function(o){eR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var xb=m(()=>{"use strict";var nR=te(),oR=qr(),uR=Fr().CONSTRUCTOR;nR({target:"Promise",stat:!0,forced:uR},{reject:function(e){var t=oR.f(this),r=t.reject;return r(e),t.promise}})});var Nu=m((lB,Pb)=>{"use strict";var lR=rt(),cR=$e(),dR=qr();Pb.exports=function(a,e){if(lR(a),cR(e)&&e.constructor===a)return e;var t=dR.f(a),r=t.resolve;return r(e),t.promise}});var kb=m(()=>{"use strict";var pR=te(),hR=lt(),Ab=We(),fR=ar(),wb=Fr().CONSTRUCTOR,mR=Nu(),bR=hR("Promise"),gR=Ab&&!wb;pR({target:"Promise",stat:!0,forced:Ab||wb},{resolve:function(e){return mR(gR&&this===bR?fR:this,e)}})});var Rb=m(()=>{"use strict";hb();yb();Ib();Eb();xb();kb()});var Cb=m(()=>{"use strict";var vR=te(),SR=We(),Fs=ar(),yR=pe(),Lb=lt(),Mb=X(),TR=uu(),$b=Nu(),IR=Br(),qu=Fs&&Fs.prototype,ER=!!Fs&&yR(function(){qu.finally.call({then:function(){}},function(){})});vR({target:"Promise",proto:!0,real:!0,forced:ER},{finally:function(a){var e=TR(this,Lb("Promise")),t=Mb(a);return this.then(t?function(r){return $b(e,a()).then(function(){return r})}:a,t?function(r){return $b(e,a()).then(function(){throw r})}:a)}});!SR&&Mb(Fs)&&(Fu=Lb("Promise").prototype.finally,qu.finally!==Fu&&IR(qu,"finally",Fu,{unsafe:!0}));var Fu});var Ob=m((bB,Db)=>{"use strict";Hf();Rb();Cb();var xR=$t();Db.exports=xR("Promise","finally")});var Bb=m((gB,Vb)=>{"use strict";var PR=Ob();Vb.exports=PR});var qs=m((vB,_b)=>{"use strict";var AR=Bb();_b.exports=AR});var Jb=m(()=>{"use strict";var FR=te(),qR=Do().values;FR({target:"Object",stat:!0},{values:function(e){return qR(e)}})});var Zb=m((r_,Xb)=>{"use strict";Jb();var UR=kr();Xb.exports=UR.Object.values});var tg=m((i_,eg)=>{"use strict";var HR=Zb();eg.exports=HR});var Vi=m((a_,rg)=>{"use strict";var jR=tg();rg.exports=jR});var mg=m(()=>{"use strict";var n$=te(),o$=Rr(),u$=Or(),l$=Ti(),c$=Ii();n$({target:"Array",proto:!0},{at:function(e){var t=o$(this),r=u$(t),i=l$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});c$("at")});var gg=m((M_,bg)=>{"use strict";mg();var d$=$t();bg.exports=d$("Array","at")});var Sg=m((C_,vg)=>{"use strict";var p$=gg();vg.exports=p$});var Yr=m((D_,yg)=>{"use strict";var h$=Sg();yg.exports=h$});var cl=m((lF,Kg)=>{"use strict";var Y$=Jt();Kg.exports=Array.isArray||function(e){return Y$(e)==="Array"}});var Xg=m((cF,Jg)=>{"use strict";var z$=TypeError,K$=9007199254740991;Jg.exports=function(a){if(a>K$)throw z$("Maximum allowed index exceeded");return a}});var tv=m((dF,ev)=>{"use strict";var J$=cl(),X$=Or(),Z$=Xg(),eL=Lr(),Zg=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,d=n?eL(n,o):!1,c,p;l<r;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&J$(c)?(p=X$(c),u=Zg(a,e,c,p,u,s-1)-1):(Z$(u+1),a[u]=c),u++),l++;return u};ev.exports=Zg});var sv=m((pF,av)=>{"use strict";var rv=cl(),tL=ou(),rL=$e(),iL=he(),aL=iL("species"),iv=Array;av.exports=function(a){var e;return rv(a)&&(e=a.constructor,tL(e)&&(e===iv||rv(e.prototype))?e=void 0:rL(e)&&(e=e[aL],e===null&&(e=void 0))),e===void 0?iv:e}});var ov=m((hF,nv)=>{"use strict";var sL=sv();nv.exports=function(a,e){return new(sL(a))(e===0?0:e)}});var uv=m(()=>{"use strict";var nL=te(),oL=tv(),uL=tt(),lL=Rr(),cL=Or(),dL=ov();nL({target:"Array",proto:!0},{flatMap:function(e){var t=lL(this),r=cL(t),i;return uL(e),i=dL(t,0),i.length=oL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var lv=m(()=>{"use strict";var pL=Ii();pL("flatMap")});var dv=m((vF,cv)=>{"use strict";uv();lv();var hL=$t();cv.exports=hL("Array","flatMap")});var hv=m((SF,pv)=>{"use strict";var fL=dv();pv.exports=fL});var dl=m((yF,fv)=>{"use strict";var mL=hv();fv.exports=mL});var Ki=m((LF,Dv)=>{"use strict";var EL=xi(),xL=String;Dv.exports=function(a){if(EL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return xL(a)}});var hl=m((MF,Ov)=>{"use strict";Ov.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 _v=m((CF,Bv)=>{"use strict";var PL=se(),AL=Rt(),wL=Ki(),ml=hl(),Vv=PL("".replace),kL=RegExp("^["+ml+"]+"),RL=RegExp("(^|[^"+ml+"])["+ml+"]+$"),fl=function(a){return function(e){var t=wL(AL(e));return a&1&&(t=Vv(t,kL,"")),a&2&&(t=Vv(t,RL,"$1")),t}};Bv.exports={start:fl(1),end:fl(2),trim:fl(3)}});var Uv=m((DF,qv)=>{"use strict";var $L=qo().PROPER,LL=pe(),Nv=hl(),Fv="\u200B\x85\u180E";qv.exports=function(a){return LL(function(){return!!Nv[a]()||Fv[a]()!==Fv||$L&&Nv[a].name!==a})}});var bl=m((OF,Hv)=>{"use strict";var ML=_v().start,CL=Uv();Hv.exports=CL("trimStart")?function(){return ML(this)}:"".trimStart});var Gv=m(()=>{"use strict";var DL=te(),jv=bl();DL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==jv},{trimLeft:jv})});var Wv=m(()=>{"use strict";Gv();var OL=te(),Qv=bl();OL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Qv},{trimStart:Qv})});var zv=m((FF,Yv)=>{"use strict";Wv();var VL=$t();Yv.exports=VL("String","trimLeft")});var Jv=m((qF,Kv)=>{"use strict";var BL=zv();Kv.exports=BL});var Zv=m((UF,Xv)=>{"use strict";var _L=Jv();Xv.exports=_L});var mS=m(()=>{"use strict"});var bS=m(()=>{"use strict"});var vS=m((m1,gS)=>{"use strict";var oM=$e(),uM=Jt(),lM=he(),cM=lM("match");gS.exports=function(a){var e;return oM(a)&&((e=a[cM])!==void 0?!!e:uM(a)==="RegExp")}});var yS=m((b1,SS)=>{"use strict";var dM=rt();SS.exports=function(){var a=dM(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 ES=m((g1,IS)=>{"use strict";var pM=Re(),hM=Ye(),fM=mi(),mM=yS(),TS=RegExp.prototype;IS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in TS)&&!hM(a,"flags")&&fM(TS,a)?pM(mM,a):e}});var PS=m((v1,xS)=>{"use strict";var Pl=se(),bM=Rr(),gM=Math.floor,El=Pl("".charAt),vM=Pl("".replace),xl=Pl("".slice),SM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,yM=/\$([$&'`]|\d{1,2})/g;xS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=yM;return i!==void 0&&(i=bM(i),u=SM),vM(s,u,function(l,d){var c;switch(El(d,0)){case"$":return"$";case"&":return a;case"`":return xl(e,0,t);case"'":return xl(e,n);case"<":c=i[xl(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=gM(p/10);return h===0?l:h<=o?r[h-1]===void 0?El(d,1):r[h-1]+El(d,1):l}c=r[p-1]}return c===void 0?"":c})}});var kS=m(()=>{"use strict";var TM=te(),IM=Re(),wl=se(),AS=Rt(),EM=X(),xM=wr(),PM=vS(),ei=Ki(),AM=gi(),wM=ES(),kM=PS(),RM=he(),$M=We(),LM=RM("replace"),MM=TypeError,Al=wl("".indexOf),CM=wl("".replace),wS=wl("".slice),DM=Math.max;TM({target:"String",proto:!0},{replaceAll:function(e,t){var r=AS(this),i,s,n,o,u,l,d,c,p,h,f=0,b="";if(!xM(e)){if(i=PM(e),i&&(s=ei(AS(wM(e))),!~Al(s,"g")))throw new MM("`.replaceAll` does not allow non-global regexes");if(n=AM(e,LM),n)return IM(n,e,r,t);if($M&&i)return CM(ei(r),e,t)}for(o=ei(r),u=ei(e),l=EM(t),l||(t=ei(t)),d=u.length,c=DM(1,d),p=Al(o,u);p!==-1;)h=l?ei(t(u,p,o)):kM(u,o,p,[],void 0,t),b+=wS(o,f,p)+h,f=p+d,p=p+c>o.length?-1:Al(o,u,p+c);return f<o.length&&(b+=wS(o,f)),b}})});var $S=m((T1,RS)=>{"use strict";mS();bS();kS();var OM=$t();RS.exports=OM("String","replaceAll")});var MS=m((I1,LS)=>{"use strict";var VM=$S();LS.exports=VM});var DS=m((E1,CS)=>{"use strict";var BM=MS();CS.exports=BM});var VS=m((x1,OS)=>{"use strict";var _M=Ti(),NM=Ki(),FM=Rt(),qM=RangeError;OS.exports=function(e){var t=NM(FM(this)),r="",i=_M(e);if(i<0||i===1/0)throw new qM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var qS=m((P1,FS)=>{"use strict";var NS=se(),UM=Ao(),BS=Ki(),HM=VS(),jM=Rt(),GM=NS(HM),QM=NS("".slice),WM=Math.ceil,_S=function(a){return function(e,t,r){var i=BS(jM(e)),s=UM(t),n=i.length,o=r===void 0?" ":BS(r),u,l;return s<=n||o===""?i:(u=s-n,l=GM(o,WM(u/o.length)),l.length>u&&(l=QM(l,0,u)),a?i+l:l+i)}};FS.exports={start:_S(!1),end:_S(!0)}});var HS=m((A1,US)=>{"use strict";var YM=Zt();US.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(YM)});var jS=m(()=>{"use strict";var zM=te(),KM=qS().start,JM=HS();zM({target:"String",proto:!0,forced:JM},{padStart:function(e){return KM(this,e,arguments.length>1?arguments[1]:void 0)}})});var QS=m((R1,GS)=>{"use strict";jS();var XM=$t();GS.exports=XM("String","padStart")});var YS=m(($1,WS)=>{"use strict";var ZM=QS();WS.exports=ZM});var KS=m((L1,zS)=>{"use strict";var eC=YS();zS.exports=eC});var Qc="2.0.122";var Se=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Se||{}),kt=(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))(kt||{});var os=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(os||{}),Yn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Yn||{});var zn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(zn||{});var AT=F(it(),1);import{assertNever as jp,assertNonNullable as hx,isNonNullable as ps,ValueSubject as ko,Subject as fx,Subscription as mx,merge as bx,observableFrom as gx,fromEvent as Fp,map as qp,tap as Up,filterChanged as vx,isNullable as Ro,ErrorCategory as Hp}from"@vkontakte/videoplayer-shared/es2015";var Np=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var hs=class{constructor(e){this.connection$=new ko(void 0);this.castState$=new ko("NOT_AVAILABLE");this.errorEvent$=new fx;this.realCastState$=new ko("NOT_AVAILABLE");this.subscription=new mx;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=ps((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Np("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Hp.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ps(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ro(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ro(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Fp(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return jp(i.sessionState)}})).add(bx(Fp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Up(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),qp(i=>i.castState)),gx([r.getCastState()])).pipe(vx(),qp(Sx),Up(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=ps(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();hx(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Ro(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?ps(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Hp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Sx=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 jp(a)}};var ic=F(it(),1),nT=F(Vr(),1),oT=F(ru(),1);var Yb=F(qs(),1);import{assertNever as Nb}from"@vkontakte/videoplayer-shared/es2015";var fe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Nb(t)}return a},Us=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Nb(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as wR,Subject as Hs,merge as Fb}from"@vkontakte/videoplayer-shared/es2015";var C=class{constructor(e){this.transitionStarted$=new Hs;this.transitionEnded$=new Hs;this.transitionUpdated$=new Hs;this.forceChanged$=new Hs;this.stateChangeStarted$=Fb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Fb(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||wR(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as kR}from"@vkontakte/videoplayer-shared/es2015";var qb=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 kR(a)}};import{assertNever as Qr,assertNonNullable as nr,debounce as Ub,ErrorCategory as Hb,fromEvent as or,isNonNullable as jb,map as Gb,merge as Qb,observableFrom as RR,Subject as $R,Subscription as Uu,timeout as LR,getHighestQuality as MR}from"@vkontakte/videoplayer-shared/es2015";var CR=5,DR=5,OR=500,Wb=7e3,Oi=class{constructor(e){this.subscription=new Uu;this.loadMediaTimeoutSubscription=new Uu;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Qr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Qr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Qr(e)}break}default:Qr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(qb(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new Uu;this.subscription.add(e),this.subscription.add(Qb(this.videoState.stateChangeStarted$.pipe(Gb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Gb(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new $R;e.add(i.pipe(Ub(OR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(or(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)>CR)&&i.next(o),s=o})),e.add(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<DR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Qr(n)}}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Qb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,RR(["init"])).pipe(Ub(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let d=t[e];nr(d);let c=MR(Object.keys(d));nr(c);let p=d[c];nr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];nr(d),r=d.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];nr(d),r=d.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];nr(d),r=d.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];nr(d),r=fe(d.url),i="application/x-mpegurl",s=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:Hb.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Qr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return jb(o)&&(n.metadata.title=o),jb(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(LR(Wb).subscribe(()=>s(`timeout(${Wb})`)))});(0,Yb.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Hb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ul=F(it(),1);import{clearVideoElement as Kb}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as VR}from"@vkontakte/videoplayer-shared/es2015";var zb=a=>{try{a.pause(),a.playbackRate=0,VR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as BR,Subscription as _R}from"@vkontakte/videoplayer-shared/es2015";var Hu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},ju=window.WeakMap?new WeakMap:new Hu,Gu=window.WeakMap?new WeakMap:new Map,NR=(a,e=20)=>{let t=0;return BR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ye=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Kb(t):(t=document.createElement("video"),a.appendChild(t)),ju.set(t,r);let i=new _R;return i.add(NR(t,e)),Gu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Te=a=>{let e=Gu.get(a);e==null||e.unsubscribe(),Gu.delete(a);let t=ju.get(a);ju.delete(a),t?Kb(a):zb(a)};var Wu=F(Vi(),1);import{assertNonNullable as Bi,isNonNullable as st,isNullable as WR,fromEvent as Wr,merge as ig,observableFrom as ag,filterChanged as sg,map as _i,Subject as ng,Subscription as YR,ValueSubject as zR,ErrorCategory as KR}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Qu,isNullable as GR,Subscription as QR}from"@vkontakte/videoplayer-shared/es2015";var js=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=GR(i),l=new QR;return i&&l.add(i.subscribe(d=>{let c=a.getState();r(d,c)&&a.setState(d)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},at=(a,e,t)=>js(e,()=>a.loop,r=>{Qu(r)&&(a.loop=r)},{onError:t}),Ie=(a,e,t,r)=>js(e,()=>({muted:a.muted,volume:a.volume}),i=>{Qu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),_e=(a,e,t,r)=>js(e,()=>a.playbackRate,i=>{Qu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Mt=js;var JR=a=>["__",a.language,a.label].join("|"),XR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Yu=class a{constructor(){this.available$=new ng;this.current$=new zR(void 0);this.error$=new ng;this.subscription=new YR;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:KR.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Mt(t.internalTextTracks,()=>(0,Wu.default)(this.internalTracks),s=>{st(s)&&this.setInternal(s)},{equal:(s,n)=>st(s)&&st(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(_i(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Mt(t.externalTextTracks,()=>(0,Wu.default)(this.externalTracks),s=>{st(s)&&this.setExternal(s)},{equal:(s,n)=>st(s)&&st(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(_i(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Mt(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Mt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Bi(this.video);let{textTracks:e}=this.video;this.subscription.add(Wr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(ig(Wr(e,"addtrack"),Wr(e,"removetrack"),ag(["init"])).pipe(_i(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),sg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(ig(Wr(e,"change"),ag(["init"])).pipe(_i(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),_i(r=>r&&this.htmlTextTrackToITextTrack(r).id),sg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(Wr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,d,c,p,h;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Wr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;st(t.align)&&(i.align=t.align),st(t.position)&&(i.position=t.position),st(t.size)&&(i.size=t.size),st(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Bi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:r}=e,i=e.id?e.id:JR(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(d=this.externalTracks.get(i))==null?void 0:d.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(c=this.internalTracks.get(i))==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(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){Bi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(WR(e)||!XR(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){Bi(this.video);let t=document.createElement("track");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){Bi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ne=Yu;var pt=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 og=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},zu=a=>{let e=og(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ug=a=>{let e=og(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Fe,map as Ct,merge as cg,filterChanged as e$,isNonNullable as dg,Subject as t$,filter as pg,mapTo as hg,combine as r$,once as i$,ErrorCategory as a$,ValueSubject as fg,clientChecker as s$}from"@vkontakte/videoplayer-shared/es2015";var ZR=3,lg=(a,e,t=ZR)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Ee=a=>{let e=y=>Fe(a,y).pipe(hg(void 0)),r=cg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Fe(a,y))).pipe(Ct(y=>y.type==="ended"?a.readyState<2:a.readyState<3),e$()),i=cg(Fe(a,"progress"),Fe(a,"timeupdate")).pipe(Ct(()=>lg(a.buffered,a.currentTime))),s=s$.isSafari?r$({play:e("play").pipe(i$()),playing:e("playing")}).pipe(hg(void 0)):e("playing"),n=Fe(a,"volumechange").pipe(Ct(()=>({muted:a.muted,volume:a.volume}))),o=Fe(a,"ratechange").pipe(Ct(()=>a.playbackRate)),u=Fe(a,"error").pipe(pg(()=>!!(a.error||a.played.length)),Ct(()=>{var I;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:a$.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=Fe(a,"timeupdate").pipe(Ct(()=>a.currentTime)),d=new t$,c=.3,p;l.subscribe(y=>{a.loop&&dg(p)&&dg(y)&&p>=a.duration-c&&y<=c&&d.next(p),p=y});let h=e("pause").pipe(pg(()=>!a.error&&p!==a.duration)),f=Fe(a,"enterpictureinpicture"),b=Fe(a,"leavepictureinpicture"),g=new fg(ug(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new fg(zu(a));return Fe(a,"fullscreenchange").pipe(Ct(()=>zu(a))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Fe(a,"durationchange").pipe(Ct(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b}};import{VideoQuality as Dt}from"@vkontakte/videoplayer-shared/es2015";var Ot=a=>{switch(a){case"mobile":return Dt.Q_144P;case"lowest":return Dt.Q_240P;case"low":return Dt.Q_360P;case"sd":case"medium":return Dt.Q_480P;case"hd":case"high":return Dt.Q_720P;case"fullhd":case"full":return Dt.Q_1080P;case"quadhd":case"quad":return Dt.Q_1440P;case"ultrahd":case"ultra":return Dt.Q_2160P}};var Vt=F(Yr(),1),wg=F(it(),1),Gs=F(Vr(),1);import{isNonNullable as ne,isNullable as Ju,now as kg,isHigher as Xu,isHigherOrEqual as Zu,isInvariantQuality as xg,isLower as Pg,isLowerOrEqual as el,videoSizeToQuality as f$,assertNotEmptyArray as Rg,assertNonNullable as m$}from"@vkontakte/videoplayer-shared/es2015";var Ku=!1,ht={},Tg=a=>{Ku=a},Ig=()=>{ht={}},Eg=a=>{a(ht)},Ni=(a,e)=>{var t;Ku&&(ht.meta=(t=ht.meta)!=null?t:{},ht.meta[a]=e)},be=class{constructor(e){this.name=e}next(e){var r,i;if(!Ku)return;ht.series=(r=ht.series)!=null?r:{};let t=(i=ht.series[this.name])!=null?i:[];t.push([Date.now(),e]),ht.series[this.name]=t}};var b$=new be("best_bitrate"),$g=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var tl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Fi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=kg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Lg='Assertion "ABR Tracks is empty array" failed',Qs=(a,e,t,r)=>{var u;let i=[...e].sort(tl(1)),s=[...t].sort(tl(1)),n=s.filter(l=>ne(l.bitrate)&&ne(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Vt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Vt.default)(s,-1);return o&&(0,wg.default)(n,o)?o:n.length?(0,Vt.default)(n,-1):(0,Vt.default)(s,0)},Ag=a=>"quality"in a,Mg=(a,e,t,r)=>{var n;let i=ne((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&ne(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&kg()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Ag(o)?"video":"audio",l=Ag(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var HT=Object.create;var Jn=Object.defineProperty,jT=Object.defineProperties,GT=Object.getOwnPropertyDescriptor,QT=Object.getOwnPropertyDescriptors,WT=Object.getOwnPropertyNames,hs=Object.getOwnPropertySymbols,YT=Object.getPrototypeOf,Xn=Object.prototype.hasOwnProperty,Jc=Object.prototype.propertyIsEnumerable;var zT=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,Kc=(a,e,t)=>e in a?Jn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,x=(a,e)=>{for(var t in e||(e={}))Xn.call(e,t)&&Kc(a,t,e[t]);if(hs)for(var t of hs(e))Jc.call(e,t)&&Kc(a,t,e[t]);return a},M=(a,e)=>jT(a,QT(e));var Xc=(a,e)=>{var t={};for(var r in a)Xn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&hs)for(var r of hs(a))e.indexOf(r)<0&&Jc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var KT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of WT(e))!Xn.call(a,i)&&i!==t&&Jn(a,i,{get:()=>e[i],enumerable:!(r=GT(e,i))||r.enumerable});return a};var _=(a,e,t)=>(t=a!=null?HT(YT(a)):{},KT(e||!a||!a.__esModule?Jn(t,"default",{value:a,enumerable:!0}):t,a));var k=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Zn=function(a,e){this[0]=a,this[1]=e},ae=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Zn,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[zT("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var te=m((ro,ed)=>{"use strict";var yi=function(a){return a&&a.Math===Math&&a};ed.exports=yi(typeof globalThis=="object"&&globalThis)||yi(typeof window=="object"&&window)||yi(typeof self=="object"&&self)||yi(typeof global=="object"&&global)||yi(typeof ro=="object"&&ro)||function(){return this}()||Function("return this")()});var pe=m((yD,td)=>{"use strict";td.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ti=m((TD,rd)=>{"use strict";var JT=pe();rd.exports=!JT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var io=m((ID,nd)=>{"use strict";var XT=Ti(),sd=Function.prototype,id=sd.apply,ad=sd.call;nd.exports=typeof Reflect=="object"&&Reflect.apply||(XT?ad.bind(id):function(){return ad.apply(id,arguments)})});var ne=m((ED,ld)=>{"use strict";var od=Ti(),ud=Function.prototype,ao=ud.call,ZT=od&&ud.bind.bind(ao,ao);ld.exports=od?ZT:function(a){return function(){return ao.apply(a,arguments)}}});var rr=m((xD,dd)=>{"use strict";var cd=ne(),eI=cd({}.toString),tI=cd("".slice);dd.exports=function(a){return tI(eI(a),8,-1)}});var so=m((PD,pd)=>{"use strict";var rI=rr(),iI=ne();pd.exports=function(a){if(rI(a)==="Function")return iI(a)}});var Z=m((wD,hd)=>{"use strict";var no=typeof document=="object"&&document.all;hd.exports=typeof no=="undefined"&&no!==void 0?function(a){return typeof a=="function"||a===no}:function(a){return typeof a=="function"}});var Re=m((AD,fd)=>{"use strict";var aI=pe();fd.exports=!aI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var $e=m((kD,md)=>{"use strict";var sI=Ti(),ms=Function.prototype.call;md.exports=sI?ms.bind(ms):function(){return ms.apply(ms,arguments)}});var oo=m(vd=>{"use strict";var bd={}.propertyIsEnumerable,gd=Object.getOwnPropertyDescriptor,nI=gd&&!bd.call({1:2},1);vd.f=nI?function(e){var t=gd(this,e);return!!t&&t.enumerable}:bd});var Ii=m(($D,Sd)=>{"use strict";Sd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Td=m((LD,yd)=>{"use strict";var oI=ne(),uI=pe(),lI=rr(),uo=Object,cI=oI("".split);yd.exports=uI(function(){return!uo("z").propertyIsEnumerable(0)})?function(a){return lI(a)==="String"?cI(a,""):uo(a)}:uo});var Cr=m((MD,Id)=>{"use strict";Id.exports=function(a){return a==null}});var Mt=m((CD,Ed)=>{"use strict";var dI=Cr(),pI=TypeError;Ed.exports=function(a){if(dI(a))throw new pI("Can't call method on "+a);return a}});var ir=m((DD,xd)=>{"use strict";var hI=Td(),fI=Mt();xd.exports=function(a){return hI(fI(a))}});var Le=m((OD,Pd)=>{"use strict";var mI=Z();Pd.exports=function(a){return typeof a=="object"?a!==null:mI(a)}});var Dr=m((BD,wd)=>{"use strict";wd.exports={}});var dt=m((VD,kd)=>{"use strict";var lo=Dr(),co=te(),bI=Z(),Ad=function(a){return bI(a)?a:void 0};kd.exports=function(a,e){return arguments.length<2?Ad(lo[a])||Ad(co[a]):lo[a]&&lo[a][e]||co[a]&&co[a][e]}});var Ei=m((_D,Rd)=>{"use strict";var gI=ne();Rd.exports=gI({}.isPrototypeOf)});var ar=m((ND,Md)=>{"use strict";var vI=te(),$d=vI.navigator,Ld=$d&&$d.userAgent;Md.exports=Ld?String(Ld):""});var ho=m((FD,_d)=>{"use strict";var Vd=te(),po=ar(),Cd=Vd.process,Dd=Vd.Deno,Od=Cd&&Cd.versions||Dd&&Dd.version,Bd=Od&&Od.v8,Ye,bs;Bd&&(Ye=Bd.split("."),bs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!bs&&po&&(Ye=po.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=po.match(/Chrome\/(\d+)/),Ye&&(bs=+Ye[1])));_d.exports=bs});var fo=m((qD,Fd)=>{"use strict";var Nd=ho(),SI=pe(),yI=te(),TI=yI.String;Fd.exports=!!Object.getOwnPropertySymbols&&!SI(function(){var a=Symbol("symbol detection");return!TI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Nd&&Nd<41})});var mo=m((UD,qd)=>{"use strict";var II=fo();qd.exports=II&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var bo=m((HD,Ud)=>{"use strict";var EI=dt(),xI=Z(),PI=Ei(),wI=mo(),AI=Object;Ud.exports=wI?function(a){return typeof a=="symbol"}:function(a){var e=EI("Symbol");return xI(e)&&PI(e.prototype,AI(a))}});var xi=m((jD,Hd)=>{"use strict";var kI=String;Hd.exports=function(a){try{return kI(a)}catch(e){return"Object"}}});var at=m((GD,jd)=>{"use strict";var RI=Z(),$I=xi(),LI=TypeError;jd.exports=function(a){if(RI(a))return a;throw new LI($I(a)+" is not a function")}});var Pi=m((QD,Gd)=>{"use strict";var MI=at(),CI=Cr();Gd.exports=function(a,e){var t=a[e];return CI(t)?void 0:MI(t)}});var Wd=m((WD,Qd)=>{"use strict";var go=$e(),vo=Z(),So=Le(),DI=TypeError;Qd.exports=function(a,e){var t,r;if(e==="string"&&vo(t=a.toString)&&!So(r=go(t,a))||vo(t=a.valueOf)&&!So(r=go(t,a))||e!=="string"&&vo(t=a.toString)&&!So(r=go(t,a)))return r;throw new DI("Can't convert object to primitive value")}});var ze=m((YD,Yd)=>{"use strict";Yd.exports=!0});var Jd=m((zD,Kd)=>{"use strict";var zd=te(),OI=Object.defineProperty;Kd.exports=function(a,e){try{OI(zd,a,{value:e,configurable:!0,writable:!0})}catch(t){zd[a]=e}return e}});var wi=m((KD,ep)=>{"use strict";var BI=ze(),VI=te(),_I=Jd(),Xd="__core-js_shared__",Zd=ep.exports=VI[Xd]||_I(Xd,{});(Zd.versions||(Zd.versions=[])).push({version:"3.38.0",mode:BI?"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 yo=m((JD,rp)=>{"use strict";var tp=wi();rp.exports=function(a,e){return tp[a]||(tp[a]=e||{})}});var Or=m((XD,ip)=>{"use strict";var NI=Mt(),FI=Object;ip.exports=function(a){return FI(NI(a))}});var Ke=m((ZD,ap)=>{"use strict";var qI=ne(),UI=Or(),HI=qI({}.hasOwnProperty);ap.exports=Object.hasOwn||function(e,t){return HI(UI(e),t)}});var To=m((eO,sp)=>{"use strict";var jI=ne(),GI=0,QI=Math.random(),WI=jI(1 .toString);sp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+WI(++GI+QI,36)}});var he=m((tO,op)=>{"use strict";var YI=te(),zI=yo(),np=Ke(),KI=To(),JI=fo(),XI=mo(),Br=YI.Symbol,Io=zI("wks"),ZI=XI?Br.for||Br:Br&&Br.withoutSetter||KI;op.exports=function(a){return np(Io,a)||(Io[a]=JI&&np(Br,a)?Br[a]:ZI("Symbol."+a)),Io[a]}});var dp=m((rO,cp)=>{"use strict";var eE=$e(),up=Le(),lp=bo(),tE=Pi(),rE=Wd(),iE=he(),aE=TypeError,sE=iE("toPrimitive");cp.exports=function(a,e){if(!up(a)||lp(a))return a;var t=tE(a,sE),r;if(t){if(e===void 0&&(e="default"),r=eE(t,a,e),!up(r)||lp(r))return r;throw new aE("Can't convert object to primitive value")}return e===void 0&&(e="number"),rE(a,e)}});var Eo=m((iO,pp)=>{"use strict";var nE=dp(),oE=bo();pp.exports=function(a){var e=nE(a,"string");return oE(e)?e:e+""}});var gs=m((aO,fp)=>{"use strict";var uE=te(),hp=Le(),xo=uE.document,lE=hp(xo)&&hp(xo.createElement);fp.exports=function(a){return lE?xo.createElement(a):{}}});var Po=m((sO,mp)=>{"use strict";var cE=Re(),dE=pe(),pE=gs();mp.exports=!cE&&!dE(function(){return Object.defineProperty(pE("div"),"a",{get:function(){return 7}}).a!==7})});var vp=m(gp=>{"use strict";var hE=Re(),fE=$e(),mE=oo(),bE=Ii(),gE=ir(),vE=Eo(),SE=Ke(),yE=Po(),bp=Object.getOwnPropertyDescriptor;gp.f=hE?bp:function(e,t){if(e=gE(e),t=vE(t),yE)try{return bp(e,t)}catch(r){}if(SE(e,t))return bE(!fE(mE.f,e,t),e[t])}});var wo=m((oO,Sp)=>{"use strict";var TE=pe(),IE=Z(),EE=/#|\.prototype\./,Ai=function(a,e){var t=PE[xE(a)];return t===AE?!0:t===wE?!1:IE(e)?TE(e):!!e},xE=Ai.normalize=function(a){return String(a).replace(EE,".").toLowerCase()},PE=Ai.data={},wE=Ai.NATIVE="N",AE=Ai.POLYFILL="P";Sp.exports=Ai});var Vr=m((uO,Tp)=>{"use strict";var yp=so(),kE=at(),RE=Ti(),$E=yp(yp.bind);Tp.exports=function(a,e){return kE(a),e===void 0?a:RE?$E(a,e):function(){return a.apply(e,arguments)}}});var Ao=m((lO,Ip)=>{"use strict";var LE=Re(),ME=pe();Ip.exports=LE&&ME(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=m((cO,Ep)=>{"use strict";var CE=Le(),DE=String,OE=TypeError;Ep.exports=function(a){if(CE(a))return a;throw new OE(DE(a)+" is not an object")}});var sr=m(Pp=>{"use strict";var BE=Re(),VE=Po(),_E=Ao(),vs=st(),xp=Eo(),NE=TypeError,ko=Object.defineProperty,FE=Object.getOwnPropertyDescriptor,Ro="enumerable",$o="configurable",Lo="writable";Pp.f=BE?_E?function(e,t,r){if(vs(e),t=xp(t),vs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Lo in r&&!r[Lo]){var i=FE(e,t);i&&i[Lo]&&(e[t]=r.value,r={configurable:$o in r?r[$o]:i[$o],enumerable:Ro in r?r[Ro]:i[Ro],writable:!1})}return ko(e,t,r)}:ko:function(e,t,r){if(vs(e),t=xp(t),vs(r),VE)try{return ko(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new NE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=m((pO,wp)=>{"use strict";var qE=Re(),UE=sr(),HE=Ii();wp.exports=qE?function(a,e,t){return UE.f(a,e,HE(1,t))}:function(a,e,t){return a[e]=t,a}});var ie=m((hO,kp)=>{"use strict";var ki=te(),jE=io(),GE=so(),QE=Z(),WE=vp().f,YE=wo(),Nr=Dr(),zE=Vr(),Fr=_r(),Ap=Ke();wi();var KE=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return jE(a,this,arguments)};return e.prototype=a.prototype,e};kp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ki:i?ki[t]:ki[t]&&ki[t].prototype,o=r?Nr:Nr[t]||Fr(Nr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=YE(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Ap(n,p),f=o[p],c&&(a.dontCallGetSet?(S=WE(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=zE(h,ki):a.wrap&&c?g=KE(h):s&&QE(h)?g=GE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Fr(g,"sham",!0),Fr(o,p,g),s&&(d=t+"Prototype",Ap(Nr,d)||Fr(Nr,d,{}),Fr(Nr[d],p,h),a.real&&u&&(l||!u[p])&&Fr(u,p,h)))}});var $p=m((fO,Rp)=>{"use strict";var JE=Math.ceil,XE=Math.floor;Rp.exports=Math.trunc||function(e){var t=+e;return(t>0?XE:JE)(t)}});var Ri=m((mO,Lp)=>{"use strict";var ZE=$p();Lp.exports=function(a){var e=+a;return e!==e||e===0?0:ZE(e)}});var Cp=m((bO,Mp)=>{"use strict";var ex=Ri(),tx=Math.max,rx=Math.min;Mp.exports=function(a,e){var t=ex(a);return t<0?tx(t+e,0):rx(t,e)}});var Mo=m((gO,Dp)=>{"use strict";var ix=Ri(),ax=Math.min;Dp.exports=function(a){var e=ix(a);return e>0?ax(e,9007199254740991):0}});var qr=m((vO,Op)=>{"use strict";var sx=Mo();Op.exports=function(a){return sx(a.length)}});var Co=m((SO,Vp)=>{"use strict";var nx=ir(),ox=Cp(),ux=qr(),Bp=function(a){return function(e,t,r){var i=nx(e),s=ux(i);if(s===0)return!a&&-1;var n=ox(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Vp.exports={includes:Bp(!0),indexOf:Bp(!1)}});var $i=m((yO,_p)=>{"use strict";_p.exports=function(){}});var Np=m(()=>{"use strict";var lx=ie(),cx=Co().includes,dx=pe(),px=$i(),hx=dx(function(){return!Array(1).includes()});lx({target:"Array",proto:!0,forced:hx},{includes:function(e){return cx(this,e,arguments.length>1?arguments[1]:void 0)}});px("includes")});var Ct=m((EO,Fp)=>{"use strict";var fx=dt();Fp.exports=fx});var Up=m((xO,qp)=>{"use strict";Np();var mx=Ct();qp.exports=mx("Array","includes")});var jp=m((PO,Hp)=>{"use strict";var bx=Up();Hp.exports=bx});var Je=m((wO,Gp)=>{"use strict";var gx=jp();Gp.exports=gx});var Ts=m((_O,Zp)=>{"use strict";var Px=yo(),wx=To(),Xp=Px("keys");Zp.exports=function(a){return Xp[a]||(Xp[a]=wx(a))}});var th=m((NO,eh)=>{"use strict";var Ax=pe();eh.exports=!Ax(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Is=m((FO,ih)=>{"use strict";var kx=Ke(),Rx=Z(),$x=Or(),Lx=Ts(),Mx=th(),rh=Lx("IE_PROTO"),Bo=Object,Cx=Bo.prototype;ih.exports=Mx?Bo.getPrototypeOf:function(a){var e=$x(a);if(kx(e,rh))return e[rh];var t=e.constructor;return Rx(t)&&e instanceof t?t.prototype:e instanceof Bo?Cx:null}});var Es=m((qO,ah)=>{"use strict";ah.exports={}});var oh=m((UO,nh)=>{"use strict";var Dx=ne(),Vo=Ke(),Ox=ir(),Bx=Co().indexOf,Vx=Es(),sh=Dx([].push);nh.exports=function(a,e){var t=Ox(a),r=0,i=[],s;for(s in t)!Vo(Vx,s)&&Vo(t,s)&&sh(i,s);for(;e.length>r;)Vo(t,s=e[r++])&&(~Bx(i,s)||sh(i,s));return i}});var _o=m((HO,uh)=>{"use strict";uh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var No=m((jO,lh)=>{"use strict";var _x=oh(),Nx=_o();lh.exports=Object.keys||function(e){return _x(e,Nx)}});var Fo=m((GO,fh)=>{"use strict";var dh=Re(),Fx=pe(),ph=ne(),qx=Is(),Ux=No(),Hx=ir(),jx=oo().f,hh=ph(jx),Gx=ph([].push),Qx=dh&&Fx(function(){var a=Object.create(null);return a[2]=2,!hh(a,2)}),ch=function(a){return function(e){for(var t=Hx(e),r=Ux(t),i=Qx&&qx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!dh||(i?u in t:hh(t,u)))&&Gx(o,a?[u,t[u]]:t[u]);return o}};fh.exports={entries:ch(!0),values:ch(!1)}});var mh=m(()=>{"use strict";var Wx=ie(),Yx=Fo().entries;Wx({target:"Object",stat:!0},{entries:function(e){return Yx(e)}})});var gh=m((YO,bh)=>{"use strict";mh();var zx=Dr();bh.exports=zx.Object.entries});var Sh=m((zO,vh)=>{"use strict";var Kx=gh();vh.exports=Kx});var Ur=m((KO,yh)=>{"use strict";var Jx=Sh();yh.exports=Jx});var nr=m((JO,Th)=>{"use strict";Th.exports={}});var xh=m((XO,Eh)=>{"use strict";var Xx=te(),Zx=Z(),Ih=Xx.WeakMap;Eh.exports=Zx(Ih)&&/native code/.test(String(Ih))});var jo=m((ZO,Ah)=>{"use strict";var eP=xh(),wh=te(),tP=Le(),rP=_r(),qo=Ke(),Uo=wi(),iP=Ts(),aP=Es(),Ph="Object already initialized",Ho=wh.TypeError,sP=wh.WeakMap,xs,Li,Ps,nP=function(a){return Ps(a)?Li(a):xs(a,{})},oP=function(a){return function(e){var t;if(!tP(e)||(t=Li(e)).type!==a)throw new Ho("Incompatible receiver, "+a+" required");return t}};eP||Uo.state?(Xe=Uo.state||(Uo.state=new sP),Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,xs=function(a,e){if(Xe.has(a))throw new Ho(Ph);return e.facade=a,Xe.set(a,e),e},Li=function(a){return Xe.get(a)||{}},Ps=function(a){return Xe.has(a)}):(or=iP("state"),aP[or]=!0,xs=function(a,e){if(qo(a,or))throw new Ho(Ph);return e.facade=a,rP(a,or,e),e},Li=function(a){return qo(a,or)?a[or]:{}},Ps=function(a){return qo(a,or)});var Xe,or;Ah.exports={set:xs,get:Li,has:Ps,enforce:nP,getterFor:oP}});var Wo=m((eB,Rh)=>{"use strict";var Go=Re(),uP=Ke(),kh=Function.prototype,lP=Go&&Object.getOwnPropertyDescriptor,Qo=uP(kh,"name"),cP=Qo&&function(){}.name==="something",dP=Qo&&(!Go||Go&&lP(kh,"name").configurable);Rh.exports={EXISTS:Qo,PROPER:cP,CONFIGURABLE:dP}});var Lh=m($h=>{"use strict";var pP=Re(),hP=Ao(),fP=sr(),mP=st(),bP=ir(),gP=No();$h.f=pP&&!hP?Object.defineProperties:function(e,t){mP(e);for(var r=bP(t),i=gP(t),s=i.length,n=0,o;s>n;)fP.f(e,o=i[n++],r[o]);return e}});var Yo=m((rB,Mh)=>{"use strict";var vP=dt();Mh.exports=vP("document","documentElement")});var Xo=m((iB,Nh)=>{"use strict";var SP=st(),yP=Lh(),Ch=_o(),TP=Es(),IP=Yo(),EP=gs(),xP=Ts(),Dh=">",Oh="<",Ko="prototype",Jo="script",Vh=xP("IE_PROTO"),zo=function(){},_h=function(a){return Oh+Jo+Dh+a+Oh+"/"+Jo+Dh},Bh=function(a){a.write(_h("")),a.close();var e=a.parentWindow.Object;return a=null,e},PP=function(){var a=EP("iframe"),e="java"+Jo+":",t;return a.style.display="none",IP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(_h("document.F=Object")),t.close(),t.F},ws,As=function(){try{ws=new ActiveXObject("htmlfile")}catch(e){}As=typeof document!="undefined"?document.domain&&ws?Bh(ws):PP():Bh(ws);for(var a=Ch.length;a--;)delete As[Ko][Ch[a]];return As()};TP[Vh]=!0;Nh.exports=Object.create||function(e,t){var r;return e!==null?(zo[Ko]=SP(e),r=new zo,zo[Ko]=null,r[Vh]=e):r=As(),t===void 0?r:yP.f(r,t)}});var Hr=m((aB,Fh)=>{"use strict";var wP=_r();Fh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:wP(a,e,t),a}});var ru=m((sB,Hh)=>{"use strict";var AP=pe(),kP=Z(),RP=Le(),$P=Xo(),qh=Is(),LP=Hr(),MP=he(),CP=ze(),tu=MP("iterator"),Uh=!1,pt,Zo,eu;[].keys&&(eu=[].keys(),"next"in eu?(Zo=qh(qh(eu)),Zo!==Object.prototype&&(pt=Zo)):Uh=!0);var DP=!RP(pt)||AP(function(){var a={};return pt[tu].call(a)!==a});DP?pt={}:CP&&(pt=$P(pt));kP(pt[tu])||LP(pt,tu,function(){return this});Hh.exports={IteratorPrototype:pt,BUGGY_SAFARI_ITERATORS:Uh}});var ks=m((nB,Gh)=>{"use strict";var OP=he(),BP=OP("toStringTag"),jh={};jh[BP]="z";Gh.exports=String(jh)==="[object z]"});var Mi=m((oB,Qh)=>{"use strict";var VP=ks(),_P=Z(),Rs=rr(),NP=he(),FP=NP("toStringTag"),qP=Object,UP=Rs(function(){return arguments}())==="Arguments",HP=function(a,e){try{return a[e]}catch(t){}};Qh.exports=VP?Rs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=HP(e=qP(a),FP))=="string"?t:UP?Rs(e):(r=Rs(e))==="Object"&&_P(e.callee)?"Arguments":r}});var Yh=m((uB,Wh)=>{"use strict";var jP=ks(),GP=Mi();Wh.exports=jP?{}.toString:function(){return"[object "+GP(this)+"]"}});var Ci=m((lB,Kh)=>{"use strict";var QP=ks(),WP=sr().f,YP=_r(),zP=Ke(),KP=Yh(),JP=he(),zh=JP("toStringTag");Kh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(zP(i,zh)||WP(i,zh,{configurable:!0,value:e}),r&&!QP&&YP(i,"toString",KP))}});var Xh=m((cB,Jh)=>{"use strict";var XP=ru().IteratorPrototype,ZP=Xo(),ew=Ii(),tw=Ci(),rw=nr(),iw=function(){return this};Jh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=ZP(XP,{next:ew(+!r,t)}),tw(a,i,!1,!0),rw[i]=iw,a}});var ef=m((dB,Zh)=>{"use strict";var aw=ne(),sw=at();Zh.exports=function(a,e,t){try{return aw(sw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var rf=m((pB,tf)=>{"use strict";var nw=Le();tf.exports=function(a){return nw(a)||a===null}});var sf=m((hB,af)=>{"use strict";var ow=rf(),uw=String,lw=TypeError;af.exports=function(a){if(ow(a))return a;throw new lw("Can't set "+uw(a)+" as a prototype")}});var iu=m((fB,nf)=>{"use strict";var cw=ef(),dw=Le(),pw=Mt(),hw=sf();nf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=cw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return pw(i),hw(s),dw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var gf=m((mB,bf)=>{"use strict";var fw=ie(),mw=$e(),$s=ze(),ff=Wo(),bw=Z(),gw=Xh(),of=Is(),uf=iu(),vw=Ci(),Sw=_r(),au=Hr(),yw=he(),lf=nr(),mf=ru(),Tw=ff.PROPER,Iw=ff.CONFIGURABLE,cf=mf.IteratorPrototype,Ls=mf.BUGGY_SAFARI_ITERATORS,Di=yw("iterator"),df="keys",Oi="values",pf="entries",hf=function(){return this};bf.exports=function(a,e,t,r,i,s,n){gw(t,e,r);var o=function(S){if(S===i&&p)return p;if(!Ls&&S&&S in c)return c[S];switch(S){case df:return function(){return new t(this,S)};case Oi:return function(){return new t(this,S)};case pf:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Di]||c["@@iterator"]||i&&c[i],p=!Ls&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=of(h.call(new a)),f!==Object.prototype&&f.next&&(!$s&&of(f)!==cf&&(uf?uf(f,cf):bw(f[Di])||au(f,Di,hf)),vw(f,u,!0,!0),$s&&(lf[u]=hf))),Tw&&i===Oi&&d&&d.name!==Oi&&(!$s&&Iw?Sw(c,"name",Oi):(l=!0,p=function(){return mw(d,this)})),i)if(b={values:o(Oi),keys:s?p:o(df),entries:o(pf)},n)for(g in b)(Ls||l||!(g in c))&&au(c,g,b[g]);else fw({target:e,proto:!0,forced:Ls||l},b);return(!$s||n)&&c[Di]!==p&&au(c,Di,p,{name:i}),lf[e]=p,b}});var Sf=m((bB,vf)=>{"use strict";vf.exports=function(a,e){return{value:a,done:e}}});var nu=m((gB,xf)=>{"use strict";var Ew=ir(),su=$i(),yf=nr(),If=jo(),xw=sr().f,Pw=gf(),Ms=Sf(),ww=ze(),Aw=Re(),Ef="Array Iterator",kw=If.set,Rw=If.getterFor(Ef);xf.exports=Pw(Array,"Array",function(a,e){kw(this,{type:Ef,target:Ew(a),index:0,kind:e})},function(){var a=Rw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ms(void 0,!0);switch(a.kind){case"keys":return Ms(t,!1);case"values":return Ms(e[t],!1)}return Ms([t,e[t]],!1)},"values");var Tf=yf.Arguments=yf.Array;su("keys");su("values");su("entries");if(!ww&&Aw&&Tf.name!=="values")try{xw(Tf,"name",{value:"values"})}catch(a){}});var wf=m((vB,Pf)=>{"use strict";var $w=he(),Lw=nr(),Mw=$w("iterator"),Cw=Array.prototype;Pf.exports=function(a){return a!==void 0&&(Lw.Array===a||Cw[Mw]===a)}});var ou=m((SB,kf)=>{"use strict";var Dw=Mi(),Af=Pi(),Ow=Cr(),Bw=nr(),Vw=he(),_w=Vw("iterator");kf.exports=function(a){if(!Ow(a))return Af(a,_w)||Af(a,"@@iterator")||Bw[Dw(a)]}});var $f=m((yB,Rf)=>{"use strict";var Nw=$e(),Fw=at(),qw=st(),Uw=xi(),Hw=ou(),jw=TypeError;Rf.exports=function(a,e){var t=arguments.length<2?Hw(a):e;if(Fw(t))return qw(Nw(t,a));throw new jw(Uw(a)+" is not iterable")}});var Cf=m((TB,Mf)=>{"use strict";var Gw=$e(),Lf=st(),Qw=Pi();Mf.exports=function(a,e,t){var r,i;Lf(a);try{if(r=Qw(a,"return"),!r){if(e==="throw")throw t;return t}r=Gw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Lf(r),t}});var Ds=m((IB,Vf)=>{"use strict";var Ww=Vr(),Yw=$e(),zw=st(),Kw=xi(),Jw=wf(),Xw=qr(),Df=Ei(),Zw=$f(),eA=ou(),Of=Cf(),tA=TypeError,Cs=function(a,e){this.stopped=a,this.result=e},Bf=Cs.prototype;Vf.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Ww(e,r),l,c,d,p,h,f,b,g=function(v){return l&&Of(l,"normal",v),new Cs(!0,v)},S=function(v){return i?(zw(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(s)l=a.iterator;else if(n)l=a;else{if(c=eA(a),!c)throw new tA(Kw(a)+" is not iterable");if(Jw(c)){for(d=0,p=Xw(a);p>d;d++)if(h=S(a[d]),h&&Df(Bf,h))return h;return new Cs(!1)}l=Zw(a,c)}for(f=s?a.next:l.next;!(b=Yw(f,l)).done;){try{h=S(b.value)}catch(v){Of(l,"throw",v)}if(typeof h=="object"&&h&&Df(Bf,h))return h}return new Cs(!1)}});var Nf=m((EB,_f)=>{"use strict";var rA=Re(),iA=sr(),aA=Ii();_f.exports=function(a,e,t){rA?iA.f(a,e,aA(0,t)):a[e]=t}});var Ff=m(()=>{"use strict";var sA=ie(),nA=Ds(),oA=Nf();sA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return nA(e,function(r,i){oA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Uf=m((wB,qf)=>{"use strict";nu();Ff();var uA=Dr();qf.exports=uA.Object.fromEntries});var jf=m((AB,Hf)=>{"use strict";Hf.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 Qf=m(()=>{"use strict";nu();var lA=jf(),cA=te(),dA=Ci(),Gf=nr();for(Os in lA)dA(cA[Os],Os),Gf[Os]=Gf.Array;var Os});var Yf=m(($B,Wf)=>{"use strict";var pA=Uf();Qf();Wf.exports=pA});var uu=m((LB,zf)=>{"use strict";var hA=Yf();zf.exports=hA});var Kf=m(()=>{"use strict"});var lu=m((DB,Jf)=>{"use strict";var Bi=te(),fA=ar(),mA=rr(),Bs=function(a){return fA.slice(0,a.length)===a};Jf.exports=function(){return Bs("Bun/")?"BUN":Bs("Cloudflare-Workers")?"CLOUDFLARE":Bs("Deno/")?"DENO":Bs("Node.js/")?"NODE":Bi.Bun&&typeof Bun.version=="string"?"BUN":Bi.Deno&&typeof Deno.version=="object"?"DENO":mA(Bi.process)==="process"?"NODE":Bi.window&&Bi.document?"BROWSER":"REST"}()});var Vs=m((OB,Xf)=>{"use strict";var bA=lu();Xf.exports=bA==="NODE"});var em=m((BB,Zf)=>{"use strict";var gA=sr();Zf.exports=function(a,e,t){return gA.f(a,e,t)}});var im=m((VB,rm)=>{"use strict";var vA=dt(),SA=em(),yA=he(),TA=Re(),tm=yA("species");rm.exports=function(a){var e=vA(a);TA&&e&&!e[tm]&&SA(e,tm,{configurable:!0,get:function(){return this}})}});var sm=m((_B,am)=>{"use strict";var IA=Ei(),EA=TypeError;am.exports=function(a,e){if(IA(e,a))return a;throw new EA("Incorrect invocation")}});var du=m((NB,nm)=>{"use strict";var xA=ne(),PA=Z(),cu=wi(),wA=xA(Function.toString);PA(cu.inspectSource)||(cu.inspectSource=function(a){return wA(a)});nm.exports=cu.inspectSource});var hu=m((FB,dm)=>{"use strict";var AA=ne(),kA=pe(),om=Z(),RA=Mi(),$A=dt(),LA=du(),um=function(){},lm=$A("Reflect","construct"),pu=/^\s*(?:class|function)\b/,MA=AA(pu.exec),CA=!pu.test(um),Vi=function(e){if(!om(e))return!1;try{return lm(um,[],e),!0}catch(t){return!1}},cm=function(e){if(!om(e))return!1;switch(RA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return CA||!!MA(pu,LA(e))}catch(t){return!0}};cm.sham=!0;dm.exports=!lm||kA(function(){var a;return Vi(Vi.call)||!Vi(Object)||!Vi(function(){a=!0})||a})?cm:Vi});var hm=m((qB,pm)=>{"use strict";var DA=hu(),OA=xi(),BA=TypeError;pm.exports=function(a){if(DA(a))return a;throw new BA(OA(a)+" is not a constructor")}});var fu=m((UB,mm)=>{"use strict";var fm=st(),VA=hm(),_A=Cr(),NA=he(),FA=NA("species");mm.exports=function(a,e){var t=fm(a).constructor,r;return t===void 0||_A(r=fm(t)[FA])?e:VA(r)}});var gm=m((HB,bm)=>{"use strict";var qA=ne();bm.exports=qA([].slice)});var Sm=m((jB,vm)=>{"use strict";var UA=TypeError;vm.exports=function(a,e){if(a<e)throw new UA("Not enough arguments");return a}});var mu=m((GB,ym)=>{"use strict";var HA=ar();ym.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(HA)});var xu=m((QB,Rm)=>{"use strict";var Me=te(),jA=io(),GA=Vr(),Tm=Z(),QA=Ke(),km=pe(),Im=Yo(),WA=gm(),Em=gs(),YA=Sm(),zA=mu(),KA=Vs(),Tu=Me.setImmediate,Iu=Me.clearImmediate,JA=Me.process,bu=Me.Dispatch,XA=Me.Function,xm=Me.MessageChannel,ZA=Me.String,gu=0,_i={},Pm="onreadystatechange",Ni,ur,vu,Su;km(function(){Ni=Me.location});var Eu=function(a){if(QA(_i,a)){var e=_i[a];delete _i[a],e()}},yu=function(a){return function(){Eu(a)}},wm=function(a){Eu(a.data)},Am=function(a){Me.postMessage(ZA(a),Ni.protocol+"//"+Ni.host)};(!Tu||!Iu)&&(Tu=function(e){YA(arguments.length,1);var t=Tm(e)?e:XA(e),r=WA(arguments,1);return _i[++gu]=function(){jA(t,void 0,r)},ur(gu),gu},Iu=function(e){delete _i[e]},KA?ur=function(a){JA.nextTick(yu(a))}:bu&&bu.now?ur=function(a){bu.now(yu(a))}:xm&&!zA?(vu=new xm,Su=vu.port2,vu.port1.onmessage=wm,ur=GA(Su.postMessage,Su)):Me.addEventListener&&Tm(Me.postMessage)&&!Me.importScripts&&Ni&&Ni.protocol!=="file:"&&!km(Am)?(ur=Am,Me.addEventListener("message",wm,!1)):Pm in Em("script")?ur=function(a){Im.appendChild(Em("script"))[Pm]=function(){Im.removeChild(this),Eu(a)}}:ur=function(a){setTimeout(yu(a),0)});Rm.exports={set:Tu,clear:Iu}});var Mm=m((WB,Lm)=>{"use strict";var $m=te(),ek=Re(),tk=Object.getOwnPropertyDescriptor;Lm.exports=function(a){if(!ek)return $m[a];var e=tk($m,a);return e&&e.value}});var Pu=m((YB,Dm)=>{"use strict";var Cm=function(){this.head=null,this.tail=null};Cm.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}}};Dm.exports=Cm});var Bm=m((zB,Om)=>{"use strict";var rk=ar();Om.exports=/ipad|iphone|ipod/i.test(rk)&&typeof Pebble!="undefined"});var _m=m((KB,Vm)=>{"use strict";var ik=ar();Vm.exports=/web0s(?!.*chrome)/i.test(ik)});var Gm=m((JB,jm)=>{"use strict";var Gr=te(),ak=Mm(),Nm=Vr(),wu=xu().set,sk=Pu(),nk=mu(),ok=Bm(),uk=_m(),Au=Vs(),Fm=Gr.MutationObserver||Gr.WebKitMutationObserver,qm=Gr.document,Um=Gr.process,_s=Gr.Promise,$u=ak("queueMicrotask"),jr,ku,Ru,Ns,Hm;$u||(Fi=new sk,qi=function(){var a,e;for(Au&&(a=Um.domain)&&a.exit();e=Fi.get();)try{e()}catch(t){throw Fi.head&&jr(),t}a&&a.enter()},!nk&&!Au&&!uk&&Fm&&qm?(ku=!0,Ru=qm.createTextNode(""),new Fm(qi).observe(Ru,{characterData:!0}),jr=function(){Ru.data=ku=!ku}):!ok&&_s&&_s.resolve?(Ns=_s.resolve(void 0),Ns.constructor=_s,Hm=Nm(Ns.then,Ns),jr=function(){Hm(qi)}):Au?jr=function(){Um.nextTick(qi)}:(wu=Nm(wu,Gr),jr=function(){wu(qi)}),$u=function(a){Fi.head||jr(),Fi.add(a)});var Fi,qi;jm.exports=$u});var Wm=m((XB,Qm)=>{"use strict";Qm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Fs=m((ZB,Ym)=>{"use strict";Ym.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var lr=m((eV,zm)=>{"use strict";var lk=te();zm.exports=lk.Promise});var Qr=m((tV,Zm)=>{"use strict";var ck=te(),Ui=lr(),dk=Z(),pk=wo(),hk=du(),fk=he(),Km=lu(),mk=ze(),Lu=ho(),Jm=Ui&&Ui.prototype,bk=fk("species"),Mu=!1,Xm=dk(ck.PromiseRejectionEvent),gk=pk("Promise",function(){var a=hk(Ui),e=a!==String(Ui);if(!e&&Lu===66||mk&&!(Jm.catch&&Jm.finally))return!0;if(!Lu||Lu<51||!/native code/.test(a)){var t=new Ui(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[bk]=r,Mu=t.then(function(){})instanceof r,!Mu)return!0}return!e&&(Km==="BROWSER"||Km==="DENO")&&!Xm});Zm.exports={CONSTRUCTOR:gk,REJECTION_EVENT:Xm,SUBCLASSING:Mu}});var Wr=m((rV,tb)=>{"use strict";var eb=at(),vk=TypeError,Sk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new vk("Bad Promise constructor");e=r,t=i}),this.resolve=eb(e),this.reject=eb(t)};tb.exports.f=function(a){return new Sk(a)}});var yb=m(()=>{"use strict";var yk=ie(),Tk=ze(),js=Vs(),Dt=te(),Jr=$e(),rb=Hr(),ib=iu(),Ik=Ci(),Ek=im(),xk=at(),Hs=Z(),Pk=Le(),wk=sm(),Ak=fu(),ub=xu().set,Vu=Gm(),kk=Wm(),Rk=Fs(),$k=Pu(),lb=jo(),Gs=lr(),_u=Qr(),cb=Wr(),Qs="Promise",db=_u.CONSTRUCTOR,Lk=_u.REJECTION_EVENT,Mk=_u.SUBCLASSING,Cu=lb.getterFor(Qs),Ck=lb.set,Yr=Gs&&Gs.prototype,cr=Gs,qs=Yr,pb=Dt.TypeError,Du=Dt.document,Nu=Dt.process,Ou=cb.f,Dk=Ou,Ok=!!(Du&&Du.createEvent&&Dt.dispatchEvent),hb="unhandledrejection",Bk="rejectionhandled",ab=0,fb=1,Vk=2,Fu=1,mb=2,Us,sb,_k,nb,bb=function(a){var e;return Pk(a)&&Hs(e=a.then)?e:!1},gb=function(a,e){var t=e.value,r=e.state===fb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===mb&&Fk(e),e.rejection=Fu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new pb("Promise-chain cycle")):(l=bb(u))?Jr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},vb=function(a,e){a.notified||(a.notified=!0,Vu(function(){for(var t=a.reactions,r;r=t.get();)gb(r,a);a.notified=!1,e&&!a.rejection&&Nk(a)}))},Sb=function(a,e,t){var r,i;Ok?(r=Du.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Dt.dispatchEvent(r)):r={promise:e,reason:t},!Lk&&(i=Dt["on"+a])?i(r):a===hb&&kk("Unhandled promise rejection",t)},Nk=function(a){Jr(ub,Dt,function(){var e=a.facade,t=a.value,r=ob(a),i;if(r&&(i=Rk(function(){js?Nu.emit("unhandledRejection",t,e):Sb(hb,e,t)}),a.rejection=js||ob(a)?mb:Fu,i.error))throw i.value})},ob=function(a){return a.rejection!==Fu&&!a.parent},Fk=function(a){Jr(ub,Dt,function(){var e=a.facade;js?Nu.emit("rejectionHandled",e):Sb(Bk,e,a.value)})},zr=function(a,e,t){return function(r){a(e,r,t)}},Kr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Vk,vb(a,!0))},Bu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new pb("Promise can't be resolved itself");var r=bb(e);r?Vu(function(){var i={done:!1};try{Jr(r,e,zr(Bu,i,a),zr(Kr,i,a))}catch(s){Kr(i,s,a)}}):(a.value=e,a.state=fb,vb(a,!1))}catch(i){Kr({done:!1},i,a)}}};if(db&&(cr=function(e){wk(this,qs),xk(e),Jr(Us,this);var t=Cu(this);try{e(zr(Bu,t),zr(Kr,t))}catch(r){Kr(t,r)}},qs=cr.prototype,Us=function(e){Ck(this,{type:Qs,done:!1,notified:!1,parent:!1,reactions:new $k,rejection:!1,state:ab,value:void 0})},Us.prototype=rb(qs,"then",function(e,t){var r=Cu(this),i=Ou(Ak(this,cr));return r.parent=!0,i.ok=Hs(e)?e:!0,i.fail=Hs(t)&&t,i.domain=js?Nu.domain:void 0,r.state===ab?r.reactions.add(i):Vu(function(){gb(i,r)}),i.promise}),sb=function(){var a=new Us,e=Cu(a);this.promise=a,this.resolve=zr(Bu,e),this.reject=zr(Kr,e)},cb.f=Ou=function(a){return a===cr||a===_k?new sb(a):Dk(a)},!Tk&&Hs(Gs)&&Yr!==Object.prototype)){nb=Yr.then,Mk||rb(Yr,"then",function(e,t){var r=this;return new cr(function(i,s){Jr(nb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Yr.constructor}catch(a){}ib&&ib(Yr,qs)}yk({global:!0,constructor:!0,wrap:!0,forced:db},{Promise:cr});Ik(cr,Qs,!1,!0);Ek(Qs)});var Pb=m((sV,xb)=>{"use strict";var qk=he(),Ib=qk("iterator"),Eb=!1;try{Tb=0,qu={next:function(){return{done:!!Tb++}},return:function(){Eb=!0}},qu[Ib]=function(){return this},Array.from(qu,function(){throw 2})}catch(a){}var Tb,qu;xb.exports=function(a,e){try{if(!e&&!Eb)return!1}catch(i){return!1}var t=!1;try{var r={};r[Ib]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Uu=m((nV,wb)=>{"use strict";var Uk=lr(),Hk=Pb(),jk=Qr().CONSTRUCTOR;wb.exports=jk||!Hk(function(a){Uk.all(a).then(void 0,function(){})})});var Ab=m(()=>{"use strict";var Gk=ie(),Qk=$e(),Wk=at(),Yk=Wr(),zk=Fs(),Kk=Ds(),Jk=Uu();Gk({target:"Promise",stat:!0,forced:Jk},{all:function(e){var t=this,r=Yk.f(t),i=r.resolve,s=r.reject,n=zk(function(){var o=Wk(t.resolve),u=[],l=0,c=1;Kk(e,function(d){var p=l++,h=!1;c++,Qk(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Rb=m(()=>{"use strict";var Xk=ie(),Zk=ze(),eR=Qr().CONSTRUCTOR,ju=lr(),tR=dt(),rR=Z(),iR=Hr(),kb=ju&&ju.prototype;Xk({target:"Promise",proto:!0,forced:eR,real:!0},{catch:function(a){return this.then(void 0,a)}});!Zk&&rR(ju)&&(Hu=tR("Promise").prototype.catch,kb.catch!==Hu&&iR(kb,"catch",Hu,{unsafe:!0}));var Hu});var $b=m(()=>{"use strict";var aR=ie(),sR=$e(),nR=at(),oR=Wr(),uR=Fs(),lR=Ds(),cR=Uu();aR({target:"Promise",stat:!0,forced:cR},{race:function(e){var t=this,r=oR.f(t),i=r.reject,s=uR(function(){var n=nR(t.resolve);lR(e,function(o){sR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Lb=m(()=>{"use strict";var dR=ie(),pR=Wr(),hR=Qr().CONSTRUCTOR;dR({target:"Promise",stat:!0,forced:hR},{reject:function(e){var t=pR.f(this),r=t.reject;return r(e),t.promise}})});var Gu=m((mV,Mb)=>{"use strict";var fR=st(),mR=Le(),bR=Wr();Mb.exports=function(a,e){if(fR(a),mR(e)&&e.constructor===a)return e;var t=bR.f(a),r=t.resolve;return r(e),t.promise}});var Ob=m(()=>{"use strict";var gR=ie(),vR=dt(),Cb=ze(),SR=lr(),Db=Qr().CONSTRUCTOR,yR=Gu(),TR=vR("Promise"),IR=Cb&&!Db;gR({target:"Promise",stat:!0,forced:Cb||Db},{resolve:function(e){return yR(IR&&this===TR?SR:this,e)}})});var Bb=m(()=>{"use strict";yb();Ab();Rb();$b();Lb();Ob()});var Fb=m(()=>{"use strict";var ER=ie(),xR=ze(),Ws=lr(),PR=pe(),_b=dt(),Nb=Z(),wR=fu(),Vb=Gu(),AR=Hr(),Wu=Ws&&Ws.prototype,kR=!!Ws&&PR(function(){Wu.finally.call({then:function(){}},function(){})});ER({target:"Promise",proto:!0,real:!0,forced:kR},{finally:function(a){var e=wR(this,_b("Promise")),t=Nb(a);return this.then(t?function(r){return Vb(e,a()).then(function(){return r})}:a,t?function(r){return Vb(e,a()).then(function(){throw r})}:a)}});!xR&&Nb(Ws)&&(Qu=_b("Promise").prototype.finally,Wu.finally!==Qu&&AR(Wu,"finally",Qu,{unsafe:!0}));var Qu});var Ub=m((IV,qb)=>{"use strict";Kf();Bb();Fb();var RR=Ct();qb.exports=RR("Promise","finally")});var jb=m((EV,Hb)=>{"use strict";var $R=Ub();Hb.exports=$R});var Ys=m((xV,Gb)=>{"use strict";var LR=jb();Gb.exports=LR});var ag=m(()=>{"use strict";var GR=ie(),QR=Fo().values;GR({target:"Object",stat:!0},{values:function(e){return QR(e)}})});var ng=m((u_,sg)=>{"use strict";ag();var WR=Dr();sg.exports=WR.Object.values});var ug=m((l_,og)=>{"use strict";var YR=ng();og.exports=YR});var Zr=m((c_,lg)=>{"use strict";var zR=ug();lg.exports=zR});var Ig=m(()=>{"use strict";var d$=ie(),p$=Or(),h$=qr(),f$=Ri(),m$=$i();d$({target:"Array",proto:!0},{at:function(e){var t=p$(this),r=h$(t),i=f$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});m$("at")});var xg=m((__,Eg)=>{"use strict";Ig();var b$=Ct();Eg.exports=b$("Array","at")});var wg=m((N_,Pg)=>{"use strict";var g$=xg();Pg.exports=g$});var ti=m((F_,Ag)=>{"use strict";var v$=wg();Ag.exports=v$});var bl=m((mF,iv)=>{"use strict";var Z$=rr();iv.exports=Array.isArray||function(e){return Z$(e)==="Array"}});var sv=m((bF,av)=>{"use strict";var eL=TypeError,tL=9007199254740991;av.exports=function(a){if(a>tL)throw eL("Maximum allowed index exceeded");return a}});var uv=m((gF,ov)=>{"use strict";var rL=bl(),iL=qr(),aL=sv(),sL=Vr(),nv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?sL(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&rL(d)?(p=iL(d),u=nv(a,e,d,p,u,s-1)-1):(aL(u+1),a[u]=d),u++),l++;return u};ov.exports=nv});var pv=m((vF,dv)=>{"use strict";var lv=bl(),nL=hu(),oL=Le(),uL=he(),lL=uL("species"),cv=Array;dv.exports=function(a){var e;return lv(a)&&(e=a.constructor,nL(e)&&(e===cv||lv(e.prototype))?e=void 0:oL(e)&&(e=e[lL],e===null&&(e=void 0))),e===void 0?cv:e}});var fv=m((SF,hv)=>{"use strict";var cL=pv();hv.exports=function(a,e){return new(cL(a))(e===0?0:e)}});var mv=m(()=>{"use strict";var dL=ie(),pL=uv(),hL=at(),fL=Or(),mL=qr(),bL=fv();dL({target:"Array",proto:!0},{flatMap:function(e){var t=fL(this),r=mL(t),i;return hL(e),i=bL(t,0),i.length=pL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var bv=m(()=>{"use strict";var gL=$i();gL("flatMap")});var vv=m((xF,gv)=>{"use strict";mv();bv();var vL=Ct();gv.exports=vL("Array","flatMap")});var yv=m((PF,Sv)=>{"use strict";var SL=vv();Sv.exports=SL});var gl=m((wF,Tv)=>{"use strict";var yL=yv();Tv.exports=yL});var ia=m((VF,qv)=>{"use strict";var kL=Mi(),RL=String;qv.exports=function(a){if(kL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return RL(a)}});var Sl=m((_F,Uv)=>{"use strict";Uv.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 Gv=m((NF,jv)=>{"use strict";var $L=ne(),LL=Mt(),ML=ia(),Tl=Sl(),Hv=$L("".replace),CL=RegExp("^["+Tl+"]+"),DL=RegExp("(^|[^"+Tl+"])["+Tl+"]+$"),yl=function(a){return function(e){var t=ML(LL(e));return a&1&&(t=Hv(t,CL,"")),a&2&&(t=Hv(t,DL,"$1")),t}};jv.exports={start:yl(1),end:yl(2),trim:yl(3)}});var zv=m((FF,Yv)=>{"use strict";var OL=Wo().PROPER,BL=pe(),Qv=Sl(),Wv="\u200B\x85\u180E";Yv.exports=function(a){return BL(function(){return!!Qv[a]()||Wv[a]()!==Wv||OL&&Qv[a].name!==a})}});var Il=m((qF,Kv)=>{"use strict";var VL=Gv().start,_L=zv();Kv.exports=_L("trimStart")?function(){return VL(this)}:"".trimStart});var Xv=m(()=>{"use strict";var NL=ie(),Jv=Il();NL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Jv},{trimLeft:Jv})});var eS=m(()=>{"use strict";Xv();var FL=ie(),Zv=Il();FL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Zv},{trimStart:Zv})});var rS=m((QF,tS)=>{"use strict";eS();var qL=Ct();tS.exports=qL("String","trimLeft")});var aS=m((WF,iS)=>{"use strict";var UL=rS();iS.exports=UL});var nS=m((YF,sS)=>{"use strict";var HL=aS();sS.exports=HL});var IS=m(()=>{"use strict"});var ES=m(()=>{"use strict"});var PS=m((T1,xS)=>{"use strict";var pM=Le(),hM=rr(),fM=he(),mM=fM("match");xS.exports=function(a){var e;return pM(a)&&((e=a[mM])!==void 0?!!e:hM(a)==="RegExp")}});var AS=m((I1,wS)=>{"use strict";var bM=st();wS.exports=function(){var a=bM(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 $S=m((E1,RS)=>{"use strict";var gM=$e(),vM=Ke(),SM=Ei(),yM=AS(),kS=RegExp.prototype;RS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in kS)&&!vM(a,"flags")&&SM(kS,a)?gM(yM,a):e}});var MS=m((x1,LS)=>{"use strict";var Ll=ne(),TM=Or(),IM=Math.floor,Rl=Ll("".charAt),EM=Ll("".replace),$l=Ll("".slice),xM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,PM=/\$([$&'`]|\d{1,2})/g;LS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=PM;return i!==void 0&&(i=TM(i),u=xM),EM(s,u,function(l,c){var d;switch(Rl(c,0)){case"$":return"$";case"&":return a;case"`":return $l(e,0,t);case"'":return $l(e,n);case"<":d=i[$l(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=IM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Rl(c,1):r[h-1]+Rl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var OS=m(()=>{"use strict";var wM=ie(),AM=$e(),Cl=ne(),CS=Mt(),kM=Z(),RM=Cr(),$M=PS(),oi=ia(),LM=Pi(),MM=$S(),CM=MS(),DM=he(),OM=ze(),BM=DM("replace"),VM=TypeError,Ml=Cl("".indexOf),_M=Cl("".replace),DS=Cl("".slice),NM=Math.max;wM({target:"String",proto:!0},{replaceAll:function(e,t){var r=CS(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!RM(e)){if(i=$M(e),i&&(s=oi(CS(MM(e))),!~Ml(s,"g")))throw new VM("`.replaceAll` does not allow non-global regexes");if(n=LM(e,BM),n)return AM(n,e,r,t);if(OM&&i)return _M(oi(r),e,t)}for(o=oi(r),u=oi(e),l=kM(t),l||(t=oi(t)),c=u.length,d=NM(1,c),p=Ml(o,u);p!==-1;)h=l?oi(t(u,p,o)):CM(u,o,p,[],void 0,t),b+=DS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Ml(o,u,p+d);return f<o.length&&(b+=DS(o,f)),b}})});var VS=m((A1,BS)=>{"use strict";IS();ES();OS();var FM=Ct();BS.exports=FM("String","replaceAll")});var NS=m((k1,_S)=>{"use strict";var qM=VS();_S.exports=qM});var qS=m((R1,FS)=>{"use strict";var UM=NS();FS.exports=UM});var HS=m(($1,US)=>{"use strict";var HM=Ri(),jM=ia(),GM=Mt(),QM=RangeError;US.exports=function(e){var t=jM(GM(this)),r="",i=HM(e);if(i<0||i===1/0)throw new QM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var YS=m((L1,WS)=>{"use strict";var QS=ne(),WM=Mo(),jS=ia(),YM=HS(),zM=Mt(),KM=QS(YM),JM=QS("".slice),XM=Math.ceil,GS=function(a){return function(e,t,r){var i=jS(zM(e)),s=WM(t),n=i.length,o=r===void 0?" ":jS(r),u,l;return s<=n||o===""?i:(u=s-n,l=KM(o,XM(u/o.length)),l.length>u&&(l=JM(l,0,u)),a?i+l:l+i)}};WS.exports={start:GS(!1),end:GS(!0)}});var KS=m((M1,zS)=>{"use strict";var ZM=ar();zS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ZM)});var JS=m(()=>{"use strict";var eC=ie(),tC=YS().start,rC=KS();eC({target:"String",proto:!0,forced:rC},{padStart:function(e){return tC(this,e,arguments.length>1?arguments[1]:void 0)}})});var ZS=m((O1,XS)=>{"use strict";JS();var iC=Ct();XS.exports=iC("String","padStart")});var ty=m((B1,ey)=>{"use strict";var aC=ZS();ey.exports=aC});var iy=m((V1,ry)=>{"use strict";var sC=ty();ry.exports=sC});var Zc="2.0.123-dev.483e1429.0";var Se=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Se||{}),Lt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Lt||{});var fs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(fs||{}),eo=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(eo||{});var to=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(to||{});var DT=_(Je(),1);import{assertNever as Jp,assertNonNullable as vx,isNonNullable as Ss,ValueSubject as Do,Subject as Sx,Subscription as yx,merge as Tx,observableFrom as Ix,fromEvent as Wp,map as Yp,tap as zp,filterChanged as Ex,isNullable as Oo,ErrorCategory as Kp}from"@vkontakte/videoplayer-shared/es2015";var Qp=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var ys=class{constructor(e){this.connection$=new Do(void 0);this.castState$=new Do("NOT_AVAILABLE");this.errorEvent$=new Sx;this.realCastState$=new Do("NOT_AVAILABLE");this.subscription=new yx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ss((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Qp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Kp.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ss(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Oo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Oo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Wp(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Jp(i.sessionState)}})).add(Tx(Wp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(zp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Yp(i=>i.castState)),Ix([r.getCastState()])).pipe(Ex(),Yp(xx),zp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ss(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();vx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Oo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ss(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Kp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},xx=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Jp(a)}};var cc=_(Je(),1),fT=_(Ur(),1),mT=_(uu(),1);var tg=_(Ys(),1);import{assertNever as Qb}from"@vkontakte/videoplayer-shared/es2015";var fe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Qb(t)}return a},zs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Qb(e)}};var P=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as MR,Subject as Ks,merge as Wb}from"@vkontakte/videoplayer-shared/es2015";var C=class{constructor(e){this.transitionStarted$=new Ks;this.transitionEnded$=new Ks;this.transitionUpdated$=new Ks;this.forceChanged$=new Ks;this.stateChangeStarted$=Wb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Wb(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||MR(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as CR}from"@vkontakte/videoplayer-shared/es2015";var Yb=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return CR(a)}};import{assertNever as Xr,assertNonNullable as dr,debounce as zb,ErrorCategory as Kb,fromEvent as pr,isNonNullable as Jb,map as Xb,merge as Zb,observableFrom as DR,Subject as OR,Subscription as Yu,timeout as BR,getHighestQuality as VR}from"@vkontakte/videoplayer-shared/es2015";var _R=5,NR=5,FR=500,eg=7e3,Hi=class{constructor(e){this.subscription=new Yu;this.loadMediaTimeoutSubscription=new Yu;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Xr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Xr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Xr(e)}break}default:Xr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Yb(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 Yu;this.subscription.add(e),this.subscription.add(Zb(this.videoState.stateChangeStarted$.pipe(Xb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Xb(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new OR;e.add(i.pipe(zb(FR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>_R)&&i.next(o),s=o})),e.add(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<NR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Xr(n)}}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Zb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,DR(["init"])).pipe(zb(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];dr(c);let d=VR(Object.keys(c));dr(d);let p=c[d];dr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];dr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];dr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];dr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];dr(c),r=fe(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Kb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Xr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Jb(o)&&(n.metadata.title=o),Jb(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(BR(eg).subscribe(()=>s(`timeout(${eg})`)))});(0,tg.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Kb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var fl=_(Je(),1);import{clearVideoElement as ig}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as qR}from"@vkontakte/videoplayer-shared/es2015";var rg=a=>{try{a.pause(),a.playbackRate=0,qR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as UR,Subscription as HR}from"@vkontakte/videoplayer-shared/es2015";var zu=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)}},Ku=window.WeakMap?new WeakMap:new zu,Ju=window.WeakMap?new WeakMap:new Map,jR=(a,e=20)=>{let t=0;return UR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ye=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?ig(t):(t=document.createElement("video"),a.appendChild(t)),Ku.set(t,r);let i=new HR;return i.add(jR(t,e)),Ju.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Te=a=>{let e=Ju.get(a);e==null||e.unsubscribe(),Ju.delete(a);let t=Ku.get(a);Ku.delete(a),t?ig(a):rg(a)};var Zu=_(Zr(),1);import{assertNonNullable as ji,isNonNullable as ot,isNullable as XR,fromEvent as ei,merge as cg,observableFrom as dg,filterChanged as pg,map as Gi,Subject as hg,Subscription as ZR,ValueSubject as e$,ErrorCategory as t$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Xu,isNullable as KR,Subscription as JR}from"@vkontakte/videoplayer-shared/es2015";var Js=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=KR(i),l=new JR;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},nt=(a,e,t)=>Js(e,()=>a.loop,r=>{Xu(r)&&(a.loop=r)},{onError:t}),Ie=(a,e,t,r)=>Js(e,()=>({muted:a.muted,volume:a.volume}),i=>{Xu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Fe=(a,e,t,r)=>Js(e,()=>a.playbackRate,i=>{Xu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ot=Js;var r$=a=>["__",a.language,a.label].join("|"),i$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},el=class a{constructor(){this.available$=new hg;this.current$=new e$(void 0);this.error$=new hg;this.subscription=new ZR;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:t$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ot(t.internalTextTracks,()=>(0,Zu.default)(this.internalTracks),s=>{ot(s)&&this.setInternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ot(t.externalTextTracks,()=>(0,Zu.default)(this.externalTracks),s=>{ot(s)&&this.setExternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ot(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Ot(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ji(this.video);let{textTracks:e}=this.video;this.subscription.add(ei(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(cg(ei(e,"addtrack"),ei(e,"removetrack"),dg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),pg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(cg(ei(e,"change"),dg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Gi(r=>r&&this.htmlTextTrackToITextTrack(r).id),pg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(ei(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(ei(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;ot(t.align)&&(i.align=t.align),ot(t.position)&&(i.position=t.position),ot(t.size)&&(i.size=t.size),ot(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){ji(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:r$(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){ji(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(XR(e)||!i$(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){ji(this.video);let t=document.createElement("track");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){ji(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},qe=el;var ft=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 fg=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},tl=a=>{let e=fg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},mg=a=>{let e=fg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ue,map as Bt,merge as gg,filterChanged as s$,isNonNullable as vg,Subject as n$,filter as Sg,mapTo as yg,combine as o$,once as u$,ErrorCategory as l$,ValueSubject as Tg,clientChecker as c$}from"@vkontakte/videoplayer-shared/es2015";var a$=3,bg=(a,e,t=a$)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Ee=a=>{let e=y=>Ue(a,y).pipe(yg(void 0)),r=gg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Ue(a,y))).pipe(Bt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),s$()),i=gg(Ue(a,"progress"),Ue(a,"timeupdate")).pipe(Bt(()=>bg(a.buffered,a.currentTime))),s=c$.isSafari?o$({play:e("play").pipe(u$()),playing:e("playing")}).pipe(yg(void 0)):e("playing"),n=Ue(a,"volumechange").pipe(Bt(()=>({muted:a.muted,volume:a.volume}))),o=Ue(a,"ratechange").pipe(Bt(()=>a.playbackRate)),u=Ue(a,"error").pipe(Sg(()=>!!(a.error||a.played.length)),Bt(()=>{var I;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:l$.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=Ue(a,"timeupdate").pipe(Bt(()=>a.currentTime)),c=new n$,d=.3,p;l.subscribe(y=>{a.loop&&vg(p)&&vg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(Sg(()=>!a.error&&p!==a.duration)),f=Ue(a,"enterpictureinpicture"),b=Ue(a,"leavepictureinpicture"),g=new Tg(mg(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Tg(tl(a));return Ue(a,"fullscreenchange").pipe(Bt(()=>tl(a))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ue(a,"durationchange").pipe(Bt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b}};import{VideoQuality as Vt}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Vt.Q_144P;case"lowest":return Vt.Q_240P;case"low":return Vt.Q_360P;case"sd":case"medium":return Vt.Q_480P;case"hd":case"high":return Vt.Q_720P;case"fullhd":case"full":return Vt.Q_1080P;case"quadhd":case"quad":return Vt.Q_1440P;case"ultrahd":case"ultra":return Vt.Q_2160P}};var Nt=_(ti(),1),Dg=_(Je(),1),Xs=_(Ur(),1);import{isNonNullable as oe,isNullable as il,now as Og,isHigher as al,isHigherOrEqual as sl,isInvariantQuality as Lg,isLower as Mg,isLowerOrEqual as nl,videoSizeToQuality as S$,assertNotEmptyArray as Bg,assertNonNullable as y$}from"@vkontakte/videoplayer-shared/es2015";var rl=!1,mt={},kg=a=>{rl=a},Rg=()=>{mt={}},$g=a=>{a(mt)},Qi=(a,e)=>{var t;rl&&(mt.meta=(t=mt.meta)!=null?t:{},mt.meta[a]=e)},be=class{constructor(e){this.name=e}next(e){var r,i;if(!rl)return;mt.series=(r=mt.series)!=null?r:{};let t=(i=mt.series[this.name])!=null?i:[];t.push([Date.now(),e]),mt.series[this.name]=t}};var T$=new be("best_bitrate"),Vg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ol=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Og()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},_g='Assertion "ABR Tracks is empty array" failed',Zs=(a,e,t,r)=>{var u;let i=[...e].sort(ol(1)),s=[...t].sort(ol(1)),n=s.filter(l=>oe(l.bitrate)&&oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,Dg.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},Cg=a=>"quality"in a,Ng=(a,e,t,r)=>{var n;let i=oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Og()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Cg(o)?"video":"audio",l=Cg(o)?o.quality:o.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${l}
|
|
9
|
-
`}),o}return r==null||r.recordSwitch(t),t},
|
|
9
|
+
`}),o}return r==null||r.recordSwitch(t),t},I$=(a,e)=>Math.log(e)/Math.log(a),Ft=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{var q,R,U,N,W,A;Bg(a,_g);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let V=r.pixelRatioLogBase,[O=0,se=0,Ve=0]=r.pixelRatioLogCoefficients,It=I$(V,O*T+se)+Ve;Number.isFinite(It)&&(b*=It)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,S=r.considerPlaybackRate&&oe(o)?o:1,v=a.filter(T=>!Lg(T.quality)).sort((T,V)=>al(T.quality,V.quality)?-1:1),y=(q=(0,Nt.default)(v,-1))==null?void 0:q.quality,I=(R=(0,Nt.default)(v,0))==null?void 0:R.quality,E=il(i)||oe(i.min)&&oe(i.max)&&Mg(i.max,i.min)||oe(i.min)&&I&&al(i.min,I)||oe(i.max)&&y&&Mg(i.max,y),$=S*Vg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),D={},L=v.filter(T=>{let V=!0;if(g)if(T.size)V=T.size.width<=g.width&&T.size.height<=g.height;else{let de=g&&S$(g);V=de?nl(T.quality,de):!0}if(!V)return D[T.quality]="FitsContainer",!1;let O=h||t;if(!(oe(O)&&isFinite(O)&&oe(T.bitrate)?O-s>=T.bitrate*$:!0))return D[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&oe(r.minBufferToSwitchUp)&&u&&!Lg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&al(T.quality,u.quality))return D[T.quality]="Buffer",!1;if(!!d&&sl(T.quality,d))return D[T.quality]="DroppedFramesLimit",!1;if(!!p&&sl(T.quality,p))return D[T.quality]="StallsLimit",!1;let j=E||(il(i.max)||nl(T.quality,i.max))&&(il(i.min)||sl(T.quality,i.min)),ce=oe(c)&&!c?nl(T.quality,r.backgroundVideoQualityLimit):!0;return!j||!ce?(D[T.quality]="FitsQualityLimits",!1):!0})[0];L&&L.bitrate&&T$.next(L.bitrate);let F=(U=L!=null?L:(0,Nt.default)(v,-1))!=null?U:a[0];return F.quality!==((N=l==null?void 0:l.last)==null?void 0:N.quality)&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
12
|
${a.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate} }`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Xs.default)(r!=null?r:{}).map(([T,V])=>`${T}: ${V}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
containerSizeLimit: ${(W=g==null?void 0:g.width)!=null?W:0} x ${(
|
|
20
|
+
containerSizeLimit: ${(W=g==null?void 0:g.width)!=null?W:0} x ${(A=g==null?void 0:g.width)!=null?A:0},
|
|
21
21
|
estimatedThroughput: ${t},
|
|
22
22
|
stallsPredictedThroughput: ${h},
|
|
23
23
|
reserve: ${s},
|
|
@@ -26,26 +26,26 @@ var _T=Object.create;var Gn=Object.defineProperty,NT=Object.defineProperties,FT=
|
|
|
26
26
|
forwardBufferHealth: ${n},
|
|
27
27
|
bitrateFactor: ${$},
|
|
28
28
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
29
|
-
droppedVideoMaxQualityLimit: ${
|
|
29
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
30
30
|
stallsVideoMaxQualityLimit: ${p},
|
|
31
31
|
limitsAreInvalid: ${E},
|
|
32
32
|
maxQualityLimit: ${i==null?void 0:i.max},
|
|
33
33
|
minQualityLimit: ${i==null?void 0:i.min},
|
|
34
34
|
|
|
35
35
|
[limited video tracks]
|
|
36
|
-
${(0,
|
|
36
|
+
${(0,Xs.default)(D).map(([T,V])=>`${T}: ${V}`).join(`
|
|
37
37
|
`)||"All tracks are available"}
|
|
38
38
|
|
|
39
|
-
[best video track] ${
|
|
40
|
-
[selected video track] ${
|
|
41
|
-
`}),
|
|
39
|
+
[best video track] ${L==null?void 0:L.quality}
|
|
40
|
+
[selected video track] ${F==null?void 0:F.quality}
|
|
41
|
+
`}),Ng(r,f,F,l)},Fg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var S;Bg(t,_g);let c=i.considerPlaybackRate&&oe(s)?s:1,d=[...t].sort(ol(-1)),p=a.bitrate;y$(p);let h=c*Vg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=Zs(a,e,t,i.minVideoAudioRatio),g=l||r;return oe(g)&&isFinite(g)&&(f=d.find(v=>oe(v.bitrate)&&oe(b==null?void 0:b.bitrate)?g-p>=v.bitrate*h&&v.bitrate>=b.bitrate:!1)),f||(f=b),(f==null?void 0:f.bitrate)!==((S=o==null?void 0:o.last)==null?void 0:S.bitrate)&&u({message:`
|
|
42
42
|
[AUDIO TRACKS ABR]
|
|
43
43
|
[available audio tracks]
|
|
44
44
|
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
45
45
|
`)}
|
|
46
46
|
|
|
47
47
|
[tuning]
|
|
48
|
-
${(0,
|
|
48
|
+
${(0,Xs.default)(i!=null?i:{}).map(([v,y])=>`${v}: ${y}`).join(`
|
|
49
49
|
`)}
|
|
50
50
|
|
|
51
51
|
[limit params]
|
|
@@ -53,20 +53,20 @@ var _T=Object.create;var Gn=Object.defineProperty,NT=Object.defineProperties,FT=
|
|
|
53
53
|
stallsPredictedThroughput: ${l},
|
|
54
54
|
reserve: ${p},
|
|
55
55
|
playbackRate: ${s},
|
|
56
|
-
playbackRateFactor: ${
|
|
56
|
+
playbackRateFactor: ${c},
|
|
57
57
|
forwardBufferHealth: ${n},
|
|
58
58
|
bitrateFactor: ${h},
|
|
59
59
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
60
60
|
|
|
61
61
|
[selected audio track] ${f==null?void 0:f.id}
|
|
62
|
-
`}),f&&Mg(i,u,f,o)};var oe=a=>new URL(a).hostname;import{assertNever as Hg,assertNonNullable as jg,combine as _$,debounce as N$,ErrorCategory as Gg,filter as Qg,filterChanged as F$,isNonNullable as nl,map as Js,merge as Wg,observableFrom as q$,once as U$,Subscription as H$,ValueSubject as ol,videoQualityToHeight as j$,videoSizeToQuality as G$}from"@vkontakte/videoplayer-shared/es2015";var Og=F(it(),1);var Dg=a=>{if(a instanceof DOMException&&(0,Og.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"))},xe=(a,e)=>k(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Dg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Dg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as Ys,isNullable as y$,assertNonNullable as Hi}from"@vkontakte/videoplayer-shared/es2015";var Bg=F(Vi(),1);import{isNonNullable as Vg,assertNonNullable as Ws,now as v$}from"@vkontakte/videoplayer-shared/es2015";function ue(){return v$()}function rl(a){return ue()-a}function il(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function _g(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function zr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Ws(d);let R=rl(d),j;if(R<b){j=b-R,setTimeout(g,j);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},S=R=>(s=R,q),v=R=>(c=R,q),y=()=>(h="json",q),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,c&&c(),t&&t()}},E=R=>(p=R,q),$=()=>{d=ue(),n=new i,n.open("get",a);let R=0,j,L=0,W=()=>(Ws(d),Math.max(d,Math.max(j||0,L||0)));if(s&&n.addEventListener("progress",w=>{let T=ue();s.updateChunk&&w.loaded>R&&(s.updateChunk(W(),w.loaded-R),R=w.loaded,j=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Ws(n);let w=n.status;if(w>=200&&w<300){if(n.response.byteLength&&s){let T=n.response.byteLength-R;T&&s.updateChunk&&s.updateChunk(W(),T)}n.responseType==="json"&&!(0,Bg.default)(n.response).length?I():(c&&c(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),p){let w=()=>{Ws(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(L=ue(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=h,n.send(),q},q={withBitrateReporting:S,withParallel:E,withJSONResponse:y,withRetryCount:R=>(l=R,q),withRetryInterval:(R,j)=>(Vg(R)&&(b=R),Vg(j)&&(f=j),q),withTimeout:R=>(o=R,q),withFinally:v,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return q}var qi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ng=F(Vi(),1);var Ui=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ue(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ue()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=zr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ue()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ue();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Ng.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as T$}from"@vkontakte/videoplayer-shared/es2015";var zs=1e4,al=3;var I$=6e4,E$=10,x$=1,P$=500,ji=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new T$,this.chunkRateEstimator=new qi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=il(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=il(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ys(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{_g(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ui(al,zs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let I=s&&(!d||d===this.rep);return I||t("Not running!"),I},p=(I,E,$)=>{u&&u.abort(),u=zr(this.urlResolver.resolve(I,!1),E,$,()=>this._retryCallback()).withTimeout(zs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(al).withFinally(()=>{u=null}).send()},h=(I,E,$)=>{Hi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=ue()-1e4,D=0;for(let N=0;N<this.bufferStates.length;N++){let O=this.bufferStates[N];I=Math.min(I,O.buf),O.ts<$&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${I} drop=${D} jitter=${this.sourceJitter}`);let z=I-x$;this.sourceJitter>=0?z-=this.sourceJitter/2:this.sourceJitter-=1,z>3?f(1.15):z>1?f(1.1):z>.3?f(1.05):f(1)}},S=I=>{let E,$=()=>E&&E.start?E.start.length:0,D=w=>E.start[w]/1e3,z=w=>E.dur[w]/1e3,N=w=>E.fragIndex+w,O=(w,T)=>({chunkIdx:N(w),startTS:D(w),dur:z(w),discontinuity:T}),q=()=>{let w=0;if(E&&E.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,_=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,V=T;this.sourceJitter>1&&(V+=this.sourceJitter-1);let ie=E.dur.length-1;for(;ie>=0&&(V-=E.dur[ie],!(V<=0));--ie);w=Math.min(ie,E.dur.length-1-_),w=Math.max(w,0)}return O(w,!0)},R=w=>{let T=$();if(!(T<=0)){if(Ys(w)){for(let _=0;_<T;_++)if(D(_)>w)return O(_)}return q()}},j=w=>{let T=$(),_=w?w.chunkIdx+1:0,V=_-E.fragIndex;if(!(T<=0)){if(!w||V<0||V-T>E$)return t(`Resync: offset=${V} bChunks=${T} chunk=`+JSON.stringify(w)),q();if(!(V>=T))return O(_-E.fragIndex,!1)}},L=(w,T,_)=>{l&&l.abort(),l=zr(this.urlResolver.resolve(w,!0,this.lowLatency),T,_,()=>this._retryCallback()).withTimeout(zs).withRetryCount(al).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,T)=>{L(I,_=>{if(!c())return;E=_;let V=!!E.lowLatency;V!==this.lowLatency&&b(V);let ie=0;for(let Oe=0;Oe<E.dur.length;++Oe)ie+=E.dur[Oe];ie>0&&(Hi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,w(R(T))},()=>this._handleNetworkError())},nextChunk:j}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Hi(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:E,logger:$}=this.params,D=S(e.jidxUrl),z,N,O,q,R=0,j,L,W,w=()=>{j&&(clearTimeout(j),j=void 0);let H=Math.max(P$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=R+H,ce=ue(),Ve=Math.min(1e4,le-ce);R=ce;let Tt=()=>{l||c()&&D.seek(()=>{c()&&(R=ue(),T(),w())})};Ve>0?j=window.setTimeout(()=>{this.paused?w():Tt()},Ve):Tt()},T=()=>{let H;for(;H=D.nextChunk(q);)q=H,yt(H);let le=D.nextChunk(O);if(le){if(O&&le.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?w():(v(),this._initPlayerWith(e));return}Oe(le)}else w()},_=(H,le)=>{if(!c()||!this.sourceBuffer)return;let ce,Ve,Tt,Sr=It=>{window.setTimeout(()=>{c()&&_(H,le)},It)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),Sr(100);else{let It=ue(),Qt=E.currentTime;!this.paused&&E.buffered.length>1&&L===Qt&&It-W>500&&($("Stall suspected; trying to fix"),this._fixupStall()),L!==Qt&&(L=Qt,W=It);let yr=this._getBufferSizeSec();if(yr>30)$(`Buffered ${yr} seconds; delaying appendBuffer`),Sr(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:It,buf:yr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(ni){if(ni.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),Tt=this.sourceBuffer.buffered.length,Tt!==0&&(ce=this.sourceBuffer.buffered.start(0),Ve=Qt,Ve-ce>4&&this.sourceBuffer.remove(ce,Ve-3)),Sr(1e3);else throw ni}}},V=()=>{N&&z&&($([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(O)]),_(N,function(){N=null,T()}))},ie=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),Oe=H=>{c()&&h(ie(H),(le,ce)=>{if(c()){if(ce/=1e3,N=le,O=H,n=H.startTS,ce){let Ve=Math.min(10,H.dur/ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ve:Ve}V()}},()=>this._handleNetworkError())},yt=H=>{c()&&(Hi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(H),!1)))},vr=H=>{c()&&(e.cachedHeader=H,_(H,()=>{z=!0,V()}))};s=!0,D.seek(H=>{if(c()){if(R=ue(),!H){w();return}q=H,!y$(I)||H.startTS>I?Oe(H):(O=H,T())}},I),e.cachedHeader?vr(e.cachedHeader):p(e.headerUrl,vr,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Ys(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Hi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ys(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=c=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),f=c/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,h)=>{let f=ue();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&rl(n)<3e4)return;r(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let h=s.updateChunk(c,p);return h&&l(),h},notifySwitch:c=>{let p=ue();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=zr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(zs).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;xe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},I$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ug=F(Vr(),1);import{debounce as A$,filter as Fg,fromEvent as w$,interval as k$,isHigher as R$,isInvariantQuality as $$,isLower as L$,merge as M$,Subject as qg,Subscription as C$}from"@vkontakte/videoplayer-shared/es2015";var sl=class{constructor(){this.onDroopedVideoFramesLimit$=new qg;this.subscription=new C$;this.playing=!1;this.tracks=[];this.forceChecker$=new qg;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&&!$$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&R$(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(w$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=k$(this.droppedFramesChecker.checkTime).pipe(Fg(()=>this.playing),Fg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(A$(this.droppedFramesChecker.checkTime)),r=M$(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,Ug.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>L$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},Ks=sl;import{map as D$,Observable as O$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as V$}from"@vkontakte/videoplayer-shared/es2015";var Gi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var B$=(a,e)=>new O$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Gi()))},P(P({},r),e));i.observe(a);let s=V$(document,"visibilitychange").pipe(D$(n=>!document.hidden||Gi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),qe=B$;var Q$=["paused","playing","ready"],W$=["paused","playing","ready"],Qi=class{constructor(e){this.subscription=new H$;this.videoState=new C("stopped");this.representations$=new ol([]);this.textTracksManager=new Ne;this.droppedFramesManager=new Ks;this.maxSeekBackTime$=new ol(1/0);this.zeroTime$=new ol(void 0);this.liveOffset=new pt;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Gg.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=(r=Ot(u.name))!=null?r:G$(u.video),c=u.bitrate/1e3,p=P({},u.video);if(!d)continue;let h={id:l,quality:d,bitrate:c,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),nl(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,ul.default)(W$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,ul.default)(Q$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(fe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(fe(this.params.source.url,u))}return;default:return Hg(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Gg.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Wg(this.videoState.stateChangeStarted$.pipe(Js(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Js(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Ee(this.video);this.subscription.add(this.representations$.pipe(Js(i=>i.map(({track:s})=>s)),Qg(i=>!!i.length),U$()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(F$(),Js(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(_$({zeroTime:this.zeroTime$.pipe(Qg(nl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(at(this.video,this.params.desiredState.isLooped,t)).add(Ie(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(_e(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(qe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&j$(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Hg(i.to)}},t)).add(Wg(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,q$(["init"])).pipe(N$(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),Te(this.video)}createLiveDashPlayer(){let e=new ji({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,p,h,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(),r=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&nl(t)?t:Bt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;jg(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;jg(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(fe(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Yg=Qi;var Ly=F(it(),1);var nt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as CC,assertNonNullable as DC,debounce as OC,ErrorCategory as Wl,filter as ky,filterChanged as Ca,fromEvent as VC,isNonNullable as Ry,map as Yl,merge as An,observableFrom as BC,once as $y,Subscription as _C}from"@vkontakte/videoplayer-shared/es2015";var Xs=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Kr=class extends Xs{constructor(){super(),this.listeners||Xs.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)}},Wi=class{constructor(){Object.defineProperty(this,"signal",{value:new Kr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Wi.prototype[Symbol.toStringTag]="AbortController",Kr.prototype[Symbol.toStringTag]="AbortSignal");function Zs(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 ll(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Zs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(h){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((h,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Yi=Zs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zg=Yi?ll({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ft=Yi?zg.fetch:window.fetch,nF=Yi?zg.Request:window.Request,Me=Yi?Wi:window.AbortController,oF=Yi?Kr:window.AbortSignal;var jl=F(dl(),1);var ln=F(Yr(),1);var mt=()=>window.ManagedMediaSource||window.MediaSource,en=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},mv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},bv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as dn,clientChecker as cn}from"@vkontakte/videoplayer-shared/es2015";var Ue=document.createElement("video"),vL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',SL='video/mp4; codecs="hev1.1.6.L93.B0"',wv='video/webm; codecs="vp09.00.10.08"',kv='video/webm; codecs="av01.0.00M.08"',yL='audio/mp4; codecs="mp4a.40.2"',TL='audio/webm; codecs="opus"',gv,vv,zi={mms:en(),mse:mv(),hls:!!((gv=Ue.canPlayType)!=null&&gv.call(Ue,"application/x-mpegurl")||(vv=Ue.canPlayType)!=null&&vv.call(Ue,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Sv,yv,Pe={mp4:!!((Sv=Ue.canPlayType)!=null&&Sv.call(Ue,"video/mp4")),webm:!!((yv=Ue.canPlayType)!=null&&yv.call(Ue,"video/webm")),cmaf:!0},rn,Tv,an,Iv,sn,Ev,nn,xv,on,Pv,un,Av,Ae={h264:!!((Tv=(rn=mt())==null?void 0:rn.isTypeSupported)!=null&&Tv.call(rn,vL)),h265:!!((Iv=(an=mt())==null?void 0:an.isTypeSupported)!=null&&Iv.call(an,SL)),vp9:!!((Ev=(sn=mt())==null?void 0:sn.isTypeSupported)!=null&&Ev.call(sn,wv)),av1:!!((xv=(nn=mt())==null?void 0:nn.isTypeSupported)!=null&&xv.call(nn,kv)),aac:!!((Pv=(on=mt())==null?void 0:on.isTypeSupported)!=null&&Pv.call(on,yL)),opus:!!((Av=(un=mt())==null?void 0:un.isTypeSupported)!=null&&Av.call(un,TL))},Jr=(Ae.h264||Ae.h265)&&Ae.aac,ur,IL=()=>k(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:kv})})),window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:wv})}))]);ur={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{IL()}catch(a){console.error(a)}var Xr=zi.hls&&Pe.mp4,Rv=()=>Object.keys(Ae).filter(a=>Ae[a]),$v=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=zi.mse&&(!r||!!window.MediaStreamTrack)||zi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Pe.mp4&&Jr;case"DASH_WEBM":return i&&Pe.webm&&Ae.vp9&&Ae.opus;case"DASH_WEBM_AV1":return i&&Pe.webm&&Ae.av1&&Ae.opus;case"DASH_STREAMS":return i&&(Pe.mp4&&Jr||Pe.webm&&(Ae.vp9||Ae.av1)&&(Ae.opus||Ae.aac));case"DASH_LIVE":return i&&Pe.mp4&&Jr;case"DASH_LIVE_CMAF":return i&&Pe.mp4&&Jr&&Pe.cmaf;case"DASH_ONDEMAND":return i&&Pe.mp4&&Jr;case"HLS":case"HLS_ONDEMAND":return Xr||e&&i&&Pe.mp4&&Jr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Xr;case"MPEG":return Pe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return zi.webrtc&&zi.ws&&Ae.h264&&(Pe.mp4||Pe.webm);default:return dn(s)}})},tn=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return ur?ur[t].smooth?[t,e]:ur[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ur?ur[t].powerEfficient?[t,e]:ur[e].powerEfficient?[e,t]:[t,e]:[e,t];default:dn(a)}return[e,t]},Lv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...tn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(cn.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...tn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...tn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...tn(a),...i,"HLS","HLS_ONDEMAND"];default:dn(e)}return Xr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Mv=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=cn.isMac&&cn.isSafari;if(cn.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:dn(a)}else Xr&&!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"]},pl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Cv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,ln.default)(t.value.split("."),0)}for(let t of a){let r=(0,ln.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,ln.default)(e.value.split("."),0)};var eS=F(Zv(),1);import{ErrorCategory as Ji}from"@vkontakte/videoplayer-shared/es2015";var tS=a=>{if(!a)return{id:"EmptyResponse",category:Ji.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ji.NETWORK,message:`UV Error ${a}`};let e=(0,eS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ji.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:Ji.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ji.PARSER,message:"Response is valid XML, but parser failed"}};var _t=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as ql,assertNonNullable as fr,clientChecker as hC,combine as Ra,ErrorCategory as Ut,filter as yn,filterChanged as Ul,flattenObject as $a,fromEvent as mr,getTraceSubscriptionMethod as fC,interval as Hl,isNonNullable as Sy,map as La,merge as br,now as mC,Subject as yy,Subscription as Ty,tap as bC,throttle as gC,ValueSubject as ee}from"@vkontakte/videoplayer-shared/es2015";var fn=F(it(),1),ri=F(Yr(),1),mn=F(dl(),1);var NL=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},FL=a=>window.clearTimeout(a),rS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),iS=!rS(window.requestIdleCallback)||!rS(window.cancelIdleCallback),gl=iS?NL:window.requestIdleCallback,Xi=iS?FL:window.cancelIdleCallback;var dy=F(qs(),1);import{assertNever as qL,ErrorCategory as aS,clientChecker as vl,Subject as sS}from"@vkontakte/videoplayer-shared/es2015";var UL=18,nS=!1;try{nS=vl.isSafari&&!!vl.macVersion&&vl.macVersion<=UL}catch(a){console.error(a)}var Sl=class{constructor(e){this.bufferFull$=new sS;this.error$=new sS;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:aS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return k(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return k(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return k(this,null,function*(){return new Promise(t=>{let r;nS&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:aS.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:qL(t)}}},oS=Sl;var yl=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 dr,assertNonNullable as ge,ErrorCategory as Ft,fromEvent as Vl,getExponentialDelay as Bl,isNonNullable as pn,isNullable as He,now as hn,once as iC,Subject as aC,Subscription as sC,ValueSubject as ti}from"@vkontakte/videoplayer-shared/es2015";var Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Zr=class extends Q{};var Zi=class extends Q{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ea=class extends Q{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ta=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var J=class extends Q{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ra=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ia=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var aa=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var lr=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var sa=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var na=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends J{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ua=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var la=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ca=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var pa=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ha=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ma=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ba=class extends J{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ga=class extends J{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var va=class extends J{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var jL={ftyp:ea,moov:ta,mvhd:ra,moof:ia,mdat:aa,sidx:lr,trak:sa,mdia:ca,mfhd:fa,tkhd:da,traf:ma,tfhd:ba,tfdt:ga,trun:va,minf:pa,sv3d:na,st3d:oa,prhd:ua,proj:ha,equi:la,uuid:Zi,unknown:Zr},bt=class a{constructor(e={}){this.options=P({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=jL[e];return r?new r(t,new a):new Zr(t,new a)}};var Nt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var QL=new TextDecoder("ascii"),WL=a=>QL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",YL=a=>{let e=new lr(a,new bt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},zL=(a,e)=>{let r=new bt().parse(a),i=new Nt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},KL=a=>{let t=new bt().parse(a),r=new Nt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},JL=a=>{var i;let t=new bt().parse(a);return(i=new Nt(t).find("sidx"))==null?void 0:i.timescale},XL=(a,e)=>{let r=new bt().parse(a),s=new Nt(r).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},ZL=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new bt().parse(a),i=new Nt(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},uS={validateData:WL,parseInit:ZL,getIndexRange:()=>{},parseSegments:YL,parseFeedableSegmentChunk:zL,getChunkEndTime:XL,getServerLatencyTimestamps:KL,getTimescaleFromIndex:JL};var ya=F(it(),1);import{assertNonNullable as Il,isNonNullable as pS,isNullable as tM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as eM}from"@vkontakte/videoplayer-shared/es2015";var lS={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"}},cS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Sa(a,t),i=r in lS,s=i?lS[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=Sa(u),c=l*et(2,(o-1)*8)+d,p=t+o,h;return p+c>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,c),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:h,valueSize:c}},Sa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*et(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*et(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*et(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},Ke=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Sa(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:eM(e)}},cr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=cS(r);if(!e(i))return;i.type==="master"&&cr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},dS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=cS(a);return cr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ke(o,n):s===17026?t=Ke(o,n):s===17029&&(r=Ke(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var hS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],rM=[231,22612,22743,167,171,163,160,175],iM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return cr(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ke(f,h);l=Sa(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ke(f,h):p===17545?i=Ke(f,h):p===21420&&l===475249515?u=Ke(f,h):p===374648427?cr(f,({tag:g,type:S,value:v})=>g===30321?(d=Ke(v,S)===1,!1):!0):s&&n&&(0,ya.default)(hS,p)&&(o=!0),!o}),Il(e,"Failed to parse webm Segment start"),Il(t,"Failed to parse webm Segment end"),Il(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},aM=a=>{if(tM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},sM=(a,e)=>{let t=!1,r=!1,i=o=>pS(o.time)&&pS(o.position),s=[],n;return cr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ke(l,u));break;case 183:break;case 241:n&&(n.position=Ke(l,u));break;default:t&&(0,ya.default)(hS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[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}}})},nM=a=>{let e=0,t=!1;try{cr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ya.default)(rM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ya.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},fS={validateData:dS,parseInit:iM,getIndexRange:aM,parseSegments:sM,parseFeedableSegmentChunk:nM};var Ta=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return fS;case"mp4":return uS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Rl=F(DS(),1),iy=F(Vr(),1),ay=F(KS(),1),sy=F(Yr(),1);var JS=F(it(),1),kl=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,JS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as ey,isNullable as ty}from"@vkontakte/videoplayer-shared/es2015";var XS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var ZS=a=>{var e;try{let t=tC(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function tC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
62
|
+
`}),f&&Ng(i,u,f,o)};var ue=a=>new URL(a).hostname;import{assertNever as Kg,assertNonNullable as Jg,combine as H$,debounce as j$,ErrorCategory as Xg,filter as Zg,filterChanged as G$,isNonNullable as pl,map as sn,merge as ev,observableFrom as Q$,once as W$,Subscription as Y$,ValueSubject as hl,videoQualityToHeight as z$,videoSizeToQuality as K$}from"@vkontakte/videoplayer-shared/es2015";var Ug=_(Je(),1);var qg=a=>{if(a instanceof DOMException&&(0,Ug.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"))},xe=(a,e)=>k(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!qg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return qg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as tn,isNullable as P$,assertNonNullable as Ki}from"@vkontakte/videoplayer-shared/es2015";var jg=_(Zr(),1);import{isNonNullable as Hg,assertNonNullable as en,now as E$}from"@vkontakte/videoplayer-shared/es2015";function le(){return E$()}function ul(a){return le()-a}function ll(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Gg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ri(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;en(c);let R=ul(c),U;if(R<b){U=b-R,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},S=R=>(s=R,q),v=R=>(d=R,q),y=()=>(h="json",q),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=R=>(p=R,q),$=()=>{c=le(),n=new i,n.open("get",a);let R=0,U,N=0,W=()=>(en(c),Math.max(c,Math.max(U||0,N||0)));if(s&&n.addEventListener("progress",A=>{let T=le();s.updateChunk&&A.loaded>R&&(s.updateChunk(W(),A.loaded-R),R=A.loaded,U=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;en(n);let A=n.status;if(A>=200&&A<300){if(n.response.byteLength&&s){let T=n.response.byteLength-R;T&&s.updateChunk&&s.updateChunk(W(),T)}n.responseType==="json"&&!(0,jg.default)(n.response).length?I():(d&&d(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),p){let A=()=>{en(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=le(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=h,n.send(),q},q={withBitrateReporting:S,withParallel:E,withJSONResponse:y,withRetryCount:R=>(l=R,q),withRetryInterval:(R,U)=>(Hg(R)&&(b=R),Hg(U)&&(f=U),q),withTimeout:R=>(o=R,q),withFinally:v,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var Yi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Qg=_(Zr(),1);var zi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=le(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=le()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ri(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=le()}_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=le();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Qg.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as w$}from"@vkontakte/videoplayer-shared/es2015";var rn=1e4,cl=3;var A$=6e4,k$=10,R$=1,$$=500,Ji=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new w$,this.chunkRateEstimator=new Yi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ll(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ll(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||tn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Gg(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zi(cl,rn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},p=(I,E,$)=>{u&&u.abort(),u=ri(this.urlResolver.resolve(I,!1),E,$,()=>this._retryCallback()).withTimeout(rn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(cl).withFinally(()=>{u=null}).send()},h=(I,E,$)=>{Ki(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=le()-1e4,D=0;for(let L=0;L<this.bufferStates.length;L++){let F=this.bufferStates[L];I=Math.min(I,F.buf),F.ts<$&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${I} drop=${D} jitter=${this.sourceJitter}`);let J=I-R$;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?f(1.15):J>1?f(1.1):J>.3?f(1.05):f(1)}},S=I=>{let E,$=()=>E&&E.start?E.start.length:0,D=A=>E.start[A]/1e3,J=A=>E.dur[A]/1e3,L=A=>E.fragIndex+A,F=(A,T)=>({chunkIdx:L(A),startTS:D(A),dur:J(A),discontinuity:T}),q=()=>{let A=0;if(E&&E.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,V=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,O=T;this.sourceJitter>1&&(O+=this.sourceJitter-1);let se=E.dur.length-1;for(;se>=0&&(O-=E.dur[se],!(O<=0));--se);A=Math.min(se,E.dur.length-1-V),A=Math.max(A,0)}return F(A,!0)},R=A=>{let T=$();if(!(T<=0)){if(tn(A)){for(let V=0;V<T;V++)if(D(V)>A)return F(V)}return q()}},U=A=>{let T=$(),V=A?A.chunkIdx+1:0,O=V-E.fragIndex;if(!(T<=0)){if(!A||O<0||O-T>k$)return t(`Resync: offset=${O} bChunks=${T} chunk=`+JSON.stringify(A)),q();if(!(O>=T))return F(V-E.fragIndex,!1)}},N=(A,T,V)=>{l&&l.abort(),l=ri(this.urlResolver.resolve(A,!0,this.lowLatency),T,V,()=>this._retryCallback()).withTimeout(rn).withRetryCount(cl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,T)=>{N(I,V=>{if(!d())return;E=V;let O=!!E.lowLatency;O!==this.lowLatency&&b(O);let se=0;for(let Ve=0;Ve<E.dur.length;++Ve)se+=E.dur[Ve];se>0&&(Ki(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,A(R(T))},()=>this._handleNetworkError())},nextChunk:U}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ki(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:$}=this.params,D=S(e.jidxUrl),J,L,F,q,R=0,U,N,W,A=()=>{U&&(clearTimeout(U),U=void 0);let j=Math.max($$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=R+j,de=le(),_e=Math.min(1e4,ce-de);R=de;let Et=()=>{l||d()&&D.seek(()=>{d()&&(R=le(),T(),A())})};_e>0?U=window.setTimeout(()=>{this.paused?A():Et()},_e):Et()},T=()=>{let j;for(;j=D.nextChunk(q);)q=j,It(j);let ce=D.nextChunk(F);if(ce){if(F&&ce.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?A():(v(),this._initPlayerWith(e));return}Ve(ce)}else A()},V=(j,ce)=>{if(!d()||!this.sourceBuffer)return;let de,_e,Et,Pr=xt=>{window.setTimeout(()=>{d()&&V(j,ce)},xt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),Pr(100);else{let xt=le(),zt=E.currentTime;!this.paused&&E.buffered.length>1&&N===zt&&xt-W>500&&($("Stall suspected; trying to fix"),this._fixupStall()),N!==zt&&(N=zt,W=xt);let wr=this._getBufferSizeSec();if(wr>30)$(`Buffered ${wr} seconds; delaying appendBuffer`),Pr(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:xt,buf:wr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(hi){if(hi.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(de=this.sourceBuffer.buffered.start(0),_e=zt,_e-de>4&&this.sourceBuffer.remove(de,_e-3)),Pr(1e3);else throw hi}}},O=()=>{L&&J&&($([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(F)]),V(L,function(){L=null,T()}))},se=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),Ve=j=>{d()&&h(se(j),(ce,de)=>{if(d()){if(de/=1e3,L=ce,F=j,n=j.startTS,de){let _e=Math.min(10,j.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*_e:_e}O()}},()=>this._handleNetworkError())},It=j=>{d()&&(Ki(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(j),!1)))},xr=j=>{d()&&(e.cachedHeader=j,V(j,()=>{J=!0,O()}))};s=!0,D.seek(j=>{if(d()){if(R=le(),!j){A();return}q=j,!P$(I)||j.startTS>I?Ve(j):(F=j,T())}},I),e.cachedHeader?xr(e.cachedHeader):p(e.headerUrl,xr,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),tn(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ki(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return tn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=le();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ul(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=le();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ri(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(rn).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;xe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},A$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var zg=_(Ur(),1);import{debounce as L$,filter as Wg,fromEvent as M$,interval as C$,isHigher as D$,isInvariantQuality as O$,isLower as B$,merge as V$,Subject as Yg,Subscription as _$}from"@vkontakte/videoplayer-shared/es2015";var dl=class{constructor(){this.onDroopedVideoFramesLimit$=new Yg;this.subscription=new _$;this.playing=!1;this.tracks=[];this.forceChecker$=new Yg;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&&!O$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&D$(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(M$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=C$(this.droppedFramesChecker.checkTime).pipe(Wg(()=>this.playing),Wg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(L$(this.droppedFramesChecker.checkTime)),r=V$(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,zg.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>B$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},an=dl;import{map as N$,Observable as F$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as q$}from"@vkontakte/videoplayer-shared/es2015";var Xi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var U$=(a,e)=>new F$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Xi()))},x(x({},r),e));i.observe(a);let s=q$(document,"visibilitychange").pipe(N$(n=>!document.hidden||Xi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),He=U$;var J$=["paused","playing","ready"],X$=["paused","playing","ready"],Zi=class{constructor(e){this.subscription=new Y$;this.videoState=new C("stopped");this.representations$=new hl([]);this.textTracksManager=new qe;this.droppedFramesManager=new an;this.maxSeekBackTime$=new hl(1/0);this.zeroTime$=new hl(void 0);this.liveOffset=new ft;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Xg.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=_t(u.name))!=null?r:K$(u.video),d=u.bitrate/1e3,p=x({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),pl(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,fl.default)(X$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,fl.default)(J$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(fe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(fe(this.params.source.url,u))}return;default:return Kg(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Xg.WTF,message:"DashLiveProvider internal logic error",thrown:i})};ev(this.videoState.stateChangeStarted$.pipe(sn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(sn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=ye(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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Ee(this.video);this.subscription.add(this.representations$.pipe(sn(i=>i.map(({track:s})=>s)),Zg(i=>!!i.length),W$()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(G$(),sn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(H$({zeroTime:this.zeroTime$.pipe(Zg(pl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(Ie(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Fe(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(He(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&z$(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Kg(i.to)}},t)).add(ev(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Q$(["init"])).pipe(j$(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),Te(this.video)}createLiveDashPlayer(){let e=new Ji({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&pl(t)?t:Ft(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Jg(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;Jg(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(fe(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var tv=Zi;var Ny=_(Je(),1);var ut=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as FC,assertNonNullable as qC,debounce as UC,ErrorCategory as Zl,filter as By,filterChanged as qa,fromEvent as HC,isNonNullable as Vy,map as ec,merge as Mn,observableFrom as tc,once as _y,Subscription as jC}from"@vkontakte/videoplayer-shared/es2015";var nn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ii=class extends nn{constructor(){super(),this.listeners||nn.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 ii,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ea.prototype[Symbol.toStringTag]="AbortController",ii.prototype[Symbol.toStringTag]="AbortSignal");function on(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function ml(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!on({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ta=on({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),rv=ta?ml({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,bt=ta?rv.fetch:window.fetch,pF=ta?rv.Request:window.Request,Ce=ta?ea:window.AbortController,hF=ta?ii:window.AbortSignal;var Kl=_(gl(),1);var bn=_(ti(),1);var gt=()=>window.ManagedMediaSource||window.MediaSource,un=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Iv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ev=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as vn,clientChecker as gn}from"@vkontakte/videoplayer-shared/es2015";var je=document.createElement("video"),EL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',xL='video/mp4; codecs="hev1.1.6.L93.B0"',Dv='video/webm; codecs="vp09.00.10.08"',Ov='video/webm; codecs="av01.0.00M.08"',PL='audio/mp4; codecs="mp4a.40.2"',wL='audio/webm; codecs="opus"',xv,Pv,ra={mms:un(),mse:Iv(),hls:!!((xv=je.canPlayType)!=null&&xv.call(je,"application/x-mpegurl")||(Pv=je.canPlayType)!=null&&Pv.call(je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},wv,Av,Pe={mp4:!!((wv=je.canPlayType)!=null&&wv.call(je,"video/mp4")),webm:!!((Av=je.canPlayType)!=null&&Av.call(je,"video/webm")),cmaf:!0},cn,kv,dn,Rv,pn,$v,hn,Lv,fn,Mv,mn,Cv,we={h264:!!((kv=(cn=gt())==null?void 0:cn.isTypeSupported)!=null&&kv.call(cn,EL)),h265:!!((Rv=(dn=gt())==null?void 0:dn.isTypeSupported)!=null&&Rv.call(dn,xL)),vp9:!!(($v=(pn=gt())==null?void 0:pn.isTypeSupported)!=null&&$v.call(pn,Dv)),av1:!!((Lv=(hn=gt())==null?void 0:hn.isTypeSupported)!=null&&Lv.call(hn,Ov)),aac:!!((Mv=(fn=gt())==null?void 0:fn.isTypeSupported)!=null&&Mv.call(fn,PL)),opus:!!((Cv=(mn=gt())==null?void 0:mn.isTypeSupported)!=null&&Cv.call(mn,wL))},ai=(we.h264||we.h265)&&we.aac,hr,AL=()=>k(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(M(x({},a),{video:M(x({},a.video),{contentType:Ov})})),window.navigator.mediaCapabilities.decodingInfo(M(x({},a),{video:M(x({},a.video),{contentType:Dv})}))]);hr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{AL()}catch(a){console.error(a)}var si=ra.hls&&Pe.mp4,Bv=()=>Object.keys(we).filter(a=>we[a]),Vv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ra.mse&&(!r||!!window.MediaStreamTrack)||ra.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Pe.mp4&&ai;case"DASH_WEBM":return i&&Pe.webm&&we.vp9&&we.opus;case"DASH_WEBM_AV1":return i&&Pe.webm&&we.av1&&we.opus;case"DASH_STREAMS":return i&&(Pe.mp4&&ai||Pe.webm&&(we.vp9||we.av1)&&(we.opus||we.aac));case"DASH_LIVE":return i&&Pe.mp4&&ai;case"DASH_LIVE_CMAF":return i&&Pe.mp4&&ai&&Pe.cmaf;case"DASH_ONDEMAND":return i&&Pe.mp4&&ai;case"HLS":case"HLS_ONDEMAND":return si||e&&i&&Pe.mp4&&ai;case"HLS_LIVE":case"HLS_LIVE_CMAF":return si;case"MPEG":return Pe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ra.webrtc&&ra.ws&&we.h264&&(Pe.mp4||Pe.webm);default:return vn(s)}})},ln=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return hr?hr[t].smooth?[t,e]:hr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return hr?hr[t].powerEfficient?[t,e]:hr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:vn(a)}return[e,t]},_v=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ln(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(gn.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...ln(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ln(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ln(a),...i,"HLS","HLS_ONDEMAND"];default:vn(e)}return si?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Nv=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=gn.isMac&&gn.isSafari;if(gn.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:vn(a)}else si&&!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"]},vl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Fv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,bn.default)(t.value.split("."),0)}for(let t of a){let r=(0,bn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,bn.default)(e.value.split("."),0)};var oS=_(nS(),1);import{ErrorCategory as aa}from"@vkontakte/videoplayer-shared/es2015";var uS=a=>{if(!a)return{id:"EmptyResponse",category:aa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:aa.NETWORK,message:`UV Error ${a}`};let e=(0,oS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:aa.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:aa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:aa.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as Yl,assertNonNullable as yr,clientChecker as yC,combine as ci,ErrorCategory as Gt,filter as Va,filterChanged as wn,flattenObject as _a,fromEvent as Tr,getTraceSubscriptionMethod as TC,interval as zl,isNonNullable as Ay,map as Na,merge as Ir,now as IC,Subject as ky,Subscription as Ry,tap as EC,throttle as xC,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2015";var yn=_(Je(),1),ui=_(ti(),1),Tn=_(gl(),1);var jL=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},GL=a=>window.clearTimeout(a),lS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),cS=!lS(window.requestIdleCallback)||!lS(window.cancelIdleCallback),El=cS?jL:window.requestIdleCallback,sa=cS?GL:window.cancelIdleCallback;var Sy=_(Ys(),1);import{assertNever as QL,ErrorCategory as dS,clientChecker as xl,Subject as pS}from"@vkontakte/videoplayer-shared/es2015";var WL=18,hS=!1;try{hS=xl.isSafari&&!!xl.macVersion&&xl.macVersion<=WL}catch(a){console.error(a)}var Pl=class{constructor(e){this.bufferFull$=new pS;this.error$=new pS;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:dS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return k(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return k(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return k(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};hS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:dS.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:QL(t)}}},fS=Pl;var wl=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 br,assertNonNullable as Oe,clientChecker as lC,ErrorCategory as Ht,fromEvent as Hl,getExponentialDelay as jl,isNonNullable as $a,isNullable as Ae,now as Sn,once as cC,Subject as dC,Subscription as pC,ValueSubject as gr}from"@vkontakte/videoplayer-shared/es2015";var Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ni=class extends Q{};var na=class extends Q{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var oa=class extends Q{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ua=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var X=class extends Q{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var la=class extends X{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 ca=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var fr=class extends X{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var pa=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ha=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends X{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 X{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ba=class extends X{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ga=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var va=class extends X{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 Sa=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ya=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ta=class extends X{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ia=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ea=class extends X{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 xa=class extends X{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Pa=class extends X{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var zL={ftyp:oa,moov:ua,mvhd:la,moof:ca,mdat:da,sidx:fr,trak:pa,mdia:ga,mfhd:Ta,tkhd:va,traf:Ia,tfhd:Ea,tfdt:xa,trun:Pa,minf:Sa,sv3d:ha,st3d:fa,prhd:ma,proj:ya,equi:ba,uuid:na,unknown:ni},vt=class a{constructor(e={}){this.options=x({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=zL[e];return r?new r(t,new a):new ni(t,new a)}};var Ut=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var JL=new TextDecoder("ascii"),XL=a=>JL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ZL=a=>{let e=new fr(a,new vt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},eM=(a,e)=>{let r=new vt().parse(a),i=new Ut(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},tM=a=>{let t=new vt().parse(a),r=new Ut(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},rM=a=>{var i;let t=new vt().parse(a);return(i=new Ut(t).find("sidx"))==null?void 0:i.timescale},iM=(a,e)=>{let r=new vt().parse(a),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},aM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new vt().parse(a),i=new Ut(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},mS={validateData:XL,parseInit:aM,getIndexRange:()=>{},parseSegments:ZL,parseFeedableSegmentChunk:eM,getChunkEndTime:iM,getServerLatencyTimestamps:tM,getTimescaleFromIndex:rM};var Aa=_(Je(),1);import{assertNonNullable as kl,isNonNullable as SS,isNullable as nM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as sM}from"@vkontakte/videoplayer-shared/es2015";var bS={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"}},gS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=wa(a,t),i=r in bS,s=i?bS[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=wa(u),d=l*it(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},wa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return wa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:sM(e)}},mr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=gS(r);if(!e(i))return;i.type==="master"&&mr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},vS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=gS(a);return mr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(r=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var yS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],oM=[231,22612,22743,167,171,163,160,175],uM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return mr(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ze(f,h);l=wa(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ze(f,h):p===17545?i=Ze(f,h):p===21420&&l===475249515?u=Ze(f,h):p===374648427?mr(f,({tag:g,type:S,value:v})=>g===30321?(c=Ze(v,S)===1,!1):!0):s&&n&&(0,Aa.default)(yS,p)&&(o=!0),!o}),kl(e,"Failed to parse webm Segment start"),kl(t,"Failed to parse webm Segment end"),kl(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},lM=a=>{if(nM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},cM=(a,e)=>{let t=!1,r=!1,i=o=>SS(o.time)&&SS(o.position),s=[],n;return mr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,Aa.default)(yS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},dM=a=>{let e=0,t=!1;try{mr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Aa.default)(oM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Aa.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},TS={validateData:vS,parseInit:uM,getIndexRange:lM,parseSegments:cM,parseFeedableSegmentChunk:dM};var ka=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return TS;case"mp4":return mS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Fl=_(qS(),1),hy=_(Ur(),1),fy=_(iy(),1),my=_(ti(),1),ql=_(Zr(),1);var ay=_(Je(),1),Dl=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,ay.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as uC,isNullable as dy}from"@vkontakte/videoplayer-shared/es2015";var sy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var ny=a=>{var e;try{let t=nC(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function nC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
63
63
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
64
64
|
(-(?<script>[a-z]{4}))?
|
|
65
65
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
66
66
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
67
67
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
68
68
|
(?:-(?<privateuse>(?:${e})))?
|
|
69
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var ry=a=>{if(!a.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},gt=(a,e)=>{let t=a;t=(0,Rl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,iy.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Rl.default)(t,n,(o,u)=>ty(s)?o:ty(u)?s:(0,ay.default)(s,parseInt(u,10),"0"))}return t},ny=(a,e)=>{var E,$,D,z,N,O,q,R,j,L,W,w,T,_,V,ie,Oe,yt,vr,H,le,ce,Ve,Tt,Sr,It,Qt,yr,ni,cc,dc,pc,hc,fc,mc,bc,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc,Cc,Dc,Oc,Vc,Bc,_c,Nc,Fc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(de=>{var Wa,Et;return(Et=(Wa=de.textContent)==null?void 0:Wa.trim())!=null?Et:""}),u=(E=(0,sy.default)(o,0))!=null?E:"",l=n.children,d=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),p=c?new Date(c).getTime():void 0,h,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)h=ry(f);else if(b){let de=ry(b);ey(de)&&(h=de)}else S&&(h=parseInt(S,10));let v=0,y=(D=($=s.getAttribute("profiles"))==null?void 0:$.split(","))!=null?D:[];for(let de of l){let Wa=(z=de.getAttribute("id"))!=null?z:"id"+(v++).toString(10),Et=(N=de.getAttribute("mimeType"))!=null?N:"",Fn=(O=de.getAttribute("codecs"))!=null?O:"",qn=(q=de.getAttribute("contentType"))!=null?q:Et==null?void 0:Et.split("/")[0],wT=(j=(R=de.getAttribute("profiles"))==null?void 0:R.split(","))!=null?j:[],qc=(W=ZS((L=de.getAttribute("lang"))!=null?L:""))!=null?W:{},kT=(_=(T=(w=de.querySelector("Label"))==null?void 0:w.textContent)==null?void 0:T.trim())!=null?_:void 0,RT=de.querySelectorAll("Representation"),$T=de.querySelector("SegmentTemplate"),LT=(ie=(V=de.querySelector("Role"))==null?void 0:V.getAttribute("value"))!=null?ie:void 0,oi=qn,ae={id:Wa,language:qc.language,isDefault:LT==="main",label:kT,codecs:Fn,hdr:oi==="video"&&kl(Fn),mime:Et,representations:[]};for(let K of RT){let MT=(Oe=K.getAttribute("lang"))!=null?Oe:void 0,CT=(yt=K.getAttribute("label"))!=null?yt:void 0,DT=(le=(H=(vr=K.querySelector("BaseURL"))==null?void 0:vr.textContent)==null?void 0:H.trim())!=null?le:"",Ya=new URL(DT||u,e).toString(),Tr=(ce=K.getAttribute("mimeType"))!=null?ce:Et,za=(Tt=(Ve=K.getAttribute("codecs"))!=null?Ve:Fn)!=null?Tt:"",Ka;if(qn==="text"){let xt=K.getAttribute("id")||"",Ja=((Sr=qc.privateuse)==null?void 0:Sr.includes("x-auto"))||xt.includes("_auto"),Wt=K.querySelector("SegmentTemplate");if(Wt){let ui={representationId:(It=K.getAttribute("id"))!=null?It:void 0,bandwidth:(Qt=K.getAttribute("bandwidth"))!=null?Qt:void 0},Xa=parseInt((yr=K.getAttribute("bandwidth"))!=null?yr:"",10)/1e3,Za=(cc=parseInt((ni=Wt.getAttribute("startNumber"))!=null?ni:"",10))!=null?cc:1,Ir=parseInt((dc=Wt.getAttribute("timescale"))!=null?dc:"",10),Un=(pc=Wt.querySelectorAll("SegmentTimeline S"))!=null?pc:[],Er=Wt.getAttribute("media");if(!Er)continue;let es=[],ts=0,rs="",xr=0,li=Za,me=0;for(let je of Un){let Yt=parseInt((hc=je.getAttribute("d"))!=null?hc:"",10),Be=parseInt((fc=je.getAttribute("r"))!=null?fc:"",10)||0,Pt=parseInt((mc=je.getAttribute("t"))!=null?mc:"",10);me=Number.isFinite(Pt)?Pt:me;let zt=Yt/Ir*1e3,At=me/Ir*1e3;for(let Xe=0;Xe<Be+1;Xe++){let wt=gt(Er,M(P({},ui),{segmentNumber:li.toString(10),segmentTime:(me+Xe*Yt).toString(10)})),Pr=(At!=null?At:0)+Xe*zt,di=Pr+zt;li++,es.push({time:{from:Pr,to:di},url:wt})}me+=(Be+1)*Yt,ts+=(Be+1)*zt}xr=me/Ir*1e3,rs=gt(Er,M(P({},ui),{segmentNumber:li.toString(10),segmentTime:me.toString(10)}));let ci={time:{from:xr,to:1/0},url:rs},ut={type:"template",baseUrl:Ya,segmentTemplateUrl:Er,initUrl:"",totalSegmentsDurationMs:ts,segments:es,nextSegmentBeyondManifest:ci,timescale:Ir};Ka={id:xt,kind:"text",segmentReference:ut,profiles:[],duration:h,bitrate:Xa,mime:"",codecs:"",width:0,height:0,isAuto:Ja}}else Ka={id:xt,isAuto:Ja,kind:"text",url:Ya}}else{let xt=(gc=(bc=K.getAttribute("contentType"))!=null?bc:Tr==null?void 0:Tr.split("/")[0])!=null?gc:qn,Ja=(Sc=(vc=de.getAttribute("profiles"))==null?void 0:vc.split(","))!=null?Sc:[],Wt=parseInt((yc=K.getAttribute("width"))!=null?yc:"",10),ui=parseInt((Tc=K.getAttribute("height"))!=null?Tc:"",10),Xa=parseInt((Ic=K.getAttribute("bandwidth"))!=null?Ic:"",10)/1e3,Za=(Ec=K.getAttribute("frameRate"))!=null?Ec:"",Ir=(xc=K.getAttribute("quality"))!=null?xc:void 0,Un=Za?XS(Za):void 0,Er=(Pc=K.getAttribute("id"))!=null?Pc:"id"+(v++).toString(10),es=xt==="video"?`${ui}p`:xt==="audio"?`${Xa}Kbps`:za,ts=`${Er}@${es}`,rs=[...y,...wT,...Ja],xr,li=K.querySelector("SegmentBase"),me=(Ac=K.querySelector("SegmentTemplate"))!=null?Ac:$T;if(li){let ut=(kc=(wc=K.querySelector("SegmentBase Initialization"))==null?void 0:wc.getAttribute("range"))!=null?kc:"",[je,Yt]=ut.split("-").map(wt=>parseInt(wt,10)),Be={from:je,to:Yt},Pt=(Rc=K.querySelector("SegmentBase"))==null?void 0:Rc.getAttribute("indexRange"),[zt,At]=Pt?Pt.split("-").map(wt=>parseInt(wt,10)):[],Xe=Pt?{from:zt,to:At}:void 0;xr={type:"byteRange",url:Ya,initRange:Be,indexRange:Xe}}else if(me){let ut={representationId:($c=K.getAttribute("id"))!=null?$c:void 0,bandwidth:(Lc=K.getAttribute("bandwidth"))!=null?Lc:void 0},je=parseInt((Mc=me.getAttribute("timescale"))!=null?Mc:"",10),Yt=(Cc=me.getAttribute("initialization"))!=null?Cc:"",Be=me.getAttribute("media"),Pt=(Oc=parseInt((Dc=me.getAttribute("startNumber"))!=null?Dc:"",10))!=null?Oc:1,zt=gt(Yt,ut);if(!Be)throw new ReferenceError("No media attribute in SegmentTemplate");let At=(Vc=me.querySelectorAll("SegmentTimeline S"))!=null?Vc:[],Xe=[],wt=0,Pr="",di=0;if(At.length){let is=Pt,Ge=0;for(let Ar of At){let Ze=parseInt((Bc=Ar.getAttribute("d"))!=null?Bc:"",10),Kt=parseInt((_c=Ar.getAttribute("r"))!=null?_c:"",10)||0,as=parseInt((Nc=Ar.getAttribute("t"))!=null?Nc:"",10);Ge=Number.isFinite(as)?as:Ge;let Hn=Ze/je*1e3,jn=Ge/je*1e3;for(let ss=0;ss<Kt+1;ss++){let VT=gt(Be,M(P({},ut),{segmentNumber:is.toString(10),segmentTime:(Ge+ss*Ze).toString(10)})),Uc=(jn!=null?jn:0)+ss*Hn,BT=Uc+Hn;is++,Xe.push({time:{from:Uc,to:BT},url:VT})}Ge+=(Kt+1)*Ze,wt+=(Kt+1)*Hn}di=Ge/je*1e3,Pr=gt(Be,M(P({},ut),{segmentNumber:is.toString(10),segmentTime:Ge.toString(10)}))}else if(ey(h)){let Ge=parseInt((Fc=me.getAttribute("duration"))!=null?Fc:"",10)/je*1e3,Ar=Math.ceil(h/Ge),Ze=0;for(let Kt=1;Kt<Ar;Kt++){let as=gt(Be,M(P({},ut),{segmentNumber:Kt.toString(10),segmentTime:Ze.toString(10)}));Xe.push({time:{from:Ze,to:Ze+Ge},url:as}),Ze+=Ge}di=Ze,Pr=gt(Be,M(P({},ut),{segmentNumber:Ar.toString(10),segmentTime:Ze.toString(10)}))}let OT={time:{from:di,to:1/0},url:Pr};xr={type:"template",baseUrl:Ya,segmentTemplateUrl:Be,initUrl:zt,totalSegmentsDurationMs:wt,segments:Xe,nextSegmentBeyondManifest:OT,timescale:je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!xt||!Tr)continue;let ci={video:"video",audio:"audio",text:"text"}[xt];if(!ci)continue;oi||(oi=ci),Ka={id:ts,kind:ci,segmentReference:xr,profiles:rs,duration:h,bitrate:Xa,mime:Tr,codecs:za,width:Wt,height:ui,fps:Un,quality:Ir}}ae.language||(ae.language=MT),ae.label||(ae.label=CT),ae.mime||(ae.mime=Tr),ae.codecs||(ae.codecs=za),ae.hdr||(ae.hdr=oi==="video"&&kl(za)),ae.representations.push(Ka)}oi&&i[oi].push(ae)}return{dynamic:d,liveAvailabilityStartTime:p,duration:h,streams:i,baseUrls:o}};var Ml=F(Yr(),1);import{videoSizeToQuality as rC}from"@vkontakte/videoplayer-shared/es2015";var oy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ot(s):void 0)!=null?u:rC({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},uy=({id:a,bitrate:e})=>({id:a,bitrate:e}),ly=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),cy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Cl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ml.default)(r.split("."),0),isDefault:i}),Dl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ml.default)(i.split("."),0)}),Ol=a=>"url"in a,Ce=a=>a.type==="template",Ia=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Ea=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ti(0);this.currentSegmentLength$=new ti(0);this.onLastSegment$=new ti(!1);this.fullyBuffered$=new ti(!1);this.playingRepresentation$=new ti(void 0);this.playingRepresentationInit$=new ti(void 0);this.error$=new aC;this.gaps=[];this.subscription=new sC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Me;this.switchAbortController=new Me;this.destroyAbortController=new Me;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=dr(this.destroyAbortController.signal,function(e){return re(this,null,function*(){let t=this.representations.get(e);ge(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new oS(this.sourceBuffer),this.subscription.add(Vl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Vl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ft.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,yl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=nt(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ge(r,"No init buffer for starting representation"),ge(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=dr(this.destroyAbortController.signal,function(e,t=!1){return re(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);ge(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(He(s)||He(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ge(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(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();pn(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Wn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=dr(this.destroyAbortController.signal,function(e){return re(this,null,function*(){var u,l;let t=(u=(0,mn.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 p=this.representations.get(d);if(!p||!Ce(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);ge(i);let s=this.segments.get(r);ge(s,"No segments for starting representation");let n=this.initData.get(r);if(ge(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var d;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Me,dr(this.switchAbortController.signal,function(r,i=!1){return re(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);ge(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(He(o)||He(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),ge(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();pn(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,d;if(He(e)||He(this.downloadingRepresentationId)||He(this.playingRepresentationId)||He(this.sourceBuffer)||pn(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ge(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((d=i==null?void 0:i.time.from)!=null?d:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=nt(this.sourceBuffer.buffered,e),h=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=i.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&yl(this.sourceBuffer.buffered)>=this.bufferLimit){let c=nt(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,fn.default)(o,i))c="high";else{let p=(0,ri.default)(o,0);p&&p.time.from-i.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&nt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ri.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;pn(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,mn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,mn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Ce(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>M(P({},p),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ri.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,c=u==null?void 0:u.findIndex(p=>Math.floor(d)>=Math.floor(p.time.from)&&Math.floor(d)<=Math.floor(p.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(c+1);this.segments.set(o.id,[...l,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ge(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Ce(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=gt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&Xi&&Xi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Xi&&Xi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:c,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=r+S||h<=r+S;return(c==="none"||c==="partially_ejected"&&g&&v&&this.sourceBuffer&&!(_t(this.sourceBuffer.buffered,p)&&_t(this.sourceBuffer.buffered,h)))&&g&&v});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=i;c<s.length&&(n<=l||o<=d);c++){let p=s[c];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return k(this,null,function*(){Ce(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return k(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield dr(o,function(){return re(this,null,function*(){let d=Bl(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:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=hn(),!d)return;let c=new DataView(d),p=Ta(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(c,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),Ia(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())Ce(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return k(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield dr(n,function(){return re(this,null,function*(){let u=Bl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Vl(window,"online").pipe(iC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=hn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ia(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Ce(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ri.default)(e,0).byte.from,to:(0,ri.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=hn(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ce(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=hn();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,fn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return k(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=Ta(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 k(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:d}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let c=d.byte.from-r,p=d.byte.to-r,h=p-c+1,f=c<i,b=p<=i;if(!f)continue;let g=Ta(u.mime);if(d.status==="downloading"&&b){d.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-c),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===h?S:g.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(d.status="partially_fed",l.feedingBytes+=v.byteLength,(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?(l.fedBytes+=v.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(ge(this.sourceBuffer),_t(this.sourceBuffer.buffered,e.segment.time.from,100)&&_t(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Ft.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ol(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");ge(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=gl(()=>(0,dy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return k(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?dr(this.destroyAbortController.signal,function(){return re(this,null,function*(){let o=Bl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ta(e.mime),i)).then(o=>k(this,null,function*(){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 p=d;this.isLive&&Ce(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ft.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return k(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return k(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||He(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,p):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return i;i.push(P({},u.time)),i=n(i);let l=Ol(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let h of p)(0,fn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||He(e)?0:nt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){ge(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=gl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ft.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(He(this.sourceBuffer)||He(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(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?i.status="partially_ejected":this.gaps.some(d=>d.from===i.time.from||d.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var xa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var py=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Pa,assertNever as fy,fromEvent as my,merge as nC,now as Aa,Subscription as oC,ValueSubject as _l,flattenObject as ii}from"@vkontakte/videoplayer-shared/es2015";var hy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var bn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new _l(void 0);this.lastConnectionReused$=new _l(void 0);this.lastRequestFirstBytes$=new _l(void 0);this.abortAllController=new Me;this.subscription=new oC;this.fetchManifest=Pa(this.abortAllController.signal,function(e){return re(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=xa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=hy(r));let i=yield ft(r,{signal:this.abortAllController.signal}).catch(wa);return i?(t.log("success",ii({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ii({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Pa(this.abortAllController.signal,function(l){return re(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,j;let d=e,c=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(d,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),d=L.toString();break}default:fy(t)}this.requestQuic&&(d=xa(d));let h=this.abortAllController.signal,f;if(n){let L=new Me;if(f=nC(my(this.abortAllController.signal,"abort"),my(n,"abort")).subscribe(()=>{try{L.abort()}catch(W){wa(W)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(W){wa(W)}h=L.signal}let b=Aa();p.log("startRequest",ii({url:d,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield ft(d,{priority:s,headers:c,signal:h}).catch(wa),S=Aa();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(S-b),!g.ok||!g.body){f==null||f.unsubscribe();let L=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:L}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let L=Aa(),W={requestStartedAt:b,requestEndedAt:L,duration:L-b};return p.log("endRequest",ii(W)),p.end(),g.arrayBuffer()}let[v,y]=g.body.tee(),I=v.getReader();o&&((j=this.throughputEstimator)==null||j.trackStream(y,u));let E=0,$=new Uint8Array(0),D=!1,z=L=>{f==null||f.unsubscribe(),D=!0,wa(L)},N=Pa(h,function(w){return re(this,arguments,function*({done:L,value:W}){if(E===0&&this.lastRequestFirstBytes$.next(Aa()-b),h.aborted){f==null||f.unsubscribe();return}if(!L&&W){let T=new Uint8Array($.length+W.length);T.set($),T.set(W,$.length),$=T,E+=W.byteLength,i==null||i(new DataView($.buffer),E),yield I==null?void 0:I.read().then(N,z)}})}.bind(this));yield I==null?void 0:I.read().then(N,z),f==null||f.unsubscribe();let O=Aa(),q={failed:D,requestStartedAt:b,requestEndedAt:O,duration:O-b};return D?(p.error("endRequest",ii(q)),p.end(),null):(p.log("endRequest",ii(q)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Pa(this.abortAllController.signal,function(e,t,r){return re(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!c)return null;let p=new DataView(c,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(c),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Pa(this.abortAllController.signal,function(e,t){return re(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>M(P({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=py(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return k(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:fy(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},wa=a=>{if(!Ia(a))throw a};var pr=(a,e,t)=>t*e+(1-t)*a,Nl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,by=(a,e,t,r)=>{let i=0,s=t,n=Nl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as uC,ValueSubject as gy}from"@vkontakte/videoplayer-shared/es2015";var qt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new gy(e.initial),this.debounced$=new gy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=et(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(uC(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 gn=class extends qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=pr(this.slow,e,this.params.emaAlphaSlow),this.fast=pr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var vn=class extends qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Nl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pr(this.emaSmoothed,e,this.params.emaAlpha);let r=by(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Sn=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?pr(this.smoothed,t,this.params.emaAlpha):t}};var hr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new gn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new vn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Sn(P({initial:e,label:"liveEdgeDelay"},t))}};var Fl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as lC,ValueSubject as cC}from"@vkontakte/videoplayer-shared/es2015";var ka=class a{constructor(e,t){this.currentRepresentation$=new cC(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 r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(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(M(P({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ce(t.segmentReference))}};var vC=["timeupdate","progress","play","seeked","stalled","waiting"],SC=["timeupdate","progress","loadeddata","playing","seeked"];var Tn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ty;this.representationSubscription=new Ty;this.state$=new C("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new yy;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.liveDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.isLowLatency$=new ee(!1);this.isActiveLowLatency$=new ee(!1);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new yy;this.gapWatchdogActive=!1;this.destroyController=new Me;this.initManifest=ql(this.destroyController.signal,function(e,t,r){return re(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=fe(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ut.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ql(this.destroyController.signal,function(){return re(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:Ut.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=ny(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=tS(e))!=null?n:{id:"ManifestParsing",category:Ut.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,d)=>{var c,p,h,f;return!!((p=(c=this.element)==null?void 0:c.canPlayType)!=null&&p.call(c,l)&&((f=(h=mt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${d}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),c=new Set(d.map(({codecs:h})=>h)),p=Cv(c);if(p&&(i[u]=d.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);hC.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=M(P({},t),{streams:i});return this.tracer.log("updateManifestEnd",$a(s)),s})}.bind(this));this.initRepresentations=ql(this.destroyController.signal,function(e,t,r){return re(this,null,function*(){var p;this.tracer.log("initRepresentationsStart",$a({initialVideo:e,initialAudio:t,sourceHls:r})),fr(this.manifest),fr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=h=>{this.representationSubscription.add(mr(h,"error").pipe(yn(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?bv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&en())if(r){let h=document.createElement("source");i(h),h.type="application/x-mpegurl",h.src=r.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((h,f)=>[...h,...f.representations],[]);if(this.videoBufferManager=new Ea("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Sy(t)){let h=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new Ea("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}ka.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ka(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Hl(1e3).subscribe(h=>{var f;if((f=this.element)!=null&&f.paused){let b=Us(this.manifestUrlString,2);this.manifestUrlString=fe(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(br(...SC.map(h=>mr(this.element,h))).pipe(La(h=>this.element?nt(this.element.buffered,this.element.currentTime*1e3):0),Ul(),bC(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(br(mr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ul()).subscribe(f=>Fl(this.element,1))),this.representationSubscription.add(Ra({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(yn(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(Ra({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(yn(({isLive:f})=>f),La(f=>P({},f)),Ul((f,b)=>b.bufferLength<f.bufferLength),La(({rtt:f,bufferLength:b,segmentServerLatency:g})=>{let S=Us(this.manifestUrlString,2);return(f/2+b+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ra({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=f-g,I=1;Math.abs(y)>S&&(I=1+Math.sign(y)*v),Fl(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let b=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var E,$;return($=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?$:v}))-v}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let h=0;this.representationSubscription.add(Ra({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gC(1e3)).subscribe(g=>k(this,[g],function*({liveLoadBufferLength:f,bufferLength:b}){if(fr(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,v=Us(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,D=isFinite(f)?f:b,z=this.isActiveLowLatency$.getValue(),N=y<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(z&&N);let O="none";if(z?O="active_low_latency":this.isLowLatency$.getValue()&&N?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(q=>q.proceedLowLatencyLive()),O="active_low_latency"):v!==0&&D<I?O="live_forward_buffering":D<I+$&&(O="live_with_target_offset"),isFinite(f)&&(h=f>h?f:h),O==="live_forward_buffering"||O==="live_with_target_offset"){let q=h-(I+E),R=this.normolizeLiveOffset(Math.trunc(v+q/S)),j=Math.abs(R-v),L;!f||j<=this.tuning.dashCmafLive.offsetCalculationError?L=v:R>0&&j>this.tuning.dashCmafLive.offsetCalculationError?L=R:L=0,this.manifestUrlString=fe(this.manifestUrlString,L,2)}O!=="none"&&O!=="active_low_latency"&&(h=0,this.updateLive())})))}let l=br(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(La(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=br(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(La(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add(br(this.forceEnded$,Ra({allBuffersFull:l,someBufferEnded:d}).pipe(yn(({allBuffersFull:h,someBufferEnded:f})=>h&&f))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(h=this.source)==null||h.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(br(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(h=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",h)}));let c=[(p=this.manifest.duration)!=null?p:0,...(0,jl.default)((0,jl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Ce(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&Sy(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Hl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Ut.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new bn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=hr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,P({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return k(this,null,function*(){var r,i,s;fr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=fe(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){fr(this.element),this.state$.setState("running"),this.subscription.add(br(...vC.map(e=>mr(this.element,e)),mr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ut.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(mr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(mr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&_t(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,S,v,y,I,E,$;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=mC(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?v:0,d=(I=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,c=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let D=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(D),($=this.audioBufferManager)==null||$.maintain(D),i.position=D}this.tracer.log("stallIntervalCallback",$a(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Hl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Ut.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return k(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u;fr(this.element),fr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),_t(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",$a({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=fC(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return k(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=M(P({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",$a(t)))}}};var In=class{constructor(e,t){this.fov=e,this.orientation=t}};var En=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/et(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=P({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*et(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Iy=`attribute vec2 a_vertex;
|
|
69
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Bl=_(ti(),1);import{videoSizeToQuality as oC}from"@vkontakte/videoplayer-shared/es2015";var oy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?_t(s):void 0)!=null?u:oC({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},uy=({id:a,bitrate:e})=>({id:a,bitrate:e}),ly=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),cy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Vl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Bl.default)(r.split("."),0),isDefault:i}),_l=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Bl.default)(i.split("."),0)}),Nl=a=>"url"in a,ge=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var py=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},St=(a,e)=>{let t=a;t=(0,Fl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,hy.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Fl.default)(t,n,(o,u)=>dy(s)?o:dy(u)?s:(0,fy.default)(s,parseInt(u,10),"0"))}return t},by=(a,e)=>{var E,$,D,J,L,F,q,R,U,N,W,A,T,V,O,se,Ve,It,xr,j,ce,de,_e,Et,Pr,xt,zt,wr,hi,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,wc,Ac,kc,Rc,$c,Lc,Mc,Cc,Dc,Oc,Bc,Vc,_c,Nc,Fc,qc,Uc,Hc,jc,Gc,Qc,Wc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Ge=>{var K,Kt;return(Kt=(K=Ge.textContent)==null?void 0:K.trim())!=null?Kt:""}),o=(E=(0,my.default)(n,0))!=null?E:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],f=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((Ge,K)=>M(x({},Ge),{[K.id]:K.children}),{}),S=b.reduce((Ge,K)=>M(x({},Ge),{[K.id]:K.getAttribute("duration")}),{});p?d=py(p):(0,ql.default)(S).filter(Ge=>Ge).length&&!u?d=(0,ql.default)(S).reduce((Ge,K)=>{var Kt;return Ge+((Kt=py(K))!=null?Kt:0)},0):f&&(d=parseInt(f,10));let v=0,y=(D=($=s.getAttribute("profiles"))==null?void 0:$.split(","))!=null?D:[];for(let Ge of b.map(K=>K.id))for(let K of g[Ge]){let Kt=(J=K.getAttribute("id"))!=null?J:"id"+(v++).toString(10),fi=(L=K.getAttribute("mimeType"))!=null?L:"",Qn=(F=K.getAttribute("codecs"))!=null?F:"",Wn=(q=K.getAttribute("contentType"))!=null?q:fi==null?void 0:fi.split("/")[0],OT=(U=(R=K.getAttribute("profiles"))==null?void 0:R.split(","))!=null?U:[],Yc=(W=ny((N=K.getAttribute("lang"))!=null?N:""))!=null?W:{},BT=(V=(T=(A=K.querySelector("Label"))==null?void 0:A.textContent)==null?void 0:T.trim())!=null?V:void 0,VT=K.querySelectorAll("Representation"),_T=K.querySelector("SegmentTemplate"),NT=(se=(O=K.querySelector("Role"))==null?void 0:O.getAttribute("value"))!=null?se:void 0,Ar=Wn,ee={id:Kt,language:Yc.language,isDefault:NT==="main",label:BT,codecs:Qn,hdr:Ar==="video"&&Dl(Qn),mime:fi,representations:[]};for(let Y of VT){let Pt=(Ve=Y.getAttribute("lang"))!=null?Ve:void 0,mi=(It=Y.getAttribute("label"))!=null?It:void 0,ts=(ce=(j=(xr=Y.querySelector("BaseURL"))==null?void 0:xr.textContent)==null?void 0:j.trim())!=null?ce:"",Jt=new URL(ts||o,e).toString(),wt=(de=Y.getAttribute("mimeType"))!=null?de:fi,rs=(Et=(_e=Y.getAttribute("codecs"))!=null?_e:Qn)!=null?Et:"",is;if(Wn==="text"){let At=Y.getAttribute("id")||"",as=((Pr=Yc.privateuse)==null?void 0:Pr.includes("x-auto"))||At.includes("_auto"),Xt=Y.querySelector("SegmentTemplate");if(Xt){let bi={representationId:(xt=Y.getAttribute("id"))!=null?xt:void 0,bandwidth:(zt=Y.getAttribute("bandwidth"))!=null?zt:void 0},ss=parseInt((wr=Y.getAttribute("bandwidth"))!=null?wr:"",10)/1e3,ns=(gc=parseInt((hi=Xt.getAttribute("startNumber"))!=null?hi:"",10))!=null?gc:1,kr=parseInt((vc=Xt.getAttribute("timescale"))!=null?vc:"",10),Yn=(Sc=Xt.querySelectorAll("SegmentTimeline S"))!=null?Sc:[],Rr=Xt.getAttribute("media");if(!Rr)continue;let os=[],us=0,ls="",$r=0,gi=ns,me=0;for(let Qe of Yn){let Zt=parseInt((yc=Qe.getAttribute("d"))!=null?yc:"",10),Ne=parseInt((Tc=Qe.getAttribute("r"))!=null?Tc:"",10)||0,kt=parseInt((Ic=Qe.getAttribute("t"))!=null?Ic:"",10);me=Number.isFinite(kt)?kt:me;let er=Zt/kr*1e3,Rt=me/kr*1e3;for(let tt=0;tt<Ne+1;tt++){let $t=St(Rr,M(x({},bi),{segmentNumber:gi.toString(10),segmentTime:(me+tt*Zt).toString(10)})),Lr=(Rt!=null?Rt:0)+tt*er,Si=Lr+er;gi++,os.push({time:{from:Lr,to:Si},url:$t})}me+=(Ne+1)*Zt,us+=(Ne+1)*er}$r=me/kr*1e3,ls=St(Rr,M(x({},bi),{segmentNumber:gi.toString(10),segmentTime:me.toString(10)}));let vi={time:{from:$r,to:1/0},url:ls},ct={type:"template",baseUrl:Jt,segmentTemplateUrl:Rr,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:vi,timescale:kr};is={id:At,kind:"text",segmentReference:ct,profiles:[],duration:d,bitrate:ss,mime:"",codecs:"",width:0,height:0,isAuto:as}}else is={id:At,isAuto:as,kind:"text",url:Jt}}else{let At=(xc=(Ec=Y.getAttribute("contentType"))!=null?Ec:wt==null?void 0:wt.split("/")[0])!=null?xc:Wn,as=(wc=(Pc=K.getAttribute("profiles"))==null?void 0:Pc.split(","))!=null?wc:[],Xt=parseInt((Ac=Y.getAttribute("width"))!=null?Ac:"",10),bi=parseInt((kc=Y.getAttribute("height"))!=null?kc:"",10),ss=parseInt((Rc=Y.getAttribute("bandwidth"))!=null?Rc:"",10)/1e3,ns=($c=Y.getAttribute("frameRate"))!=null?$c:"",kr=(Lc=Y.getAttribute("quality"))!=null?Lc:void 0,Yn=ns?sy(ns):void 0,Rr=(Mc=Y.getAttribute("id"))!=null?Mc:"id"+(v++).toString(10),os=At==="video"?`${bi}p`:At==="audio"?`${ss}Kbps`:rs,us=`${Rr}@${os}`,ls=[...y,...OT,...as],$r,gi=Y.querySelector("SegmentBase"),me=(Cc=Y.querySelector("SegmentTemplate"))!=null?Cc:_T;if(gi){let ct=(Oc=(Dc=Y.querySelector("SegmentBase Initialization"))==null?void 0:Dc.getAttribute("range"))!=null?Oc:"",[Qe,Zt]=ct.split("-").map($t=>parseInt($t,10)),Ne={from:Qe,to:Zt},kt=(Bc=Y.querySelector("SegmentBase"))==null?void 0:Bc.getAttribute("indexRange"),[er,Rt]=kt?kt.split("-").map($t=>parseInt($t,10)):[],tt=kt?{from:er,to:Rt}:void 0;$r={type:"byteRange",url:Jt,initRange:Ne,indexRange:tt}}else if(me){let ct={representationId:(Vc=Y.getAttribute("id"))!=null?Vc:void 0,bandwidth:(_c=Y.getAttribute("bandwidth"))!=null?_c:void 0},Qe=parseInt((Nc=me.getAttribute("timescale"))!=null?Nc:"",10),Zt=(Fc=me.getAttribute("initialization"))!=null?Fc:"",Ne=me.getAttribute("media"),kt=(Uc=parseInt((qc=me.getAttribute("startNumber"))!=null?qc:"",10))!=null?Uc:1,er=St(Zt,ct);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Rt=(Hc=me.querySelectorAll("SegmentTimeline S"))!=null?Hc:[],tt=[],$t=0,Lr="",Si=0;if(Rt.length){let cs=kt,We=0;for(let Mr of Rt){let rt=parseInt((jc=Mr.getAttribute("d"))!=null?jc:"",10),tr=parseInt((Gc=Mr.getAttribute("r"))!=null?Gc:"",10)||0,ds=parseInt((Qc=Mr.getAttribute("t"))!=null?Qc:"",10);We=Number.isFinite(ds)?ds:We;let zn=rt/Qe*1e3,Kn=We/Qe*1e3;for(let ps=0;ps<tr+1;ps++){let qT=St(Ne,M(x({},ct),{segmentNumber:cs.toString(10),segmentTime:(We+ps*rt).toString(10)})),zc=(Kn!=null?Kn:0)+ps*zn,UT=zc+zn;cs++,tt.push({time:{from:zc,to:UT},url:qT})}We+=(tr+1)*rt,$t+=(tr+1)*zn}Si=We/Qe*1e3,Lr=St(Ne,M(x({},ct),{segmentNumber:cs.toString(10),segmentTime:We.toString(10)}))}else if(uC(d)){let We=parseInt((Wc=me.getAttribute("duration"))!=null?Wc:"",10)/Qe*1e3,Mr=Math.ceil(d/We),rt=0;for(let tr=1;tr<Mr;tr++){let ds=St(Ne,M(x({},ct),{segmentNumber:tr.toString(10),segmentTime:rt.toString(10)}));tt.push({time:{from:rt,to:rt+We},url:ds}),rt+=We}Si=rt,Lr=St(Ne,M(x({},ct),{segmentNumber:Mr.toString(10),segmentTime:rt.toString(10)}))}let FT={time:{from:Si,to:1/0},url:Lr};$r={type:"template",baseUrl:Jt,segmentTemplateUrl:Ne,initUrl:er,totalSegmentsDurationMs:$t,segments:tt,nextSegmentBeyondManifest:FT,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!At||!wt)continue;let vi={video:"video",audio:"audio",text:"text"}[At];if(!vi)continue;Ar||(Ar=vi),is={id:us,kind:vi,segmentReference:$r,profiles:ls,duration:d,bitrate:ss,mime:wt,codecs:rs,width:Xt,height:bi,fps:Yn,quality:kr}}ee.language||(ee.language=Pt),ee.label||(ee.label=mi),ee.mime||(ee.mime=wt),ee.codecs||(ee.codecs=rs),ee.hdr||(ee.hdr=Ar==="video"&&Dl(rs)),ee.representations.push(is)}if(Ar){let Y=i[Ar].find(Pt=>Pt.id===ee.id);if(Y&&ee.representations.every(Pt=>ge(Pt.segmentReference)))for(let Pt of Y.representations){let mi=ee.representations.find(wt=>wt.id===Pt.id),ts=mi==null?void 0:mi.segmentReference,Jt=Pt.segmentReference;Jt.segments.push(...ts.segments),Jt.nextSegmentBeyondManifest=ts.nextSegmentBeyondManifest}else i[Ar].push(ee)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var vy=_(Je(),1);import{isNonNullable as gy}from"@vkontakte/videoplayer-shared/es2015";var De=(a,e)=>gy(a)&&gy(e)&&a.readyState==="open"&&(0,vy.default)([...a.activeSourceBuffers],e);var La=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gr(0);this.currentLowLatencySegmentLength$=new gr(0);this.currentSegmentLength$=new gr(0);this.onLastSegment$=new gr(!1);this.fullyBuffered$=new gr(!1);this.playingRepresentation$=new gr(void 0);this.playingRepresentationInit$=new gr(void 0);this.error$=new dC;this.gaps=[];this.subscription=new pC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ce;this.switchAbortController=new Ce;this.destroyAbortController=new Ce;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=br(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){let t=this.representations.get(e);Oe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new fS(this.sourceBuffer),this.subscription.add(Hl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ht.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ht.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Hl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ht.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!De(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,wl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ut(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Oe(r,"No init buffer for starting representation"),Oe(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=br(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);Oe(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ae(s)||Ae(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),Oe(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!De(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();$a(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Zn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=br(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){var u,l;let t=(u=(0,Tn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!ge(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);Oe(i);let s=this.segments.get(r);Oe(s,"No segments for starting representation");let n=this.initData.get(r);if(Oe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Ce,br(this.switchAbortController.signal,function(r,i=!1){return ae(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);Oe(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Ae(o)||Ae(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),Oe(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!De(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();$a(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Ae(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return k(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ce,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Ae(e)||Ae(this.downloadingRepresentationId)||Ae(this.playingRepresentationId)||Ae(this.sourceBuffer)||!De(this.mediaSource,this.sourceBuffer)||$a(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Oe(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);$a(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ut(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&wl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ut(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,yn.default)(o,i))l="high";else{let c=(0,ui.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&ut(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ui.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;$a(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,Tn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,Tn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!ge(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>M(x({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ui.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Oe(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!ge(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=St(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&sa&&sa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&sa&&sa(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&v&&this.sourceBuffer&&De(this.mediaSource,this.sourceBuffer)&&!(qt(this.sourceBuffer.buffered,p)&&qt(this.sourceBuffer.buffered,h)))&&g&&v});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return k(this,null,function*(){ge(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return k(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield br(o,function(){return ae(this,null,function*(){let c=jl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Sn(),!c)return;let d=new DataView(c),p=ka(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ra(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())ge(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return k(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield br(n,function(){return ae(this,null,function*(){let u=jl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Hl(window,"online").pipe(cC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=Sn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ge(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ui.default)(e,0).byte.from,to:(0,ui.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Sn(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ge(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Sn();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:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,yn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return k(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=ka(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return k(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(!f)continue;let g=ka(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===h?S:g.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(c.status="partially_fed",l.feedingBytes+=v.byteLength,(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?(l.fedBytes+=v.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(Ae(this.sourceBuffer)||!De(this.mediaSource,this.sourceBuffer))){!this.isLive&&lC.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ht.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",Nl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=El(()=>(0,Sy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return k(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?br(this.destroyAbortController.signal,function(){return ae(this,null,function*(){let o=jl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ka(e.mime),i)).then(o=>k(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&ge(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ht.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return k(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return k(this,null,function*(){if(!this.sourceBuffer||!De(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ae(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(x({},u.time)),i=n(i);let l=Nl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,yn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return k(this,null,function*(){if(!this.sourceBuffer||!De(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||!De(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!De(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ae(e)?0:ut(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!De(this.mediaSource,this.sourceBuffer)))for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){Oe(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=El(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ht.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ae(this.sourceBuffer)||!De(this.mediaSource,this.sourceBuffer)||Ae(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Ma=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var yy=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ca,assertNever as Iy,fromEvent as Ey,merge as hC,now as Da,Subscription as fC,ValueSubject as Gl,flattenObject as li}from"@vkontakte/videoplayer-shared/es2015";var Ty=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var In=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Gl(void 0);this.lastConnectionReused$=new Gl(void 0);this.lastRequestFirstBytes$=new Gl(void 0);this.abortAllController=new Ce;this.subscription=new fC;this.fetchManifest=Ca(this.abortAllController.signal,function(e){return ae(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ma(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Ty(r));let i=yield bt(r,{signal:this.abortAllController.signal}).catch(Oa);return i?(t.log("success",li({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",li({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Ca(this.abortAllController.signal,function(l){return ae(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,U;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let N=new URL(c,location.href);N.searchParams.append("bytes",`${r.from}-${r.to}`),c=N.toString();break}default:Iy(t)}this.requestQuic&&(c=Ma(c));let h=this.abortAllController.signal,f;if(n){let N=new Ce;if(f=hC(Ey(this.abortAllController.signal,"abort"),Ey(n,"abort")).subscribe(()=>{try{N.abort()}catch(W){Oa(W)}}),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(W){Oa(W)}h=N.signal}let b=Da();p.log("startRequest",li({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield bt(c,{priority:s,headers:d,signal:h}).catch(Oa),S=Da();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(S-b),!g.ok||!g.body){f==null||f.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:N}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let N=Da(),W={requestStartedAt:b,requestEndedAt:N,duration:N-b};return p.log("endRequest",li(W)),p.end(),g.arrayBuffer()}let[v,y]=g.body.tee(),I=v.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(y,u));let E=0,$=new Uint8Array(0),D=!1,J=N=>{f==null||f.unsubscribe(),D=!0,Oa(N)},L=Ca(h,function(A){return ae(this,arguments,function*({done:N,value:W}){if(E===0&&this.lastRequestFirstBytes$.next(Da()-b),h.aborted){f==null||f.unsubscribe();return}if(!N&&W){let T=new Uint8Array($.length+W.length);T.set($),T.set(W,$.length),$=T,E+=W.byteLength,i==null||i(new DataView($.buffer),E),yield I==null?void 0:I.read().then(L,J)}})}.bind(this));yield I==null?void 0:I.read().then(L,J),f==null||f.unsubscribe();let F=Da(),q={failed:D,requestStartedAt:b,requestEndedAt:F,duration:F-b};return D?(p.error("endRequest",li(q)),p.end(),null):(p.log("endRequest",li(q)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Ca(this.abortAllController.signal,function(e,t,r){return ae(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ca(this.abortAllController.signal,function(e,t){return ae(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>M(x({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=yy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return k(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Iy(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Oa=a=>{if(!Ra(a))throw a};var vr=(a,e,t)=>t*e+(1-t)*a,Ql=(a,e)=>a.reduce((t,r)=>t+r,0)/e,xy=(a,e,t,r)=>{let i=0,s=t,n=Ql(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as mC,ValueSubject as Py}from"@vkontakte/videoplayer-shared/es2015";var jt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Py(e.initial),this.debounced$=new Py(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=it(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(mC(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 jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vr(this.slow,e,this.params.emaAlphaSlow),this.fast=vr(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 jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ql(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vr(this.emaSmoothed,e,this.params.emaAlpha);let r=xy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Pn=class extends jt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?vr(this.smoothed,t,this.params.emaAlpha):t}};var Sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new En({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new xn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Pn(x({initial:e,label:"liveEdgeDelay"},t))}};var Wl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as bC,ValueSubject as gC}from"@vkontakte/videoplayer-shared/es2015";var Ba=class a{constructor(e,t){this.currentRepresentation$=new gC(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(!bC(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(M(x({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ge(t.segmentReference))}};var PC=["timeupdate","progress","play","seeked","stalled","waiting"],wC=["timeupdate","progress","loadeddata","playing","seeked"];var An=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ry;this.representationSubscription=new Ry;this.state$=new C("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 ky;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.liveDuration$=new re(0);this.liveAvailabilityStartTime$=new re(void 0);this.bufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.isLowLatency$=new re(!1);this.isActiveLowLatency$=new re(!1);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new ky;this.gapWatchdogActive=!1;this.destroyController=new Ce;this.initManifest=Yl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=fe(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Gt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Yl(this.destroyController.signal,function(){return ae(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Gt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=by(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=uS(e))!=null?n:{id:"ManifestParsing",category:Gt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=gt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=Fv(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);yC.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=M(x({},t),{streams:i});return this.tracer.log("updateManifestEnd",_a(s)),s})}.bind(this));this.initRepresentations=Yl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",_a({initialVideo:e,initialAudio:t,sourceHls:r})),yr(this.manifest),yr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Tr(p,"error").pipe(Va(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Gt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Ev():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&un())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new La("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ay(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new La("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$)),this.representationSubscription.add(zl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=zs(this.manifestUrlString,2);this.manifestUrlString=fe(this.manifestUrlString,f+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ir(...wC.map(p=>Tr(this.element,p))).pipe(Na(p=>this.element?ut(this.element.buffered,this.element.currentTime*1e3):0),wn(),EC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ir(Tr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(wn()).subscribe(h=>Wl(this.element,1))),this.representationSubscription.add(ci({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Va(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(ci({isActiveLowLatency:this.isActiveLowLatency$.pipe(wn()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Va(({isActiveLowLatency:h,currentLowLatencySegmentLength:f})=>h&&!!f)).subscribe(({currentLowLatencySegmentLength:h})=>{let f=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(f,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(ci({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Va(({isLive:h})=>h),Na(h=>x({},h)),wn((h,f)=>f.bufferLength<h.bufferLength),Na(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=zs(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ci({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-b,y=1;Math.abs(v)>g&&(y=1+Math.sign(v)*S),Wl(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let S=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(y=>{var I,E;return(E=(I=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?E:S}))-S}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(ci({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(xC(1e3)).subscribe(b=>k(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(yr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=zs(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(h)?h:f,D=this.isActiveLowLatency$.getValue(),J=v<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(D&&J);let L="none";if(D?L="active_low_latency":this.isLowLatency$.getValue()&&J?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),L="active_low_latency"):S!==0&&$<y?L="live_forward_buffering":$<y+E&&(L="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),L==="live_forward_buffering"||L==="live_with_target_offset"){let F=p-(y+I),q=this.normolizeLiveOffset(Math.trunc(S+F/g)),R=Math.abs(q-S),U;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?U=S:q>0&&R>this.tuning.dashCmafLive.offsetCalculationError?U=q:U=0,this.manifestUrlString=fe(this.manifestUrlString,U,2)}L!=="none"&&L!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=Ir(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Na(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Ir(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Na(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(Ir(this.forceEnded$,ci({allBuffersFull:l,someBufferEnded:c}).pipe(Va(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:Gt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ir(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,Kl.default)((0,Kl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),ge(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Ay(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=zl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Gt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new In({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Sr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return k(this,null,function*(){var r,i,s;yr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=fe(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){yr(this.element),this.state$.setState("running"),this.subscription.add(Ir(...PC.map(e=>Tr(this.element,e)),Tr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Gt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Tr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Tr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,S,v,y,I,E,$;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=IC(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?v:0,c=(I=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let D=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(D),($=this.audioBufferManager)==null||$.maintain(D),i.position=D}this.tracer.log("stallIntervalCallback",_a(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=zl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Gt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return k(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){return k(this,null,function*(){var i,s,n,o,u;yr(this.element),yr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),qt(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",_a({requestedPosition:e,forcePrecise:t,position:r}))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=TC(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return k(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=M(x({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",_a(t)))}}};var kn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Rn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/it(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=x({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*it(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var $y=`attribute vec2 a_vertex;
|
|
70
70
|
attribute vec2 a_texel;
|
|
71
71
|
|
|
72
72
|
varying vec2 v_texel;
|
|
@@ -77,7 +77,7 @@ void main(void) {
|
|
|
77
77
|
// save texel vector to pass to fragment shader
|
|
78
78
|
v_texel = a_texel;
|
|
79
79
|
}
|
|
80
|
-
`;var
|
|
80
|
+
`;var Ly=`#ifdef GL_ES
|
|
81
81
|
precision highp float;
|
|
82
82
|
precision highp int;
|
|
83
83
|
#else
|
|
@@ -120,5 +120,5 @@ void main(void) {
|
|
|
120
120
|
// sample using new coordinates
|
|
121
121
|
gl_FragColor = texture2D(u_texture, tc);
|
|
122
122
|
}
|
|
123
|
-
`;var xn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new In(this.params.fov,this.params.orientation),this.cameraRotationManager=new En(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Iy,this.gl.VERTEX_SHADER),r=this.createShader(Ey,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,d=t+i,c=e-r,p=t+i;return[s,n,o,u,l,d,c,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as IC,now as xy,Subscription as EC,filter as xC,combine as Py,ValueSubject as Ay,isNonNullable as PC}from"@vkontakte/videoplayer-shared/es2015";var Gl=class{constructor(){this.isSeeked$=new Ay(!1);this.isBuffering$=new Ay(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new EC}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(Py({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(xC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Py({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(IC(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),d=this.videoLastDataObtainedTimestamp$.getValue(),c=xy(),p=n&&this.currentStallsCount>=n,h=i&&!r&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,f=s&&c-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&c-d>=s+u&&t>=s;(p||h||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,PC(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}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=xy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},wy=Gl;import{combine as AC,map as wC,observeElementSize as kC,Subscription as RC,ValueSubject as Ql,noop as $C}from"@vkontakte/videoplayer-shared/es2015";var Pn=class{constructor(){this.subscription=new RC;this.pipSize$=new Ql(void 0);this.videoSize$=new Ql(void 0);this.elementSize$=new Ql(void 0);this.pictureInPictureWindowRemoveEventListener=$C}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(kC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(AC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(wC(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var gr=class{constructor(e){this.subscription=new _C;this.videoState=new C("stopped");this.textTracksManager=new Ne;this.droppedFramesManager=new Ks;this.stallsManager=new wy;this.elementSizeManager=new Pn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Fi;this.audioTrackSwitchHistory=new Fi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return CC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new xn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ye(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Tn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Ee(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Wl.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){var d;let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ky(c=>!!c.length),$y()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Yl(c=>c.to.state!=="none"),Ca());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ca()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ky(Ry),$y()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Yl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(at(this.video,t.isLooped,i)),this.subscription.add(Ie(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(qe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if(DC(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(Cl(b));let g=[];for(let S of b.representations){let v=uy(S);g.push(v),this.audioTracksMap.set(v,{stream:b,representation:S})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let h=[];for(let f of p.video){h.push(Dl(f));let b=[];for(let g of f.representations){let S=oy(M(P({},g),{streamId:f.id}));S&&(b.push(S),this.videoTracksMap.set(S,{stream:f,representation:g}))}this.videoStreamsMap.set(f,b)}if(this.params.output.availableVideoStreams$.next(h),this.textTracksManager)for(let f of p.text)for(let b of f.representations){let g=ly(f,b);this.textTracksMap.set(g,{stream:f,representation:b})}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())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:Wl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(An(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$,VC(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(!(0,Ly.default)(["manifest_ready","running"],c)||p)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,b]=h,g=[...this.videoTracksMap.keys()].find(v=>{var y;return((y=this.videoTracksMap.get(v))==null?void 0:y.representation.id)===f.id});Ry(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")this.player.initRepresentations(f.id,b==null?void 0:b.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",f.id).catch(o),b){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",b.id,v).catch(o)}},i)),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(Ca()).subscribe(c=>{let p=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=p,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Dl(f))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ca()).subscribe(c=>{let p=[...this.audioTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=p,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===f.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Cl(f))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var p,h;if(c!=null&&c.is3dVideo&&((p=this.params.tuning.spherical)!=null&&p.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(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),(d=this.textTracksManager)==null||d.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(Yl(({to:c})=>c==="ready"),Ca());this.subscription.add(An(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(An(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=An(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,BC(["init"])).pipe(OC(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var $,D,z,N,O,q,R,j,L,W,w,T,_;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=($=e.videoTrack.getState())==null?void 0:$.id,n=[...this.videoTracksMap.keys()].find(({id:V})=>V===i),o=t.currentVideoTrack$.getValue(),u=((N=(z=e.videoStream.getState())!=null?z:n&&((D=this.videoTracksMap.get(n))==null?void 0:D.stream))!=null?N:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:V})=>V===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=nt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(O=e.audioStream.getState())!=null?O:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(q=[...this.audioStreamsMap.keys()].find(({id:V})=>V===(f==null?void 0:f.id)))!=null?q:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let V=Qs(n,d,(R=this.audioStreamsMap.get(b))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(j=V==null?void 0:V.bitrate)!=null?j:-1/0)}if(o){let V=Qs(o,d,(L=this.audioStreamsMap.get(b))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(W=V==null?void 0:V.bitrate)!=null?W:-1/0)}}let S=Bt(d,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,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}),v=r?S!=null?S:n:n!=null?n:S,y=b&&Cg(v,d,(w=this.audioStreamsMap.get(b))!=null?w:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(T=this.videoTracksMap.get(v))==null?void 0:T.representation,E=y&&((_=this.audioTracksMap.get(y))==null?void 0:_.representation);if(I&&E)return[I,E];if(I&&!E&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wl.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Te(this.video),this.tracer.end()}};var Da=class extends gr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as My,interval as NC,map as Cy}from"@vkontakte/videoplayer-shared/es2015";var Oa=class extends gr{constructor(e){super(e),this.liveOffset=new pt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(Cy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(My({interval:NC(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(My({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Cy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=cy(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Oy=F(qs(),1);import{assertNever as Va,assertNonNullable as Dy,debounce as FC,ErrorCategory as wn,filter as qC,isNonNullable as UC,isNullable as HC,map as kn,merge as jC,Observable as GC,observableFrom as QC,Subscription as WC,videoSizeToQuality as YC}from"@vkontakte/videoplayer-shared/es2015";var Je={};var ai=(a,e)=>new GC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ba=class{constructor(e){this.subscription=new WC;this.videoState=new C("initializing");this.textTracksManager=new Ne;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Va(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Va(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Va(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Va(e)}break;default:Va(t)}};this.video=ye(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Te(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:wn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Oy.default)(import("hls.js").then(i=>{e||(Je.Hls=i.default,Je.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Dy(Je.Hls,"hls.js not loaded"),this.hls=new Je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Dy(Je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:wn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ee(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(at(this.video,e.isLooped,r)),this.subscription.add(Ie(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(_e(this.video,e.playbackRate,i.playbackRateState$,r)),s(qe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(kn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ai(this.hls,Je.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:wn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(d=l.err)==null?void 0:d.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(ai(this.hls,Je.Events.MANIFEST_PARSED).pipe(kn(({levels:l})=>l.reduce((d,c)=>{var v,y;let p=c.name||c.height.toString(10),{width:h,height:f}=c,b=(y=Ot((v=c.attrs.QUALITY)!=null?v:""))!=null?y:YC({width:h,height:f});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:c}),d.push(S),d},[]))),t.availableVideoTracks$),s(ai(this.hls,Je.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,h=c.attrs.URI||"",f=c.lang;d.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(ai(this.hls,Je.Events.LEVEL_LOADING).pipe(kn(({url:l})=>oe(l))),t.hostname$),s(ai(this.hls,Je.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=d==null?void 0:d.endPTS)!=null?p:0)-((h=d==null?void 0:d.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=c==null?void 0:c.endPTS)!=null?f:0)-((b=c==null?void 0:c.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Mt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:c})=>c===l))==null?void 0:d.track},o=ai(this.hls,Je.Events.LEVEL_SWITCHED).pipe(kn(({level:l})=>n(this.hls.levels[l])));o.pipe(qC(UC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Mt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(HC(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),p=this.hls.currentLevel,h=this.hls.levels[p];!h||d.bitrate>h.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=jC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,QC(["init"])).pipe(FC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return k(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wn.DOM,thrown:t})))||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0)}};var Vy="X-Playback-Duration",zl=a=>k(void 0,null,function*(){var i;let e=yield ft(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Vy)?parseInt(e.headers.get(Vy),10):void 0});import{assertNever as e0,combine as t0,debounce as r0,ErrorCategory as $n,filter as i0,filterChanged as a0,isNonNullable as _y,isNullable as Ln,map as Ny,merge as s0,observableFrom as n0,Subscription as o0,ValueSubject as Xl,VideoQuality as u0}from"@vkontakte/videoplayer-shared/es2015";var Jl=F(ru(),1);import{videoSizeToQuality as zC,getExponentialDelay as KC}from"@vkontakte/videoplayer-shared/es2015";var JC=a=>{let e=null;if(a.QUALITY&&(e=Ot(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=zC({width:t,height:r})}return e!=null?e:null},XC=(a,e)=>{var s,n;let t=a.split(`
|
|
124
|
-
`),r=[],i=[];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,Jl.default)(l[1].split(",").map(v=>v.split("="))),p=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,h=JC(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 b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[v,y]=c.RESOLUTION.split("x").map(I=>parseInt(I,10));v&&y&&(g={width:v,height:y})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:g,fps:b})}if(d){let c=(0,Jl.default)(d[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=c.LANGUAGE,f=c.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},ZC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Kl=0,By=(r,...i)=>k(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield ft(a)).text();Kl+=1;try{let{qualityManifests:o,textTracks:u}=XC(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Kl<=t.manifestRetryMaxCount)return yield ZC(KC(Kl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),By(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Rn=By;var _a=class{constructor(e){this.subscription=new o0;this.videoState=new C("stopped");this.textTracksManager=new Ne;this.manifests$=new Xl([]);this.liveOffset=new pt;this.manifestStartTime$=new Xl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let 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((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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(i==null?void 0:i.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return e0(t)}};var t;this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:u0.INVARIANT,url:this.params.source.url},Rn(fe(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:$n.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:$n.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Xl((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(c=(d=(u=i==null?void 0:i.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=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:$n.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),s(qe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a0(),Ny(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&_y(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(oe(p.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)},r)),this.subscription.add(i.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)},r)),this.subscription.add(t0({startTime:this.manifestStartTime$.pipe(i0(_y)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Ny(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));let n=s0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,n0(["init"])).pipe(r0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Ln(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[c,p]of[[l,"mq"],[d,"lq"]]){let h=String(parseFloat(c||""));p&&c&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=fe(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),zl(n).then(l=>{var d;if(!Ln(l))this.maxSeekBackTime$.next(l);else{let c=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();if(Ln(c)||!isFinite(c))try{ft(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();zl(b).then(g=>{Ln(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$n.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as l0,debounce as c0,ErrorCategory as Zl,fromEvent as ec,isNonNullable as d0,isNullable as p0,map as Fy,merge as qy,observableFrom as Uy,Subscription as h0,ValueSubject as f0,VideoQuality as m0,clientChecker as b0}from"@vkontakte/videoplayer-shared/es2015";var Na=class{constructor(e){this.subscription=new h0;this.videoState=new C("stopped");this.textTracksManager=new Ne;this.manifests$=new f0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let 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((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return l0(t)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:m0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Rn(fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Zl.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,r=e.getState(),i=t.getTransition(),s=(c=(d=(u=i==null?void 0:i.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=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Zl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Fy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(at(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&d0(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===f);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(oe(b.url)))}let c=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(c!==p){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)},r))),this.subscription.add(this.manifests$.pipe(Fy(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!b0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(qy(ec(o,"addtrack"),ec(o,"removetrack"),ec(o,"change"),Uy(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=qy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Uy(["init"])).pipe(c0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var s,n;let e=this.selectManifest();if(p0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&i.searchParams.set(d,c)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Qy=F(Vr(),1),Fa=F(Vi(),1);import{assertNever as g0,assertNonNullable as Hy,debounce as v0,ErrorCategory as jy,isHigher as S0,isHigherOrEqual as y0,isInvariantQuality as Gy,isLowerOrEqual as T0,isNonNullable as I0,merge as E0,observableFrom as x0,Subscription as P0,map as A0}from"@vkontakte/videoplayer-shared/es2015";var qa=class{constructor(e){this.subscription=new P0;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Ne;this.syncPlayback=()=>{var u,l,d;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((d=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:d.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return g0(e)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Qy.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Fa.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:jy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(A0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(at(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),s(qe(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&I0(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 p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(d),p.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=E0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,x0(["init"])).pipe(v0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Te(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Hy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Hy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=xa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jy.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Fa.default)(this.trackUrls).find(c=>!Gy(c.track.quality)&&T0(c.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,d=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&d&&y0(d.quality,u.quality)&&(t=u),!t){let c=(0,Fa.default)(this.trackUrls).filter(h=>!Gy(h.track.quality)&&S0(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Fa.default)(this.trackUrls).map(l=>l.track);t=Bt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Yy,debounce as $0,merge as zy,observableFrom as L0,Subscription as M0,map as Ky,ValueSubject as C0,ErrorCategory as rc,VideoQuality as D0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as w0}from"@vkontakte/videoplayer-shared/es2015";var Wy=["stun:videostun.mycdn.me:80"],k0=1e3,R0=3,tc=()=>null,Mn=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=tc;this.externalStopCallback=tc;this.externalErrorCallback=tc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return k(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return k(this,null,function*(){try{let e={iceServers:[{urls:Wy}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return k(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return k(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:w0.WTF,message:e.message})}onPeerConnectionStream(e){return k(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return k(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),k0)}normalizeOptions(e={}){let t={stunServerList:Wy,maxRetryNumber:R0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ua=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new C0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Yy(e)}};this.subscription=new M0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ye(e.container,e.tuning),this.liveStreamClient=new Mn(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),Te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:rc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};zy(this.videoState.stateChangeStarted$.pipe(Ky(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ky(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ee(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(qe(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ie(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return Yy(n.to)}},r)).add(zy(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,L0(["init"])).pipe($0(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:D0.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:rc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ha=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ga,assertNonNullable as Ht,ErrorCategory as Cn,filter as rT,isNonNullable as iT,isNullable as U0,map as H0,merge as j0,once as G0,Subject as we,Subscription as aT,ValueSubject as B,flattenObject as sT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as O0,map as Jy,Subscription as V0,Subject as B0}from"@vkontakte/videoplayer-shared/es2015";var Xy=a=>new O0(e=>{let t=new V0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(Jy(({from:l,to:d})=>`${l}-${d}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(Jy(({type:l})=>l!==void 0)),n=new B0,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as _0,Subscription as N0,combine as F0,filter as eT,once as tT}from"@vkontakte/videoplayer-shared/es2015";function Zy(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as q0}from"@vkontakte/videoplayer-shared/es2015";var ja=class ja{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new Me;this.subscriptions=new N0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(eT(s=>!!s.type),tT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){q0.isSafari&&e!=="MPEG"||this.subscriptions.add(F0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(eT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),tT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return k(this,null,function*(){let{volumeMultiplier:t}=this,r=Zy();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:ja.errorId,category:_0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${ja.errorId} exception`,thrown:e})}};ja.errorId="VolumeMultiplierManager";var si=ja;var Q0={chunkDuration:5e3,maxParallelRequests:5},Qa=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new we;this.noAvailableProvidersError$=new we;this.volumeMultiplierError$=new we;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new we,warning$:new we,willSeekEvent$:new we,soundProhibitedEvent$:new we,seekedEvent$:new we,loopedEvent$:new we,endedEvent$:new we,firstBytesEvent$:new we,loadedMetadataEvent$:new we,firstFrameEvent$:new we,canplay$:new we,isLive$:new B(void 0),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B("")};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=$v([...Mv(this.params.tuning),...Lv(this.params.tuning)],this.params.tuning).filter(l=>iT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,ic.default)(i,l)),...t.filter(l=>(0,ic.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",sT(s)),this.screenFormatsIterator=new Ha(s);let n=[...pl(!0),...pl(!1)];this.chromecastFormatsIterator=new Ha(n.filter(l=>iT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&si.isSupported()&&(this.volumeMultiplierManager=new si(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(U0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Cn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ga(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ht(o),new Da(M(P({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ht(o),new Oa(M(P({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ht(o),Xr||!this.params.tuning.useHlsJs?new Na(M(P({},n),{source:o})):new Ba(M(P({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ht(o),new _a(M(P({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ht(o),new qa(M(P({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ht(o),new Yg(M(P({},n),{source:o,config:M(P({},Q0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ht(o),new Ua({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ga(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ht(o),new Oi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Ga(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ga(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Ga(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return M(P({},e),{url:r(e.url)})}return(0,oT.default)((0,nT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new aT,t=!1,r=0;return e.add(j0(this.providerOutput.error$.pipe(rT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),Xy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(H0(i=>({id:`ProviderHangup:${i}`,category:Cn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(rT(({to:s})=>s==="playing"),G0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Cn.NETWORK,u=i.category===Cn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n=M(P({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d}),d?(r++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",sT(n))})),e}};import{fromEvent as Dn,once as W0,combine as Y0,Subscription as uT,ValueSubject as ac,map as z0,filter as K0,isNonNullable as On,now as De,safeStorage as sc}from"@vkontakte/videoplayer-shared/es2015";var J0=5e3,lT="one_video_throughput",cT="one_video_rtt",vt=window.navigator.connection,dT=()=>{let a=vt==null?void 0:vt.downlink;if(On(a)&&a!==10)return a*1e3},pT=()=>{let a=vt==null?void 0:vt.rtt;if(On(a)&&a!==3e3)return a},hT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},nc=class a{constructor(e){this.subscription=new uT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(lT)||(e.useBrowserEstimation?dT():void 0)||J0,r=(s=(i=a.load(cT))!=null?i:e.useBrowserEstimation?pT():void 0)!=null?s:0;if(this.throughput$=new ac(t),this.rtt$=new ac(r),this.rttAdjustedThroughput$=new ac(hT(t,r,e.rttPenaltyRequestSize)),this.throughput=hr.getSmoothedValue(t,-1,e),this.rtt=hr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=dT();u&&this.throughput.next(u);let l=pT();On(l)&&this.rtt.next(l)};vt&&"onchange"in vt&&this.subscription.add(Dn(vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{sc.set(lT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{sc.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(Y0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(z0(({throughput:n,rtt:o})=>hT(n,o,e.rttPenaltyRequestSize)),K0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=De(),i=new uT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Dn(e,"progress").pipe(W0()).subscribe(s=>{t=s.loaded,r=De()}));break;case 1:case 0:i.add(Dn(e,"loadstart").subscribe(()=>{t=0,r=De()}));break}i.add(Dn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=De(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=De(),n=0,o=De(),u=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=p=>k(this,[p],function*({done:d,value:c}){if(d)!t&&this.addRawSpeed(i,De()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let h=De();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=c.byteLength,s=De()}else n+=c.byteLength;o=De()}else i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&De()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,De()-o,this.concurrentDownloads.size),n=0,o=De());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=sc.get(e);if(On(t))return(r=parseInt(t,10))!=null?r:void 0}},fT=nc;import{fillWithDefault as X0,VideoQuality as mT}from"@vkontakte/videoplayer-shared/es2015";var bT={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:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:mT.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:mT.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,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,exposeInternalsToGlobal:!1},gT=a=>{var e;return M(P({},X0(a,bT)),{configName:[...(e=a.configName)!=null?e:[],...bT.configName]})};import{assertNonNullable as Vn,combine as St,ErrorCategory as Bn,filter as ve,filterChanged as G,fromEvent as uc,isNonNullable as sD,isNullable as nD,Logger as oD,map as U,mapTo as TT,merge as jt,now as _n,once as ot,Subject as Y,Subscription as IT,tap as ET,ValueSubject as A,isHigher as uD,isInvariantQuality as xT,flattenObject as Gt,throttle as lc,getTraceSubscriptionMethod as PT,Tracer as lD,InternalsExposure as cD}from"@vkontakte/videoplayer-shared/es2015";import{merge as Z0,map as eD,filter as vT,isNonNullable as tD}from"@vkontakte/videoplayer-shared/es2015";var oc=({seekState:a,position$:e})=>Z0(a.stateChangeEnded$.pipe(eD(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),vT(tD)),e.pipe(vT(()=>a.getState().state==="none")));import{assertNonNullable as rD}from"@vkontakte/videoplayer-shared/es2015";var ST=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return rD(e,`Wrong container or containerId {${a.container}}`),e};import{filter as iD,once as aD}from"@vkontakte/videoplayer-shared/es2015";var yT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(iD(i=>i.length>0),aD()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Nn=class{constructor(e={configName:[]},t=lD.createRootTracer(!1)){this.subscription=new IT;this.logger=new oD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new A("stopped"),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),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),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,autoplaySoundProhibited$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Eg};if(this.initLogs(),this.tuning=gT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new hs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new fT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new cD("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,AT.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),d=`Player.${String(i)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Bn.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=Gc(i,["container"]);return this.tracer.log("initVideo",Gt(r)),this.domContainer=ST(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Qa({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Gi()?(this.tracer.log("request play from hidden tab"),uc(document,"visibilitychange").pipe(ot()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Vn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),ot()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Gt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Vn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Gt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>P({type:"external"},t))),this}selectTextTrack(e){var t;return yT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",P({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(nD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return sD(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(jt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ve(({from:e})=>e==="stopped"),ot()).subscribe(()=>{this.initedAt=_n(),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",Gt(n)),n.state==="requested"?this.desiredState.seekState.setState(M(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Bn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ot()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Gt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(U(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(U(n=>n.destination),G()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(St({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(U(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>xT(u)?1:xT(l)?-1:uD(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(G()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(G()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(G()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(G()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(U(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(St({hasLiveOffsetByPaused:jt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(n=>n.to),G(),U(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(St({atLiveEdge:St({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:oc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(U(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),G(),ET(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(U(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(St({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(U(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),G(),ET(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(U(n=>n.muted),G()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(U(n=>n.volume),G()).subscribe(this.info.volume$)).add(oc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(jt(e.providerOutput.endedEvent$.pipe(TT(!0)),e.providerOutput.seekedEvent$.pipe(TT(!1))).pipe(G()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(U(n=>({id:n?`No${n}`:"NoProviders",category:Bn.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.firstBytesEvent$.pipe(ot(),U(n=>n!=null?n:_n()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ot(),U(()=>_n()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ot(),U(()=>_n()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new A(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ve(({to:n})=>n==="playing"),ot()).subscribe(()=>r.next(!1)));let i=0,s=jt(e.providerOutput.isBuffering$,t,r).pipe(U(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),G());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(jt(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(jt(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(U(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new IT;this.subscription.add(t),this.subscription.add(e.current$.pipe(G((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),ot()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Bt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(jt(this.desiredState.videoTrack.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(U(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Vn(this.providerContainer),Vn(e),Ig(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Tg(r)),this.providerContainer.current$.subscribe(({type:r})=>Ni("provider",r)),e.duration$.subscribe(r=>Ni("duration",r)),e.availableVideoTracks$.pipe(ve(r=>!!r.length),ot()).subscribe(r=>Ni("tracks",r)),this.events.fatalError$.subscribe(new be("fatalError")),this.events.managedError$.subscribe(new be("managedError")),e.position$.subscribe(new be("position")),e.currentVideoTrack$.pipe(U(r=>r==null?void 0:r.quality)).subscribe(new be("quality")),this.info.currentBuffer$.subscribe(new be("buffer")),e.isBuffering$.subscribe(new be("isBuffering"))].forEach(r=>this.subscription.add(r)),Ni("codecs",Rv())}initTracerSubscription(){let e=PT(this.tracer.log.bind(this.tracer)),t=PT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(G()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(St({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ve(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),G((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ve(r=>r>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ve(r=>r>0),G()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(St({currentBuffer:this.info.currentBuffer$.pipe(ve(r=>r.end>0),G((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(G())}).pipe(lc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(G()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(G()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(G()).subscribe(e("canChangePlaybackSpeed"))).add(St({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ve(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),lc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),ve(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),ve(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(G()).subscribe(e("muted"))).add(this.info.volume$.pipe(G()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(G(),ve(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(St({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ve(({throughputEstimation:r,rtt:i})=>!!r&&!!i),lc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),ve(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>k(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Bn.DOM,message:String(i)})})});this.subscription.add(jt(uc(document,"visibilitychange"),uc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Gt({quality:t,availableTracks:Gt(e),track:Gt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as Jz,Observable as Xz,Subject as Zz,ValueSubject as e4,VideoQuality as t4}from"@vkontakte/videoplayer-shared/es2015";var r4=`@vkontakte/videoplayer-core@${Qc}`;export{os as ChromecastState,Yn as HttpConnectionType,Xz as Observable,Se as PlaybackState,Nn as Player,r4 as SDK_VERSION,Zz as Subject,Jz as Subscription,zn as Surface,Qc as VERSION,e4 as ValueSubject,kt as VideoFormat,t4 as VideoQuality};
|
|
123
|
+
`;var $n=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new kn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Rn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader($y,this.gl.VERTEX_SHADER),r=this.createShader(Ly,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as RC,now as My,Subscription as $C,filter as LC,combine as Cy,ValueSubject as Dy,isNonNullable as MC}from"@vkontakte/videoplayer-shared/es2015";var Jl=class{constructor(){this.isSeeked$=new Dy(!1);this.isBuffering$=new Dy(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new $C}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(Cy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(LC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Cy({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(RC(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=My(),p=n&&this.currentStallsCount>=n,h=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||h||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,MC(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}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=My(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Oy=Jl;import{combine as CC,map as DC,observeElementSize as OC,Subscription as BC,ValueSubject as Xl,noop as VC}from"@vkontakte/videoplayer-shared/es2015";var Ln=class{constructor(){this.subscription=new BC;this.pipSize$=new Xl(void 0);this.videoSize$=new Xl(void 0);this.elementSize$=new Xl(void 0);this.pictureInPictureWindowRemoveEventListener=VC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(OC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(CC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(DC(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Er=class{constructor(e){this.subscription=new jC;this.videoState=new C("stopped");this.textTracksManager=new qe;this.droppedFramesManager=new an;this.stallsManager=new Oy;this.elementSizeManager=new Ln;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wi;this.audioTrackSwitchHistory=new Wi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return FC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new $n(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ye(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(ue(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 An({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Ee(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Zl.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(By(c=>!!c.length),_y()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ec(c=>c.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$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(By(Vy),_y()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(ec(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(Ie(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Fe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),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 d=this.player.getStreams();if(qC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Vl(f));let b=[];for(let g of f.representations){let S=uy(g);b.push(S),this.audioTracksMap.set(S,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(_l(h));let f=[];for(let b of h.representations){let g=oy(M(x({},b),{streamId:h.id}));g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let f of h.representations){let b=ly(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}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())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:Zl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Mn(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$,HC(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Ny.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===h.id});Vy(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,S).catch(o)}},i)),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(qa()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(_l(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qa()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Vl(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(ec(({to:c})=>c==="ready"),qa());this.subscription.add(Mn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,tc(["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(Mn(u,this.player.state$.stateChangeEnded$,tc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Mn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,tc(["init"])).pipe(UC(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var $,D,J,L,F,q,R,U,N,W,A,T,V;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=($=e.videoTrack.getState())==null?void 0:$.id,n=[...this.videoTracksMap.keys()].find(({id:O})=>O===i),o=t.currentVideoTrack$.getValue(),u=((L=(J=e.videoStream.getState())!=null?J:n&&((D=this.videoTracksMap.get(n))==null?void 0:D.stream))!=null?L:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:O})=>O===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ut(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(F=e.audioStream.getState())!=null?F:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(q=[...this.audioStreamsMap.keys()].find(({id:O})=>O===(f==null?void 0:f.id)))!=null?q:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let O=Zs(n,c,(R=this.audioStreamsMap.get(b))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(U=O==null?void 0:O.bitrate)!=null?U:-1/0)}if(o){let O=Zs(o,c,(N=this.audioStreamsMap.get(b))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(W=O==null?void 0:O.bitrate)!=null?W:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,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}),v=r?S!=null?S:n:n!=null?n:S,y=b&&Fg(v,c,(A=this.audioStreamsMap.get(b))!=null?A:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(T=this.videoTracksMap.get(v))==null?void 0:T.representation,E=y&&((V=this.audioTracksMap.get(y))==null?void 0:V.representation);if(I&&E)return[I,E];if(I&&!E&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zl.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),Te(this.video),this.tracer.end()}};var Ua=class extends Er{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Fy,interval as GC,map as qy}from"@vkontakte/videoplayer-shared/es2015";var Ha=class extends Er{constructor(e){super(e),this.liveOffset=new ft,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(qy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Fy({interval:GC(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(Fy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(qy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=cy(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Hy=_(Ys(),1);import{assertNever as ja,assertNonNullable as Uy,debounce as QC,ErrorCategory as Cn,filter as WC,isNonNullable as YC,isNullable as zC,map as Dn,merge as KC,Observable as JC,observableFrom as XC,Subscription as ZC,videoSizeToQuality as e0}from"@vkontakte/videoplayer-shared/es2015";var et={};var di=(a,e)=>new JC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ga=class{constructor(e){this.subscription=new ZC;this.videoState=new C("initializing");this.textTracksManager=new qe;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default: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"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ja(e)}break;default:ja(t)}};this.video=ye(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(ue(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),Te(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Cn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Hy.default)(import("hls.js").then(i=>{e||(et.Hls=i.default,et.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Uy(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(){Uy(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Cn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ee(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(nt(this.video,e.isLooped,r)),this.subscription.add(Ie(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Fe(this.video,e.playbackRate,i.playbackRateState$,r)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Dn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(di(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Cn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(di(this.hls,et.Events.MANIFEST_PARSED).pipe(Dn(({levels:l})=>l.reduce((c,d)=>{var v,y;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(y=_t((v=d.attrs.QUALITY)!=null?v:""))!=null?y:e0({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(di(this.hls,et.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(di(this.hls,et.Events.LEVEL_LOADING).pipe(Dn(({url:l})=>ue(l))),t.hostname$),s(di(this.hls,et.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Ot(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=di(this.hls,et.Events.LEVEL_SWITCHED).pipe(Dn(({level:l})=>n(this.hls.levels[l])));o.pipe(WC(YC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ot(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(zC(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=KC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,XC(["init"])).pipe(QC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return k(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cn.DOM,thrown:t})))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0)}};var jy="X-Playback-Duration",rc=a=>k(void 0,null,function*(){var i;let e=yield bt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(jy)?parseInt(e.headers.get(jy),10):void 0});import{assertNever as n0,combine as o0,debounce as u0,ErrorCategory as Bn,filter as l0,filterChanged as c0,isNonNullable as Qy,isNullable as Vn,map as Wy,merge as d0,observableFrom as p0,Subscription as h0,ValueSubject as sc,VideoQuality as f0}from"@vkontakte/videoplayer-shared/es2015";var ac=_(uu(),1);import{videoSizeToQuality as t0,getExponentialDelay as r0}from"@vkontakte/videoplayer-shared/es2015";var i0=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=t0({width:t,height:r})}return e!=null?e:null},a0=(a,e)=>{var s,n;let t=a.split(`
|
|
124
|
+
`),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,ac.default)(l[1].split(",").map(v=>v.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=i0(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[v,y]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));v&&y&&(g={width:v,height:y})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:g,fps:b})}if(c){let d=(0,ac.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},s0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),ic=0,Gy=(r,...i)=>k(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield bt(a)).text();ic+=1;try{let{qualityManifests:o,textTracks:u}=a0(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(ic<=t.manifestRetryMaxCount)return yield s0(r0(ic-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Gy(a,e,t)}return{qualityManifests:[],textTracks:[]}}),On=Gy;var Qa=class{constructor(e){this.subscription=new h0;this.videoState=new C("stopped");this.textTracksManager=new qe;this.manifests$=new sc([]);this.liveOffset=new ft;this.manifestStartTime$=new sc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return n0(t)}};var t;this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:f0.INVARIANT,url:this.params.source.url},On(fe(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Bn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Bn.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(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new sc((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Bn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(c0(),Wy(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Qy(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(o0({startTime:this.manifestStartTime$.pipe(l0(Qy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Wy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=d0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,p0(["init"])).pipe(u0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Vn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=fe(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),rc(n).then(l=>{var c;if(!Vn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Vn(d)||!isFinite(d))try{bt(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();rc(b).then(g=>{Vn(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as m0,debounce as b0,ErrorCategory as nc,fromEvent as oc,isNonNullable as g0,isNullable as v0,map as Yy,merge as zy,observableFrom as Ky,Subscription as S0,ValueSubject as y0,VideoQuality as T0,clientChecker as I0}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new S0;this.videoState=new C("stopped");this.textTracksManager=new qe;this.manifests$=new y0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return m0(t)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:T0.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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),On(fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:nc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:nc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Yy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&g0(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===f);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(ue(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Yy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!I0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(zy(oc(o,"addtrack"),oc(o,"removetrack"),oc(o,"change"),Ky(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=zy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ky(["init"])).pipe(b0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var s,n;let e=this.selectManifest();if(v0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var eT=_(Ur(),1),Ya=_(Zr(),1);import{assertNever as E0,assertNonNullable as Jy,debounce as x0,ErrorCategory as Xy,isHigher as P0,isHigherOrEqual as w0,isInvariantQuality as Zy,isLowerOrEqual as A0,isNonNullable as k0,merge as R0,observableFrom as $0,Subscription as L0,map as M0}from"@vkontakte/videoplayer-shared/es2015";var za=class{constructor(e){this.subscription=new L0;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new qe;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return E0(e)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),(0,eT.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ya.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:Xy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(M0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&k0(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=R0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,$0(["init"])).pipe(x0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Te(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Jy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Jy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ma(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xy.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Ya.default)(this.trackUrls).find(d=>!Zy(d.track.quality)&&A0(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&w0(c.quality,u.quality)&&(t=u),!t){let d=(0,Ya.default)(this.trackUrls).filter(h=>!Zy(h.track.quality)&&P0(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Ya.default)(this.trackUrls).map(l=>l.track);t=Ft(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as rT,debounce as B0,merge as iT,observableFrom as V0,Subscription as _0,map as aT,ValueSubject as N0,ErrorCategory as lc,VideoQuality as F0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as C0}from"@vkontakte/videoplayer-shared/es2015";var tT=["stun:videostun.mycdn.me:80"],D0=1e3,O0=3,uc=()=>null,_n=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=uc;this.externalStopCallback=uc;this.externalErrorCallback=uc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return k(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return k(this,null,function*(){try{let e={iceServers:[{urls:tT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return k(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return k(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:C0.WTF,message:e.message})}onPeerConnectionStream(e){return k(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return k(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),D0)}normalizeOptions(e={}){let t={stunServerList:tT,maxRetryNumber:O0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ka=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new N0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return rT(e)}};this.subscription=new _0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ye(e.container,e.tuning),this.liveStreamClient=new _n(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),Te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:lc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};iT(this.videoState.stateChangeStarted$.pipe(aT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(aT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ee(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(He(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ie(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return rT(n.to)}},r)).add(iT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,V0(["init"])).pipe(B0(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(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:F0.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:lc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ja=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Za,assertNonNullable as Qt,ErrorCategory as Nn,filter as cT,isNonNullable as dT,isNullable as Y0,map as z0,merge as K0,once as J0,Subject as ke,Subscription as pT,ValueSubject as B,flattenObject as hT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as q0,map as sT,Subscription as U0,Subject as H0}from"@vkontakte/videoplayer-shared/es2015";var nT=a=>new q0(e=>{let t=new U0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(sT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(sT(({type:l})=>l!==void 0)),n=new H0,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as j0,Subscription as G0,combine as Q0,filter as uT,once as lT}from"@vkontakte/videoplayer-shared/es2015";function oT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as W0}from"@vkontakte/videoplayer-shared/es2015";var Xa=class Xa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new Ce;this.subscriptions=new G0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(uT(s=>!!s.type),lT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){W0.isSafari&&e!=="MPEG"||this.subscriptions.add(Q0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(uT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),lT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return k(this,null,function*(){let{volumeMultiplier:t}=this,r=oT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Xa.errorId,category:j0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Xa.errorId} exception`,thrown:e})}};Xa.errorId="VolumeMultiplierManager";var pi=Xa;var X0={chunkDuration:5e3,maxParallelRequests:5},es=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new ke;this.noAvailableProvidersError$=new ke;this.volumeMultiplierError$=new ke;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new ke,warning$:new ke,willSeekEvent$:new ke,soundProhibitedEvent$:new ke,seekedEvent$:new ke,loopedEvent$:new ke,endedEvent$:new ke,firstBytesEvent$:new ke,loadedMetadataEvent$:new ke,firstFrameEvent$:new ke,canplay$:new ke,isLive$:new B(void 0),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B("")};this.subscription=new pT;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=Vv([...Nv(this.params.tuning),..._v(this.params.tuning)],this.params.tuning).filter(l=>dT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,cc.default)(i,l)),...t.filter(l=>(0,cc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",hT(s)),this.screenFormatsIterator=new Ja(s);let n=[...vl(!0),...vl(!1)];this.chromecastFormatsIterator=new Ja(n.filter(l=>dT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&pi.isSupported()&&(this.volumeMultiplierManager=new pi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Y0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Nn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Za(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Qt(o),new Ua(M(x({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ha(M(x({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Qt(o),si||!this.params.tuning.useHlsJs?new Wa(M(x({},n),{source:o})):new Ga(M(x({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Qa(M(x({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Qt(o),new za(M(x({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new tv(M(x({},n),{source:o,config:M(x({},X0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ka({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Za(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Qt(o),new Hi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Za(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Za(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Za(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return M(x({},e),{url:r(e.url)})}return(0,mT.default)((0,fT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new pT,t=!1,r=0;return e.add(K0(this.providerOutput.error$.pipe(cT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),nT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(z0(i=>({id:`ProviderHangup:${i}`,category:Nn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(cT(({to:s})=>s==="playing"),J0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Nn.NETWORK,u=i.category===Nn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=M(x({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",hT(n))})),e}};import{fromEvent as Fn,once as Z0,combine as eD,Subscription as bT,ValueSubject as dc,map as tD,filter as rD,isNonNullable as qn,now as Be,safeStorage as pc}from"@vkontakte/videoplayer-shared/es2015";var iD=5e3,gT="one_video_throughput",vT="one_video_rtt",yt=window.navigator.connection,ST=()=>{let a=yt==null?void 0:yt.downlink;if(qn(a)&&a!==10)return a*1e3},yT=()=>{let a=yt==null?void 0:yt.rtt;if(qn(a)&&a!==3e3)return a},TT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},hc=class a{constructor(e){this.subscription=new bT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(gT)||(e.useBrowserEstimation?ST():void 0)||iD,r=(s=(i=a.load(vT))!=null?i:e.useBrowserEstimation?yT():void 0)!=null?s:0;if(this.throughput$=new dc(t),this.rtt$=new dc(r),this.rttAdjustedThroughput$=new dc(TT(t,r,e.rttPenaltyRequestSize)),this.throughput=Sr.getSmoothedValue(t,-1,e),this.rtt=Sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=ST();u&&this.throughput.next(u);let l=yT();qn(l)&&this.rtt.next(l)};yt&&"onchange"in yt&&this.subscription.add(Fn(yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{pc.set(gT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{pc.set(vT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(eD({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(tD(({throughput:n,rtt:o})=>TT(n,o,e.rttPenaltyRequestSize)),rD(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Be(),i=new bT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Fn(e,"progress").pipe(Z0()).subscribe(s=>{t=s.loaded,r=Be()}));break;case 1:case 0:i.add(Fn(e,"loadstart").subscribe(()=>{t=0,r=Be()}));break}i.add(Fn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Be(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Be(),n=0,o=Be(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>k(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Be()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Be();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Be()}else n+=d.byteLength;o=Be()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Be()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Be()-o,this.concurrentDownloads.size),n=0,o=Be());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=pc.get(e);if(qn(t))return(r=parseInt(t,10))!=null?r:void 0}},IT=hc;import{fillWithDefault as aD,VideoQuality as ET}from"@vkontakte/videoplayer-shared/es2015";var xT={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:ET.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ET.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,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,exposeInternalsToGlobal:!1},PT=a=>{var e;return M(x({},aD(a,xT)),{configName:[...(e=a.configName)!=null?e:[],...xT.configName]})};import{assertNonNullable as Un,combine as Tt,ErrorCategory as Hn,filter as ve,filterChanged as G,fromEvent as mc,isNonNullable as dD,isNullable as pD,Logger as hD,map as H,mapTo as RT,merge as Wt,now as jn,once as lt,Subject as z,Subscription as $T,tap as LT,ValueSubject as w,isHigher as fD,isInvariantQuality as MT,flattenObject as Yt,throttle as bc,getTraceSubscriptionMethod as CT,Tracer as mD,InternalsExposure as bD}from"@vkontakte/videoplayer-shared/es2015";import{merge as sD,map as nD,filter as wT,isNonNullable as oD}from"@vkontakte/videoplayer-shared/es2015";var fc=({seekState:a,position$:e})=>sD(a.stateChangeEnded$.pipe(nD(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),wT(oD)),e.pipe(wT(()=>a.getState().state==="none")));import{assertNonNullable as uD}from"@vkontakte/videoplayer-shared/es2015";var AT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return uD(e,`Wrong container or containerId {${a.container}}`),e};import{filter as lD,once as cD}from"@vkontakte/videoplayer-shared/es2015";var kT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(lD(i=>i.length>0),cD()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Gn=class{constructor(e={configName:[]},t=mD.createRootTracer(!1)){this.subscription=new $T;this.logger=new hD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new w(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new w("stopped"),position$:new w(0),duration$:new w(1/0),muted$:new w(!1),volume$:new w(1),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableQualities$:new w([]),availableQualitiesFps$:new w({}),currentQuality$:new w(void 0),isAutoQualityEnabled$:new w(!0),autoQualityLimitingAvailable$:new w(!1),autoQualityLimits$:new w({}),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),isAudioAvailable$:new w(!0),currentPlaybackRate$:new w(1),currentBuffer$:new w({start:0,end:0}),isBuffering$:new w(!0),isStalled$:new w(!1),isEnded$:new w(!1),isLooped$:new w(!1),isLive$:new w(void 0),canChangePlaybackSpeed$:new w(void 0),atLiveEdge$:new w(void 0),atLiveDurationEdge$:new w(void 0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),currentFormat$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),throughputEstimation$:new w(void 0),rttEstimation$:new w(void 0),videoBitrate$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),surface$:new w("none"),chromecastState$:new w("NOT_AVAILABLE"),chromecastDeviceName$:new w(void 0),intrinsicVideoSize$:new w(void 0),availableSources$:new w(void 0),is3DVideo$:new w(!1),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(0)};this.events={inited$:new z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z};this.experimental={element$:new w(void 0),tuningConfigName$:new w([]),enableDebugTelemetry$:new w(!1),dumpTelemetry:$g};if(this.initLogs(),this.tuning=PT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ys({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new IT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new bD("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,DT.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Hn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=Xc(i,["container"]);return this.tracer.log("initVideo",Yt(r)),this.domContainer=AT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new es({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Xi()?(this.tracer.log("request play from hidden tab"),mc(document,"visibilitychange").pipe(lt()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Un(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),lt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Yt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Un(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Yt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>x({type:"external"},t))),this}selectTextTrack(e){var t;return kT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",x({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(pD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return dD(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ve(({from:e})=>e==="stopped"),lt()).subscribe(()=>{this.initedAt=jn(),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(M(x({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Hn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(lt()).subscribe(this.events.autoplaySoundProhibited$)).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(H(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(H(n=>n.destination),G()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Tt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(H(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>MT(u)?1:MT(l)?-1:fD(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(G()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(G()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(G()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(G()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(H(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.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(Tt({hasLiveOffsetByPaused:Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(n=>n.to),G(),H(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Tt({atLiveEdge:Tt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:fc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(H(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),G(),LT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(H(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Tt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(H(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),G(),LT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(H(n=>n.muted),G()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(H(n=>n.volume),G()).subscribe(this.info.volume$)).add(fc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Wt(e.providerOutput.endedEvent$.pipe(RT(!0)),e.providerOutput.seekedEvent$.pipe(RT(!1))).pipe(G()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(H(n=>({id:n?`No${n}`:"NoProviders",category:Hn.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.firstBytesEvent$.pipe(lt(),H(n=>n!=null?n:jn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(lt(),H(()=>jn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(lt(),H(()=>jn()-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 w(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new w(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ve(({to:n})=>n==="playing"),lt()).subscribe(()=>r.next(!1)));let i=0,s=Wt(e.providerOutput.isBuffering$,t,r).pipe(H(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),G());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(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(H(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new $T;this.subscription.add(t),this.subscription.add(e.current$.pipe(G((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),lt()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Wt(this.desiredState.videoTrack.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(H(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Un(this.providerContainer),Un(e),Rg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>kg(r)),this.providerContainer.current$.subscribe(({type:r})=>Qi("provider",r)),e.duration$.subscribe(r=>Qi("duration",r)),e.availableVideoTracks$.pipe(ve(r=>!!r.length),lt()).subscribe(r=>Qi("tracks",r)),this.events.fatalError$.subscribe(new be("fatalError")),this.events.managedError$.subscribe(new be("managedError")),e.position$.subscribe(new be("position")),e.currentVideoTrack$.pipe(H(r=>r==null?void 0:r.quality)).subscribe(new be("quality")),this.info.currentBuffer$.subscribe(new be("buffer")),e.isBuffering$.subscribe(new be("isBuffering"))].forEach(r=>this.subscription.add(r)),Qi("codecs",Bv())}initTracerSubscription(){let e=CT(this.tracer.log.bind(this.tracer)),t=CT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(G()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Tt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ve(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),G((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ve(r=>r>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ve(r=>r>0),G()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Tt({currentBuffer:this.info.currentBuffer$.pipe(ve(r=>r.end>0),G((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(G())}).pipe(bc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(G()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(G()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(G()).subscribe(e("canChangePlaybackSpeed"))).add(Tt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ve(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),bc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),ve(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),ve(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(G()).subscribe(e("muted"))).add(this.info.volume$.pipe(G()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(G(),ve(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Tt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ve(({throughputEstimation:r,rtt:i})=>!!r&&!!i),bc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),ve(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>k(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Hn.DOM,message:String(i)})})});this.subscription.add(Wt(mc(document,"visibilitychange"),mc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Yt({quality:t,availableTracks:Yt(e),track:Yt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as c4,Observable as d4,Subject as p4,ValueSubject as h4,VideoQuality as f4}from"@vkontakte/videoplayer-shared/es2015";var m4=`@vkontakte/videoplayer-core@${Zc}`;export{fs as ChromecastState,eo as HttpConnectionType,d4 as Observable,Se as PlaybackState,Gn as Player,m4 as SDK_VERSION,p4 as Subject,c4 as Subscription,to as Surface,Zc as VERSION,h4 as ValueSubject,Lt as VideoFormat,f4 as VideoQuality};
|