@vkontakte/videoplayer-core 2.0.119-dev.df6b2fd8.0 → 2.0.119-dev.e9ac9f0e.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 +20 -20
- package/es2015.esm.js +21 -21
- package/es2018.cjs.js +22 -22
- package/es2018.esm.js +22 -22
- package/esnext.cjs.js +21 -21
- package/esnext.esm.js +21 -21
- package/evergreen.esm.js +21 -21
- package/package.json +2 -2
- package/types/index.d.ts +2 -2
- package/types/player/Player.d.ts +1 -3
- package/types/player/types.d.ts +0 -13
- package/types/utils/tuningConfig.d.ts +0 -2
- package/types/utils/qualityLimits.d.ts +0 -9
package/es2018.esm.js
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.119-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.119-dev.e9ac9f0e.0
|
|
3
|
+
* Wed, 11 Dec 2024 12:46:31 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-119/doc/
|
|
5
5
|
*/
|
|
6
|
-
var wT=Object.create;var Oc=Object.defineProperty;var kT=Object.getOwnPropertyDescriptor;var RT=Object.getOwnPropertyNames;var $T=Object.getPrototypeOf,LT=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var MT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of RT(e))!LT.call(a,i)&&i!==t&&Oc(a,i,{get:()=>e[i],enumerable:!(r=kT(e,i))||r.enumerable});return a};var C=(a,e,t)=>(t=a!=null?wT($T(a)):{},MT(e||!a||!a.__esModule?Oc(t,"default",{value:a,enumerable:!0}):t,a));var z=m((Hn,Bc)=>{"use strict";var ui=function(a){return a&&a.Math===Math&&a};Bc.exports=ui(typeof globalThis=="object"&&globalThis)||ui(typeof window=="object"&&window)||ui(typeof self=="object"&&self)||ui(typeof global=="object"&&global)||ui(typeof Hn=="object"&&Hn)||function(){return this}()||Function("return this")()});var ne=m((Z0,_c)=>{"use strict";_c.exports=function(a){try{return!!a()}catch(e){return!0}}});var li=m((eD,Nc)=>{"use strict";var CT=ne();Nc.exports=!CT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var jn=m((tD,Hc)=>{"use strict";var DT=li(),Uc=Function.prototype,Fc=Uc.apply,qc=Uc.call;Hc.exports=typeof Reflect=="object"&&Reflect.apply||(DT?qc.bind(Fc):function(){return qc.apply(Fc,arguments)})});var te=m((rD,Gc)=>{"use strict";var jc=li(),Qc=Function.prototype,Qn=Qc.call,OT=jc&&Qc.bind.bind(Qn,Qn);Gc.exports=jc?OT:function(a){return function(){return Qn.apply(a,arguments)}}});var Gt=m((iD,Yc)=>{"use strict";var Wc=te(),VT=Wc({}.toString),BT=Wc("".slice);Yc.exports=function(a){return BT(VT(a),8,-1)}});var Gn=m((aD,zc)=>{"use strict";var _T=Gt(),NT=te();zc.exports=function(a){if(_T(a)==="Function")return NT(a)}});var Y=m((sD,Kc)=>{"use strict";var Wn=typeof document=="object"&&document.all;Kc.exports=typeof Wn=="undefined"&&Wn!==void 0?function(a){return typeof a=="function"||a===Wn}:function(a){return typeof a=="function"}});var xe=m((nD,Jc)=>{"use strict";var FT=ne();Jc.exports=!FT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Pe=m((oD,Xc)=>{"use strict";var qT=li(),is=Function.prototype.call;Xc.exports=qT?is.bind(is):function(){return is.apply(is,arguments)}});var Yn=m(td=>{"use strict";var Zc={}.propertyIsEnumerable,ed=Object.getOwnPropertyDescriptor,UT=ed&&!Zc.call({1:2},1);td.f=UT?function(e){var t=ed(this,e);return!!t&&t.enumerable}:Zc});var ci=m((lD,rd)=>{"use strict";rd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var ad=m((cD,id)=>{"use strict";var HT=te(),jT=ne(),QT=Gt(),zn=Object,GT=HT("".split);id.exports=jT(function(){return!zn("z").propertyIsEnumerable(0)})?function(a){return QT(a)==="String"?GT(a,""):zn(a)}:zn});var Tr=m((dD,sd)=>{"use strict";sd.exports=function(a){return a==null}});var Et=m((pD,nd)=>{"use strict";var WT=Tr(),YT=TypeError;nd.exports=function(a){if(WT(a))throw new YT("Can't call method on "+a);return a}});var Wt=m((hD,od)=>{"use strict";var zT=ad(),KT=Et();od.exports=function(a){return zT(KT(a))}});var Ae=m((fD,ud)=>{"use strict";var JT=Y();ud.exports=function(a){return typeof a=="object"?a!==null:JT(a)}});var Ir=m((mD,ld)=>{"use strict";ld.exports={}});var at=m((bD,dd)=>{"use strict";var Kn=Ir(),Jn=z(),XT=Y(),cd=function(a){return XT(a)?a:void 0};dd.exports=function(a,e){return arguments.length<2?cd(Kn[a])||cd(Jn[a]):Kn[a]&&Kn[a][e]||Jn[a]&&Jn[a][e]}});var di=m((gD,pd)=>{"use strict";var ZT=te();pd.exports=ZT({}.isPrototypeOf)});var Yt=m((vD,md)=>{"use strict";var eI=z(),hd=eI.navigator,fd=hd&&hd.userAgent;md.exports=fd?String(fd):""});var Zn=m((SD,Td)=>{"use strict";var yd=z(),Xn=Yt(),bd=yd.process,gd=yd.Deno,vd=bd&&bd.versions||gd&&gd.version,Sd=vd&&vd.v8,qe,as;Sd&&(qe=Sd.split("."),as=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!as&&Xn&&(qe=Xn.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=Xn.match(/Chrome\/(\d+)/),qe&&(as=+qe[1])));Td.exports=as});var eo=m((yD,Ed)=>{"use strict";var Id=Zn(),tI=ne(),rI=z(),iI=rI.String;Ed.exports=!!Object.getOwnPropertySymbols&&!tI(function(){var a=Symbol("symbol detection");return!iI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Id&&Id<41})});var to=m((TD,xd)=>{"use strict";var aI=eo();xd.exports=aI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ro=m((ID,Pd)=>{"use strict";var sI=at(),nI=Y(),oI=di(),uI=to(),lI=Object;Pd.exports=uI?function(a){return typeof a=="symbol"}:function(a){var e=sI("Symbol");return nI(e)&&oI(e.prototype,lI(a))}});var pi=m((ED,Ad)=>{"use strict";var cI=String;Ad.exports=function(a){try{return cI(a)}catch(e){return"Object"}}});var Ke=m((xD,wd)=>{"use strict";var dI=Y(),pI=pi(),hI=TypeError;wd.exports=function(a){if(dI(a))return a;throw new hI(pI(a)+" is not a function")}});var hi=m((PD,kd)=>{"use strict";var fI=Ke(),mI=Tr();kd.exports=function(a,e){var t=a[e];return mI(t)?void 0:fI(t)}});var $d=m((AD,Rd)=>{"use strict";var io=Pe(),ao=Y(),so=Ae(),bI=TypeError;Rd.exports=function(a,e){var t,r;if(e==="string"&&ao(t=a.toString)&&!so(r=io(t,a))||ao(t=a.valueOf)&&!so(r=io(t,a))||e!=="string"&&ao(t=a.toString)&&!so(r=io(t,a)))return r;throw new bI("Can't convert object to primitive value")}});var Ue=m((wD,Ld)=>{"use strict";Ld.exports=!0});var Dd=m((kD,Cd)=>{"use strict";var Md=z(),gI=Object.defineProperty;Cd.exports=function(a,e){try{gI(Md,a,{value:e,configurable:!0,writable:!0})}catch(t){Md[a]=e}return e}});var fi=m((RD,Bd)=>{"use strict";var vI=Ue(),SI=z(),yI=Dd(),Od="__core-js_shared__",Vd=Bd.exports=SI[Od]||yI(Od,{});(Vd.versions||(Vd.versions=[])).push({version:"3.38.0",mode:vI?"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 no=m(($D,Nd)=>{"use strict";var _d=fi();Nd.exports=function(a,e){return _d[a]||(_d[a]=e||{})}});var Er=m((LD,Fd)=>{"use strict";var TI=Et(),II=Object;Fd.exports=function(a){return II(TI(a))}});var He=m((MD,qd)=>{"use strict";var EI=te(),xI=Er(),PI=EI({}.hasOwnProperty);qd.exports=Object.hasOwn||function(e,t){return PI(xI(e),t)}});var oo=m((CD,Ud)=>{"use strict";var AI=te(),wI=0,kI=Math.random(),RI=AI(1 .toString);Ud.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+RI(++wI+kI,36)}});var oe=m((DD,jd)=>{"use strict";var $I=z(),LI=no(),Hd=He(),MI=oo(),CI=eo(),DI=to(),xr=$I.Symbol,uo=LI("wks"),OI=DI?xr.for||xr:xr&&xr.withoutSetter||MI;jd.exports=function(a){return Hd(uo,a)||(uo[a]=CI&&Hd(xr,a)?xr[a]:OI("Symbol."+a)),uo[a]}});var Yd=m((OD,Wd)=>{"use strict";var VI=Pe(),Qd=Ae(),Gd=ro(),BI=hi(),_I=$d(),NI=oe(),FI=TypeError,qI=NI("toPrimitive");Wd.exports=function(a,e){if(!Qd(a)||Gd(a))return a;var t=BI(a,qI),r;if(t){if(e===void 0&&(e="default"),r=VI(t,a,e),!Qd(r)||Gd(r))return r;throw new FI("Can't convert object to primitive value")}return e===void 0&&(e="number"),_I(a,e)}});var lo=m((VD,zd)=>{"use strict";var UI=Yd(),HI=ro();zd.exports=function(a){var e=UI(a,"string");return HI(e)?e:e+""}});var ss=m((BD,Jd)=>{"use strict";var jI=z(),Kd=Ae(),co=jI.document,QI=Kd(co)&&Kd(co.createElement);Jd.exports=function(a){return QI?co.createElement(a):{}}});var po=m((_D,Xd)=>{"use strict";var GI=xe(),WI=ne(),YI=ss();Xd.exports=!GI&&!WI(function(){return Object.defineProperty(YI("div"),"a",{get:function(){return 7}}).a!==7})});var tp=m(ep=>{"use strict";var zI=xe(),KI=Pe(),JI=Yn(),XI=ci(),ZI=Wt(),eE=lo(),tE=He(),rE=po(),Zd=Object.getOwnPropertyDescriptor;ep.f=zI?Zd:function(e,t){if(e=ZI(e),t=eE(t),rE)try{return Zd(e,t)}catch(r){}if(tE(e,t))return XI(!KI(JI.f,e,t),e[t])}});var ho=m((FD,rp)=>{"use strict";var iE=ne(),aE=Y(),sE=/#|\.prototype\./,mi=function(a,e){var t=oE[nE(a)];return t===lE?!0:t===uE?!1:aE(e)?iE(e):!!e},nE=mi.normalize=function(a){return String(a).replace(sE,".").toLowerCase()},oE=mi.data={},uE=mi.NATIVE="N",lE=mi.POLYFILL="P";rp.exports=mi});var Pr=m((qD,ap)=>{"use strict";var ip=Gn(),cE=Ke(),dE=li(),pE=ip(ip.bind);ap.exports=function(a,e){return cE(a),e===void 0?a:dE?pE(a,e):function(){return a.apply(e,arguments)}}});var fo=m((UD,sp)=>{"use strict";var hE=xe(),fE=ne();sp.exports=hE&&fE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Je=m((HD,np)=>{"use strict";var mE=Ae(),bE=String,gE=TypeError;np.exports=function(a){if(mE(a))return a;throw new gE(bE(a)+" is not an object")}});var zt=m(up=>{"use strict";var vE=xe(),SE=po(),yE=fo(),ns=Je(),op=lo(),TE=TypeError,mo=Object.defineProperty,IE=Object.getOwnPropertyDescriptor,bo="enumerable",go="configurable",vo="writable";up.f=vE?yE?function(e,t,r){if(ns(e),t=op(t),ns(r),typeof e=="function"&&t==="prototype"&&"value"in r&&vo in r&&!r[vo]){var i=IE(e,t);i&&i[vo]&&(e[t]=r.value,r={configurable:go in r?r[go]:i[go],enumerable:bo in r?r[bo]:i[bo],writable:!1})}return mo(e,t,r)}:mo:function(e,t,r){if(ns(e),t=op(t),ns(r),SE)try{return mo(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new TE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Ar=m((QD,lp)=>{"use strict";var EE=xe(),xE=zt(),PE=ci();lp.exports=EE?function(a,e,t){return xE.f(a,e,PE(1,t))}:function(a,e,t){return a[e]=t,a}});var X=m((GD,dp)=>{"use strict";var bi=z(),AE=jn(),wE=Gn(),kE=Y(),RE=tp().f,$E=ho(),wr=Ir(),LE=Pr(),kr=Ar(),cp=He();fi();var ME=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 AE(a,this,arguments)};return e.prototype=a.prototype,e};dp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?bi:i?bi[t]:bi[t]&&bi[t].prototype,o=r?wr:wr[t]||kr(wr,t,{})[t],u=o.prototype,l,d,c,p,h,f,b,g,v;for(p in e)l=$E(r?p:t+(i?".":"#")+p,a.forced),d=!l&&n&&cp(n,p),f=o[p],d&&(a.dontCallGetSet?(v=RE(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&d?g=LE(h,bi):a.wrap&&d?g=ME(h):s&&kE(h)?g=wE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&kr(g,"sham",!0),kr(o,p,g),s&&(c=t+"Prototype",cp(wr,c)||kr(wr,c,{}),kr(wr[c],p,h),a.real&&u&&(l||!u[p])&&kr(u,p,h)))}});var hp=m((WD,pp)=>{"use strict";var CE=Math.ceil,DE=Math.floor;pp.exports=Math.trunc||function(e){var t=+e;return(t>0?DE:CE)(t)}});var gi=m((YD,fp)=>{"use strict";var OE=hp();fp.exports=function(a){var e=+a;return e!==e||e===0?0:OE(e)}});var bp=m((zD,mp)=>{"use strict";var VE=gi(),BE=Math.max,_E=Math.min;mp.exports=function(a,e){var t=VE(a);return t<0?BE(t+e,0):_E(t,e)}});var So=m((KD,gp)=>{"use strict";var NE=gi(),FE=Math.min;gp.exports=function(a){var e=NE(a);return e>0?FE(e,9007199254740991):0}});var Rr=m((JD,vp)=>{"use strict";var qE=So();vp.exports=function(a){return qE(a.length)}});var yo=m((XD,yp)=>{"use strict";var UE=Wt(),HE=bp(),jE=Rr(),Sp=function(a){return function(e,t,r){var i=UE(e),s=jE(i);if(s===0)return!a&&-1;var n=HE(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};yp.exports={includes:Sp(!0),indexOf:Sp(!1)}});var vi=m((ZD,Tp)=>{"use strict";Tp.exports=function(){}});var Ip=m(()=>{"use strict";var QE=X(),GE=yo().includes,WE=ne(),YE=vi(),zE=WE(function(){return!Array(1).includes()});QE({target:"Array",proto:!0,forced:zE},{includes:function(e){return GE(this,e,arguments.length>1?arguments[1]:void 0)}});YE("includes")});var xt=m((rO,Ep)=>{"use strict";var KE=at();Ep.exports=KE});var Pp=m((iO,xp)=>{"use strict";Ip();var JE=xt();xp.exports=JE("Array","includes")});var wp=m((aO,Ap)=>{"use strict";var XE=Pp();Ap.exports=XE});var Xe=m((sO,kp)=>{"use strict";var ZE=wp();kp.exports=ZE});var ls=m((gO,Vp)=>{"use strict";var ox=no(),ux=oo(),Op=ox("keys");Vp.exports=function(a){return Op[a]||(Op[a]=ux(a))}});var _p=m((vO,Bp)=>{"use strict";var lx=ne();Bp.exports=!lx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var cs=m((SO,Fp)=>{"use strict";var cx=He(),dx=Y(),px=Er(),hx=ls(),fx=_p(),Np=hx("IE_PROTO"),Eo=Object,mx=Eo.prototype;Fp.exports=fx?Eo.getPrototypeOf:function(a){var e=px(a);if(cx(e,Np))return e[Np];var t=e.constructor;return dx(t)&&e instanceof t?t.prototype:e instanceof Eo?mx:null}});var ds=m((yO,qp)=>{"use strict";qp.exports={}});var jp=m((TO,Hp)=>{"use strict";var bx=te(),xo=He(),gx=Wt(),vx=yo().indexOf,Sx=ds(),Up=bx([].push);Hp.exports=function(a,e){var t=gx(a),r=0,i=[],s;for(s in t)!xo(Sx,s)&&xo(t,s)&&Up(i,s);for(;e.length>r;)xo(t,s=e[r++])&&(~vx(i,s)||Up(i,s));return i}});var Po=m((IO,Qp)=>{"use strict";Qp.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ao=m((EO,Gp)=>{"use strict";var yx=jp(),Tx=Po();Gp.exports=Object.keys||function(e){return yx(e,Tx)}});var wo=m((xO,Jp)=>{"use strict";var Yp=xe(),Ix=ne(),zp=te(),Ex=cs(),xx=Ao(),Px=Wt(),Ax=Yn().f,Kp=zp(Ax),wx=zp([].push),kx=Yp&&Ix(function(){var a=Object.create(null);return a[2]=2,!Kp(a,2)}),Wp=function(a){return function(e){for(var t=Px(e),r=xx(t),i=kx&&Ex(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Yp||(i?u in t:Kp(t,u)))&&wx(o,a?[u,t[u]]:t[u]);return o}};Jp.exports={entries:Wp(!0),values:Wp(!1)}});var Xp=m(()=>{"use strict";var Rx=X(),$x=wo().entries;Rx({target:"Object",stat:!0},{entries:function(e){return $x(e)}})});var eh=m((wO,Zp)=>{"use strict";Xp();var Lx=Ir();Zp.exports=Lx.Object.entries});var rh=m((kO,th)=>{"use strict";var Mx=eh();th.exports=Mx});var $r=m((RO,ih)=>{"use strict";var Cx=rh();ih.exports=Cx});var Kt=m(($O,ah)=>{"use strict";ah.exports={}});var oh=m((LO,nh)=>{"use strict";var Dx=z(),Ox=Y(),sh=Dx.WeakMap;nh.exports=Ox(sh)&&/native code/.test(String(sh))});var Lo=m((MO,ch)=>{"use strict";var Vx=oh(),lh=z(),Bx=Ae(),_x=Ar(),ko=He(),Ro=fi(),Nx=ls(),Fx=ds(),uh="Object already initialized",$o=lh.TypeError,qx=lh.WeakMap,ps,Si,hs,Ux=function(a){return hs(a)?Si(a):ps(a,{})},Hx=function(a){return function(e){var t;if(!Bx(e)||(t=Si(e)).type!==a)throw new $o("Incompatible receiver, "+a+" required");return t}};Vx||Ro.state?(je=Ro.state||(Ro.state=new qx),je.get=je.get,je.has=je.has,je.set=je.set,ps=function(a,e){if(je.has(a))throw new $o(uh);return e.facade=a,je.set(a,e),e},Si=function(a){return je.get(a)||{}},hs=function(a){return je.has(a)}):(Jt=Nx("state"),Fx[Jt]=!0,ps=function(a,e){if(ko(a,Jt))throw new $o(uh);return e.facade=a,_x(a,Jt,e),e},Si=function(a){return ko(a,Jt)?a[Jt]:{}},hs=function(a){return ko(a,Jt)});var je,Jt;ch.exports={set:ps,get:Si,has:hs,enforce:Ux,getterFor:Hx}});var Do=m((CO,ph)=>{"use strict";var Mo=xe(),jx=He(),dh=Function.prototype,Qx=Mo&&Object.getOwnPropertyDescriptor,Co=jx(dh,"name"),Gx=Co&&function(){}.name==="something",Wx=Co&&(!Mo||Mo&&Qx(dh,"name").configurable);ph.exports={EXISTS:Co,PROPER:Gx,CONFIGURABLE:Wx}});var fh=m(hh=>{"use strict";var Yx=xe(),zx=fo(),Kx=zt(),Jx=Je(),Xx=Wt(),Zx=Ao();hh.f=Yx&&!zx?Object.defineProperties:function(e,t){Jx(e);for(var r=Xx(t),i=Zx(t),s=i.length,n=0,o;s>n;)Kx.f(e,o=i[n++],r[o]);return e}});var Oo=m((OO,mh)=>{"use strict";var eP=at();mh.exports=eP("document","documentElement")});var No=m((VO,Ih)=>{"use strict";var tP=Je(),rP=fh(),bh=Po(),iP=ds(),aP=Oo(),sP=ss(),nP=ls(),gh=">",vh="<",Bo="prototype",_o="script",yh=nP("IE_PROTO"),Vo=function(){},Th=function(a){return vh+_o+gh+a+vh+"/"+_o+gh},Sh=function(a){a.write(Th("")),a.close();var e=a.parentWindow.Object;return a=null,e},oP=function(){var a=sP("iframe"),e="java"+_o+":",t;return a.style.display="none",aP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Th("document.F=Object")),t.close(),t.F},fs,ms=function(){try{fs=new ActiveXObject("htmlfile")}catch(e){}ms=typeof document!="undefined"?document.domain&&fs?Sh(fs):oP():Sh(fs);for(var a=bh.length;a--;)delete ms[Bo][bh[a]];return ms()};iP[yh]=!0;Ih.exports=Object.create||function(e,t){var r;return e!==null?(Vo[Bo]=tP(e),r=new Vo,Vo[Bo]=null,r[yh]=e):r=ms(),t===void 0?r:rP.f(r,t)}});var Lr=m((BO,Eh)=>{"use strict";var uP=Ar();Eh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:uP(a,e,t),a}});var Ho=m((_O,Ah)=>{"use strict";var lP=ne(),cP=Y(),dP=Ae(),pP=No(),xh=cs(),hP=Lr(),fP=oe(),mP=Ue(),Uo=fP("iterator"),Ph=!1,st,Fo,qo;[].keys&&(qo=[].keys(),"next"in qo?(Fo=xh(xh(qo)),Fo!==Object.prototype&&(st=Fo)):Ph=!0);var bP=!dP(st)||lP(function(){var a={};return st[Uo].call(a)!==a});bP?st={}:mP&&(st=pP(st));cP(st[Uo])||hP(st,Uo,function(){return this});Ah.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:Ph}});var bs=m((NO,kh)=>{"use strict";var gP=oe(),vP=gP("toStringTag"),wh={};wh[vP]="z";kh.exports=String(wh)==="[object z]"});var yi=m((FO,Rh)=>{"use strict";var SP=bs(),yP=Y(),gs=Gt(),TP=oe(),IP=TP("toStringTag"),EP=Object,xP=gs(function(){return arguments}())==="Arguments",PP=function(a,e){try{return a[e]}catch(t){}};Rh.exports=SP?gs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=PP(e=EP(a),IP))=="string"?t:xP?gs(e):(r=gs(e))==="Object"&&yP(e.callee)?"Arguments":r}});var Lh=m((qO,$h)=>{"use strict";var AP=bs(),wP=yi();$h.exports=AP?{}.toString:function(){return"[object "+wP(this)+"]"}});var Ti=m((UO,Ch)=>{"use strict";var kP=bs(),RP=zt().f,$P=Ar(),LP=He(),MP=Lh(),CP=oe(),Mh=CP("toStringTag");Ch.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(LP(i,Mh)||RP(i,Mh,{configurable:!0,value:e}),r&&!kP&&$P(i,"toString",MP))}});var Oh=m((HO,Dh)=>{"use strict";var DP=Ho().IteratorPrototype,OP=No(),VP=ci(),BP=Ti(),_P=Kt(),NP=function(){return this};Dh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=OP(DP,{next:VP(+!r,t)}),BP(a,i,!1,!0),_P[i]=NP,a}});var Bh=m((jO,Vh)=>{"use strict";var FP=te(),qP=Ke();Vh.exports=function(a,e,t){try{return FP(qP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Nh=m((QO,_h)=>{"use strict";var UP=Ae();_h.exports=function(a){return UP(a)||a===null}});var qh=m((GO,Fh)=>{"use strict";var HP=Nh(),jP=String,QP=TypeError;Fh.exports=function(a){if(HP(a))return a;throw new QP("Can't set "+jP(a)+" as a prototype")}});var jo=m((WO,Uh)=>{"use strict";var GP=Bh(),WP=Ae(),YP=Et(),zP=qh();Uh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=GP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return YP(i),zP(s),WP(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Zh=m((YO,Xh)=>{"use strict";var KP=X(),JP=Pe(),vs=Ue(),Kh=Do(),XP=Y(),ZP=Oh(),Hh=cs(),jh=jo(),eA=Ti(),tA=Ar(),Qo=Lr(),rA=oe(),Qh=Kt(),Jh=Ho(),iA=Kh.PROPER,aA=Kh.CONFIGURABLE,Gh=Jh.IteratorPrototype,Ss=Jh.BUGGY_SAFARI_ITERATORS,Ii=rA("iterator"),Wh="keys",Ei="values",Yh="entries",zh=function(){return this};Xh.exports=function(a,e,t,r,i,s,n){ZP(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ss&&v&&v in d)return d[v];switch(v){case Wh:return function(){return new t(this,v)};case Ei:return function(){return new t(this,v)};case Yh:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[Ii]||d["@@iterator"]||i&&d[i],p=!Ss&&c||o(i),h=e==="Array"&&d.entries||c,f,b,g;if(h&&(f=Hh(h.call(new a)),f!==Object.prototype&&f.next&&(!vs&&Hh(f)!==Gh&&(jh?jh(f,Gh):XP(f[Ii])||Qo(f,Ii,zh)),eA(f,u,!0,!0),vs&&(Qh[u]=zh))),iA&&i===Ei&&c&&c.name!==Ei&&(!vs&&aA?tA(d,"name",Ei):(l=!0,p=function(){return JP(c,this)})),i)if(b={values:o(Ei),keys:s?p:o(Wh),entries:o(Yh)},n)for(g in b)(Ss||l||!(g in d))&&Qo(d,g,b[g]);else KP({target:e,proto:!0,forced:Ss||l},b);return(!vs||n)&&d[Ii]!==p&&Qo(d,Ii,p,{name:i}),Qh[e]=p,b}});var tf=m((zO,ef)=>{"use strict";ef.exports=function(a,e){return{value:a,done:e}}});var Wo=m((KO,of)=>{"use strict";var sA=Wt(),Go=vi(),rf=Kt(),sf=Lo(),nA=zt().f,oA=Zh(),ys=tf(),uA=Ue(),lA=xe(),nf="Array Iterator",cA=sf.set,dA=sf.getterFor(nf);of.exports=oA(Array,"Array",function(a,e){cA(this,{type:nf,target:sA(a),index:0,kind:e})},function(){var a=dA(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,ys(void 0,!0);switch(a.kind){case"keys":return ys(t,!1);case"values":return ys(e[t],!1)}return ys([t,e[t]],!1)},"values");var af=rf.Arguments=rf.Array;Go("keys");Go("values");Go("entries");if(!uA&&lA&&af.name!=="values")try{nA(af,"name",{value:"values"})}catch(a){}});var lf=m((JO,uf)=>{"use strict";var pA=oe(),hA=Kt(),fA=pA("iterator"),mA=Array.prototype;uf.exports=function(a){return a!==void 0&&(hA.Array===a||mA[fA]===a)}});var Yo=m((XO,df)=>{"use strict";var bA=yi(),cf=hi(),gA=Tr(),vA=Kt(),SA=oe(),yA=SA("iterator");df.exports=function(a){if(!gA(a))return cf(a,yA)||cf(a,"@@iterator")||vA[bA(a)]}});var hf=m((ZO,pf)=>{"use strict";var TA=Pe(),IA=Ke(),EA=Je(),xA=pi(),PA=Yo(),AA=TypeError;pf.exports=function(a,e){var t=arguments.length<2?PA(a):e;if(IA(t))return EA(TA(t,a));throw new AA(xA(a)+" is not iterable")}});var bf=m((eV,mf)=>{"use strict";var wA=Pe(),ff=Je(),kA=hi();mf.exports=function(a,e,t){var r,i;ff(a);try{if(r=kA(a,"return"),!r){if(e==="throw")throw t;return t}r=wA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return ff(r),t}});var Is=m((tV,yf)=>{"use strict";var RA=Pr(),$A=Pe(),LA=Je(),MA=pi(),CA=lf(),DA=Rr(),gf=di(),OA=hf(),VA=Yo(),vf=bf(),BA=TypeError,Ts=function(a,e){this.stopped=a,this.result=e},Sf=Ts.prototype;yf.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=RA(e,r),l,d,c,p,h,f,b,g=function(y){return l&&vf(l,"normal",y),new Ts(!0,y)},v=function(y){return i?(LA(y),o?u(y[0],y[1],g):u(y[0],y[1])):o?u(y,g):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(d=VA(a),!d)throw new BA(MA(a)+" is not iterable");if(CA(d)){for(c=0,p=DA(a);p>c;c++)if(h=v(a[c]),h&&gf(Sf,h))return h;return new Ts(!1)}l=OA(a,d)}for(f=s?a.next:l.next;!(b=$A(f,l)).done;){try{h=v(b.value)}catch(y){vf(l,"throw",y)}if(typeof h=="object"&&h&&gf(Sf,h))return h}return new Ts(!1)}});var If=m((rV,Tf)=>{"use strict";var _A=xe(),NA=zt(),FA=ci();Tf.exports=function(a,e,t){_A?NA.f(a,e,FA(0,t)):a[e]=t}});var Ef=m(()=>{"use strict";var qA=X(),UA=Is(),HA=If();qA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return UA(e,function(r,i){HA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Pf=m((sV,xf)=>{"use strict";Wo();Ef();var jA=Ir();xf.exports=jA.Object.fromEntries});var wf=m((nV,Af)=>{"use strict";Af.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Rf=m(()=>{"use strict";Wo();var QA=wf(),GA=z(),WA=Ti(),kf=Kt();for(Es in QA)WA(GA[Es],Es),kf[Es]=kf.Array;var Es});var Lf=m((lV,$f)=>{"use strict";var YA=Pf();Rf();$f.exports=YA});var zo=m((cV,Mf)=>{"use strict";var zA=Lf();Mf.exports=zA});var Cf=m(()=>{"use strict"});var Ko=m((hV,Df)=>{"use strict";var xi=z(),KA=Yt(),JA=Gt(),xs=function(a){return KA.slice(0,a.length)===a};Df.exports=function(){return xs("Bun/")?"BUN":xs("Cloudflare-Workers")?"CLOUDFLARE":xs("Deno/")?"DENO":xs("Node.js/")?"NODE":xi.Bun&&typeof Bun.version=="string"?"BUN":xi.Deno&&typeof Deno.version=="object"?"DENO":JA(xi.process)==="process"?"NODE":xi.window&&xi.document?"BROWSER":"REST"}()});var Ps=m((fV,Of)=>{"use strict";var XA=Ko();Of.exports=XA==="NODE"});var Bf=m((mV,Vf)=>{"use strict";var ZA=zt();Vf.exports=function(a,e,t){return ZA.f(a,e,t)}});var Ff=m((bV,Nf)=>{"use strict";var ew=at(),tw=Bf(),rw=oe(),iw=xe(),_f=rw("species");Nf.exports=function(a){var e=ew(a);iw&&e&&!e[_f]&&tw(e,_f,{configurable:!0,get:function(){return this}})}});var Uf=m((gV,qf)=>{"use strict";var aw=di(),sw=TypeError;qf.exports=function(a,e){if(aw(e,a))return a;throw new sw("Incorrect invocation")}});var Xo=m((vV,Hf)=>{"use strict";var nw=te(),ow=Y(),Jo=fi(),uw=nw(Function.toString);ow(Jo.inspectSource)||(Jo.inspectSource=function(a){return uw(a)});Hf.exports=Jo.inspectSource});var eu=m((SV,Yf)=>{"use strict";var lw=te(),cw=ne(),jf=Y(),dw=yi(),pw=at(),hw=Xo(),Qf=function(){},Gf=pw("Reflect","construct"),Zo=/^\s*(?:class|function)\b/,fw=lw(Zo.exec),mw=!Zo.test(Qf),Pi=function(e){if(!jf(e))return!1;try{return Gf(Qf,[],e),!0}catch(t){return!1}},Wf=function(e){if(!jf(e))return!1;switch(dw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return mw||!!fw(Zo,hw(e))}catch(t){return!0}};Wf.sham=!0;Yf.exports=!Gf||cw(function(){var a;return Pi(Pi.call)||!Pi(Object)||!Pi(function(){a=!0})||a})?Wf:Pi});var Kf=m((yV,zf)=>{"use strict";var bw=eu(),gw=pi(),vw=TypeError;zf.exports=function(a){if(bw(a))return a;throw new vw(gw(a)+" is not a constructor")}});var tu=m((TV,Xf)=>{"use strict";var Jf=Je(),Sw=Kf(),yw=Tr(),Tw=oe(),Iw=Tw("species");Xf.exports=function(a,e){var t=Jf(a).constructor,r;return t===void 0||yw(r=Jf(t)[Iw])?e:Sw(r)}});var em=m((IV,Zf)=>{"use strict";var Ew=te();Zf.exports=Ew([].slice)});var rm=m((EV,tm)=>{"use strict";var xw=TypeError;tm.exports=function(a,e){if(a<e)throw new xw("Not enough arguments");return a}});var ru=m((xV,im)=>{"use strict";var Pw=Yt();im.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Pw)});var du=m((PV,pm)=>{"use strict";var we=z(),Aw=jn(),ww=Pr(),am=Y(),kw=He(),dm=ne(),sm=Oo(),Rw=em(),nm=ss(),$w=rm(),Lw=ru(),Mw=Ps(),uu=we.setImmediate,lu=we.clearImmediate,Cw=we.process,iu=we.Dispatch,Dw=we.Function,om=we.MessageChannel,Ow=we.String,au=0,Ai={},um="onreadystatechange",wi,Xt,su,nu;dm(function(){wi=we.location});var cu=function(a){if(kw(Ai,a)){var e=Ai[a];delete Ai[a],e()}},ou=function(a){return function(){cu(a)}},lm=function(a){cu(a.data)},cm=function(a){we.postMessage(Ow(a),wi.protocol+"//"+wi.host)};(!uu||!lu)&&(uu=function(e){$w(arguments.length,1);var t=am(e)?e:Dw(e),r=Rw(arguments,1);return Ai[++au]=function(){Aw(t,void 0,r)},Xt(au),au},lu=function(e){delete Ai[e]},Mw?Xt=function(a){Cw.nextTick(ou(a))}:iu&&iu.now?Xt=function(a){iu.now(ou(a))}:om&&!Lw?(su=new om,nu=su.port2,su.port1.onmessage=lm,Xt=ww(nu.postMessage,nu)):we.addEventListener&&am(we.postMessage)&&!we.importScripts&&wi&&wi.protocol!=="file:"&&!dm(cm)?(Xt=cm,we.addEventListener("message",lm,!1)):um in nm("script")?Xt=function(a){sm.appendChild(nm("script"))[um]=function(){sm.removeChild(this),cu(a)}}:Xt=function(a){setTimeout(ou(a),0)});pm.exports={set:uu,clear:lu}});var mm=m((AV,fm)=>{"use strict";var hm=z(),Vw=xe(),Bw=Object.getOwnPropertyDescriptor;fm.exports=function(a){if(!Vw)return hm[a];var e=Bw(hm,a);return e&&e.value}});var pu=m((wV,gm)=>{"use strict";var bm=function(){this.head=null,this.tail=null};bm.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}}};gm.exports=bm});var Sm=m((kV,vm)=>{"use strict";var _w=Yt();vm.exports=/ipad|iphone|ipod/i.test(_w)&&typeof Pebble!="undefined"});var Tm=m((RV,ym)=>{"use strict";var Nw=Yt();ym.exports=/web0s(?!.*chrome)/i.test(Nw)});var km=m(($V,wm)=>{"use strict";var Cr=z(),Fw=mm(),Im=Pr(),hu=du().set,qw=pu(),Uw=ru(),Hw=Sm(),jw=Tm(),fu=Ps(),Em=Cr.MutationObserver||Cr.WebKitMutationObserver,xm=Cr.document,Pm=Cr.process,As=Cr.Promise,gu=Fw("queueMicrotask"),Mr,mu,bu,ws,Am;gu||(ki=new qw,Ri=function(){var a,e;for(fu&&(a=Pm.domain)&&a.exit();e=ki.get();)try{e()}catch(t){throw ki.head&&Mr(),t}a&&a.enter()},!Uw&&!fu&&!jw&&Em&&xm?(mu=!0,bu=xm.createTextNode(""),new Em(Ri).observe(bu,{characterData:!0}),Mr=function(){bu.data=mu=!mu}):!Hw&&As&&As.resolve?(ws=As.resolve(void 0),ws.constructor=As,Am=Im(ws.then,ws),Mr=function(){Am(Ri)}):fu?Mr=function(){Pm.nextTick(Ri)}:(hu=Im(hu,Cr),Mr=function(){hu(Ri)}),gu=function(a){ki.head||Mr(),ki.add(a)});var ki,Ri;wm.exports=gu});var $m=m((LV,Rm)=>{"use strict";Rm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ks=m((MV,Lm)=>{"use strict";Lm.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Zt=m((CV,Mm)=>{"use strict";var Qw=z();Mm.exports=Qw.Promise});var Dr=m((DV,Vm)=>{"use strict";var Gw=z(),$i=Zt(),Ww=Y(),Yw=ho(),zw=Xo(),Kw=oe(),Cm=Ko(),Jw=Ue(),vu=Zn(),Dm=$i&&$i.prototype,Xw=Kw("species"),Su=!1,Om=Ww(Gw.PromiseRejectionEvent),Zw=Yw("Promise",function(){var a=zw($i),e=a!==String($i);if(!e&&vu===66||Jw&&!(Dm.catch&&Dm.finally))return!0;if(!vu||vu<51||!/native code/.test(a)){var t=new $i(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Xw]=r,Su=t.then(function(){})instanceof r,!Su)return!0}return!e&&(Cm==="BROWSER"||Cm==="DENO")&&!Om});Vm.exports={CONSTRUCTOR:Zw,REJECTION_EVENT:Om,SUBCLASSING:Su}});var Or=m((OV,_m)=>{"use strict";var Bm=Ke(),ek=TypeError,tk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new ek("Bad Promise constructor");e=r,t=i}),this.resolve=Bm(e),this.reject=Bm(t)};_m.exports.f=function(a){return new tk(a)}});var ib=m(()=>{"use strict";var rk=X(),ik=Ue(),Ms=Ps(),Pt=z(),Nr=Pe(),Nm=Lr(),Fm=jo(),ak=Ti(),sk=Ff(),nk=Ke(),Ls=Y(),ok=Ae(),uk=Uf(),lk=tu(),Qm=du().set,xu=km(),ck=$m(),dk=ks(),pk=pu(),Gm=Lo(),Cs=Zt(),Pu=Dr(),Wm=Or(),Ds="Promise",Ym=Pu.CONSTRUCTOR,hk=Pu.REJECTION_EVENT,fk=Pu.SUBCLASSING,yu=Gm.getterFor(Ds),mk=Gm.set,Vr=Cs&&Cs.prototype,er=Cs,Rs=Vr,zm=Pt.TypeError,Tu=Pt.document,Au=Pt.process,Iu=Wm.f,bk=Iu,gk=!!(Tu&&Tu.createEvent&&Pt.dispatchEvent),Km="unhandledrejection",vk="rejectionhandled",qm=0,Jm=1,Sk=2,wu=1,Xm=2,$s,Um,yk,Hm,Zm=function(a){var e;return ok(a)&&Ls(e=a.then)?e:!1},eb=function(a,e){var t=e.value,r=e.state===Jm,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{i?(r||(e.rejection===Xm&&Ik(e),e.rejection=wu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),d=!0)),u===a.promise?n(new zm("Promise-chain cycle")):(l=Zm(u))?Nr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},tb=function(a,e){a.notified||(a.notified=!0,xu(function(){for(var t=a.reactions,r;r=t.get();)eb(r,a);a.notified=!1,e&&!a.rejection&&Tk(a)}))},rb=function(a,e,t){var r,i;gk?(r=Tu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Pt.dispatchEvent(r)):r={promise:e,reason:t},!hk&&(i=Pt["on"+a])?i(r):a===Km&&ck("Unhandled promise rejection",t)},Tk=function(a){Nr(Qm,Pt,function(){var e=a.facade,t=a.value,r=jm(a),i;if(r&&(i=dk(function(){Ms?Au.emit("unhandledRejection",t,e):rb(Km,e,t)}),a.rejection=Ms||jm(a)?Xm:wu,i.error))throw i.value})},jm=function(a){return a.rejection!==wu&&!a.parent},Ik=function(a){Nr(Qm,Pt,function(){var e=a.facade;Ms?Au.emit("rejectionHandled",e):rb(vk,e,a.value)})},Br=function(a,e,t){return function(r){a(e,r,t)}},_r=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Sk,tb(a,!0))},Eu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new zm("Promise can't be resolved itself");var r=Zm(e);r?xu(function(){var i={done:!1};try{Nr(r,e,Br(Eu,i,a),Br(_r,i,a))}catch(s){_r(i,s,a)}}):(a.value=e,a.state=Jm,tb(a,!1))}catch(i){_r({done:!1},i,a)}}};if(Ym&&(er=function(e){uk(this,Rs),nk(e),Nr($s,this);var t=yu(this);try{e(Br(Eu,t),Br(_r,t))}catch(r){_r(t,r)}},Rs=er.prototype,$s=function(e){mk(this,{type:Ds,done:!1,notified:!1,parent:!1,reactions:new pk,rejection:!1,state:qm,value:void 0})},$s.prototype=Nm(Rs,"then",function(e,t){var r=yu(this),i=Iu(lk(this,er));return r.parent=!0,i.ok=Ls(e)?e:!0,i.fail=Ls(t)&&t,i.domain=Ms?Au.domain:void 0,r.state===qm?r.reactions.add(i):xu(function(){eb(i,r)}),i.promise}),Um=function(){var a=new $s,e=yu(a);this.promise=a,this.resolve=Br(Eu,e),this.reject=Br(_r,e)},Wm.f=Iu=function(a){return a===er||a===yk?new Um(a):bk(a)},!ik&&Ls(Cs)&&Vr!==Object.prototype)){Hm=Vr.then,fk||Nm(Vr,"then",function(e,t){var r=this;return new er(function(i,s){Nr(Hm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Vr.constructor}catch(a){}Fm&&Fm(Vr,Rs)}rk({global:!0,constructor:!0,wrap:!0,forced:Ym},{Promise:er});ak(er,Ds,!1,!0);sk(Ds)});var ub=m((_V,ob)=>{"use strict";var Ek=oe(),sb=Ek("iterator"),nb=!1;try{ab=0,ku={next:function(){return{done:!!ab++}},return:function(){nb=!0}},ku[sb]=function(){return this},Array.from(ku,function(){throw 2})}catch(a){}var ab,ku;ob.exports=function(a,e){try{if(!e&&!nb)return!1}catch(i){return!1}var t=!1;try{var r={};r[sb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Ru=m((NV,lb)=>{"use strict";var xk=Zt(),Pk=ub(),Ak=Dr().CONSTRUCTOR;lb.exports=Ak||!Pk(function(a){xk.all(a).then(void 0,function(){})})});var cb=m(()=>{"use strict";var wk=X(),kk=Pe(),Rk=Ke(),$k=Or(),Lk=ks(),Mk=Is(),Ck=Ru();wk({target:"Promise",stat:!0,forced:Ck},{all:function(e){var t=this,r=$k.f(t),i=r.resolve,s=r.reject,n=Lk(function(){var o=Rk(t.resolve),u=[],l=0,d=1;Mk(e,function(c){var p=l++,h=!1;d++,kk(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 pb=m(()=>{"use strict";var Dk=X(),Ok=Ue(),Vk=Dr().CONSTRUCTOR,Lu=Zt(),Bk=at(),_k=Y(),Nk=Lr(),db=Lu&&Lu.prototype;Dk({target:"Promise",proto:!0,forced:Vk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Ok&&_k(Lu)&&($u=Bk("Promise").prototype.catch,db.catch!==$u&&Nk(db,"catch",$u,{unsafe:!0}));var $u});var hb=m(()=>{"use strict";var Fk=X(),qk=Pe(),Uk=Ke(),Hk=Or(),jk=ks(),Qk=Is(),Gk=Ru();Fk({target:"Promise",stat:!0,forced:Gk},{race:function(e){var t=this,r=Hk.f(t),i=r.reject,s=jk(function(){var n=Uk(t.resolve);Qk(e,function(o){qk(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var fb=m(()=>{"use strict";var Wk=X(),Yk=Or(),zk=Dr().CONSTRUCTOR;Wk({target:"Promise",stat:!0,forced:zk},{reject:function(e){var t=Yk.f(this),r=t.reject;return r(e),t.promise}})});var Mu=m((YV,mb)=>{"use strict";var Kk=Je(),Jk=Ae(),Xk=Or();mb.exports=function(a,e){if(Kk(a),Jk(e)&&e.constructor===a)return e;var t=Xk.f(a),r=t.resolve;return r(e),t.promise}});var vb=m(()=>{"use strict";var Zk=X(),eR=at(),bb=Ue(),tR=Zt(),gb=Dr().CONSTRUCTOR,rR=Mu(),iR=eR("Promise"),aR=bb&&!gb;Zk({target:"Promise",stat:!0,forced:bb||gb},{resolve:function(e){return rR(aR&&this===iR?tR:this,e)}})});var Sb=m(()=>{"use strict";ib();cb();pb();hb();fb();vb()});var Eb=m(()=>{"use strict";var sR=X(),nR=Ue(),Os=Zt(),oR=ne(),Tb=at(),Ib=Y(),uR=tu(),yb=Mu(),lR=Lr(),Du=Os&&Os.prototype,cR=!!Os&&oR(function(){Du.finally.call({then:function(){}},function(){})});sR({target:"Promise",proto:!0,real:!0,forced:cR},{finally:function(a){var e=uR(this,Tb("Promise")),t=Ib(a);return this.then(t?function(r){return yb(e,a()).then(function(){return r})}:a,t?function(r){return yb(e,a()).then(function(){throw r})}:a)}});!nR&&Ib(Os)&&(Cu=Tb("Promise").prototype.finally,Du.finally!==Cu&&lR(Du,"finally",Cu,{unsafe:!0}));var Cu});var Pb=m((tB,xb)=>{"use strict";Cf();Sb();Eb();var dR=xt();xb.exports=dR("Promise","finally")});var wb=m((rB,Ab)=>{"use strict";var pR=Pb();Ab.exports=pR});var Vs=m((iB,kb)=>{"use strict";var hR=wb();kb.exports=hR});var qb=m(()=>{"use strict";var wR=X(),kR=wo().values;wR({target:"Object",stat:!0},{values:function(e){return kR(e)}})});var Hb=m((qB,Ub)=>{"use strict";qb();var RR=Ir();Ub.exports=RR.Object.values});var Qb=m((UB,jb)=>{"use strict";var $R=Hb();jb.exports=$R});var Mi=m((HB,Gb)=>{"use strict";var LR=Qb();Gb.exports=LR});var sg=m(()=>{"use strict";var WR=X(),YR=Er(),zR=Rr(),KR=gi(),JR=vi();WR({target:"Array",proto:!0},{at:function(e){var t=YR(this),r=zR(t),i=KR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});JR("at")});var og=m((g_,ng)=>{"use strict";sg();var XR=xt();ng.exports=XR("Array","at")});var lg=m((v_,ug)=>{"use strict";var ZR=og();ug.exports=ZR});var Ur=m((S_,cg)=>{"use strict";var e$=lg();cg.exports=e$});var il=m((XN,Fg)=>{"use strict";var V$=Gt();Fg.exports=Array.isArray||function(e){return V$(e)==="Array"}});var Ug=m((ZN,qg)=>{"use strict";var B$=TypeError,_$=9007199254740991;qg.exports=function(a){if(a>_$)throw B$("Maximum allowed index exceeded");return a}});var Qg=m((eF,jg)=>{"use strict";var N$=il(),F$=Rr(),q$=Ug(),U$=Pr(),Hg=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,d=n?U$(n,o):!1,c,p;l<r;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&N$(c)?(p=F$(c),u=Hg(a,e,c,p,u,s-1)-1):(q$(u+1),a[u]=c),u++),l++;return u};jg.exports=Hg});var zg=m((tF,Yg)=>{"use strict";var Gg=il(),H$=eu(),j$=Ae(),Q$=oe(),G$=Q$("species"),Wg=Array;Yg.exports=function(a){var e;return Gg(a)&&(e=a.constructor,H$(e)&&(e===Wg||Gg(e.prototype))?e=void 0:j$(e)&&(e=e[G$],e===null&&(e=void 0))),e===void 0?Wg:e}});var Jg=m((rF,Kg)=>{"use strict";var W$=zg();Kg.exports=function(a,e){return new(W$(a))(e===0?0:e)}});var Xg=m(()=>{"use strict";var Y$=X(),z$=Qg(),K$=Ke(),J$=Er(),X$=Rr(),Z$=Jg();Y$({target:"Array",proto:!0},{flatMap:function(e){var t=J$(this),r=X$(t),i;return K$(e),i=Z$(t,0),i.length=z$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Zg=m(()=>{"use strict";var eL=vi();eL("flatMap")});var tv=m((oF,ev)=>{"use strict";Xg();Zg();var tL=xt();ev.exports=tL("Array","flatMap")});var iv=m((uF,rv)=>{"use strict";var rL=tv();rv.exports=rL});var al=m((lF,av)=>{"use strict";var iL=iv();av.exports=iL});var Gi=m((SF,xv)=>{"use strict";var dL=yi(),pL=String;xv.exports=function(a){if(dL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return pL(a)}});var nl=m((yF,Pv)=>{"use strict";Pv.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 kv=m((TF,wv)=>{"use strict";var hL=te(),fL=Et(),mL=Gi(),ul=nl(),Av=hL("".replace),bL=RegExp("^["+ul+"]+"),gL=RegExp("(^|[^"+ul+"])["+ul+"]+$"),ol=function(a){return function(e){var t=mL(fL(e));return a&1&&(t=Av(t,bL,"")),a&2&&(t=Av(t,gL,"$1")),t}};wv.exports={start:ol(1),end:ol(2),trim:ol(3)}});var Mv=m((IF,Lv)=>{"use strict";var vL=Do().PROPER,SL=ne(),Rv=nl(),$v="\u200B\x85\u180E";Lv.exports=function(a){return SL(function(){return!!Rv[a]()||$v[a]()!==$v||vL&&Rv[a].name!==a})}});var ll=m((EF,Cv)=>{"use strict";var yL=kv().start,TL=Mv();Cv.exports=TL("trimStart")?function(){return yL(this)}:"".trimStart});var Ov=m(()=>{"use strict";var IL=X(),Dv=ll();IL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Dv},{trimLeft:Dv})});var Bv=m(()=>{"use strict";Ov();var EL=X(),Vv=ll();EL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Vv},{trimStart:Vv})});var Nv=m((kF,_v)=>{"use strict";Bv();var xL=xt();_v.exports=xL("String","trimLeft")});var qv=m((RF,Fv)=>{"use strict";var PL=Nv();Fv.exports=PL});var Hv=m(($F,Uv)=>{"use strict";var AL=qv();Uv.exports=AL});var sS=m(()=>{"use strict"});var nS=m(()=>{"use strict"});var uS=m((e1,oS)=>{"use strict";var zL=Ae(),KL=Gt(),JL=oe(),XL=JL("match");oS.exports=function(a){var e;return zL(a)&&((e=a[XL])!==void 0?!!e:KL(a)==="RegExp")}});var cS=m((t1,lS)=>{"use strict";var ZL=Je();lS.exports=function(){var a=ZL(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 hS=m((r1,pS)=>{"use strict";var eM=Pe(),tM=He(),rM=di(),iM=cS(),dS=RegExp.prototype;pS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in dS)&&!tM(a,"flags")&&rM(dS,a)?eM(iM,a):e}});var mS=m((i1,fS)=>{"use strict";var vl=te(),aM=Er(),sM=Math.floor,bl=vl("".charAt),nM=vl("".replace),gl=vl("".slice),oM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,uM=/\$([$&'`]|\d{1,2})/g;fS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=uM;return i!==void 0&&(i=aM(i),u=oM),nM(s,u,function(l,d){var c;switch(bl(d,0)){case"$":return"$";case"&":return a;case"`":return gl(e,0,t);case"'":return gl(e,n);case"<":c=i[gl(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=sM(p/10);return h===0?l:h<=o?r[h-1]===void 0?bl(d,1):r[h-1]+bl(d,1):l}c=r[p-1]}return c===void 0?"":c})}});var vS=m(()=>{"use strict";var lM=X(),cM=Pe(),yl=te(),bS=Et(),dM=Y(),pM=Tr(),hM=uS(),Yr=Gi(),fM=hi(),mM=hS(),bM=mS(),gM=oe(),vM=Ue(),SM=gM("replace"),yM=TypeError,Sl=yl("".indexOf),TM=yl("".replace),gS=yl("".slice),IM=Math.max;lM({target:"String",proto:!0},{replaceAll:function(e,t){var r=bS(this),i,s,n,o,u,l,d,c,p,h,f=0,b="";if(!pM(e)){if(i=hM(e),i&&(s=Yr(bS(mM(e))),!~Sl(s,"g")))throw new yM("`.replaceAll` does not allow non-global regexes");if(n=fM(e,SM),n)return cM(n,e,r,t);if(vM&&i)return TM(Yr(r),e,t)}for(o=Yr(r),u=Yr(e),l=dM(t),l||(t=Yr(t)),d=u.length,c=IM(1,d),p=Sl(o,u);p!==-1;)h=l?Yr(t(u,p,o)):bM(u,o,p,[],void 0,t),b+=gS(o,f,p)+h,f=p+d,p=p+c>o.length?-1:Sl(o,u,p+c);return f<o.length&&(b+=gS(o,f)),b}})});var yS=m((n1,SS)=>{"use strict";sS();nS();vS();var EM=xt();SS.exports=EM("String","replaceAll")});var IS=m((o1,TS)=>{"use strict";var xM=yS();TS.exports=xM});var xS=m((u1,ES)=>{"use strict";var PM=IS();ES.exports=PM});var AS=m((l1,PS)=>{"use strict";var AM=gi(),wM=Gi(),kM=Et(),RM=RangeError;PS.exports=function(e){var t=wM(kM(this)),r="",i=AM(e);if(i<0||i===1/0)throw new RM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var LS=m((c1,$S)=>{"use strict";var RS=te(),$M=So(),wS=Gi(),LM=AS(),MM=Et(),CM=RS(LM),DM=RS("".slice),OM=Math.ceil,kS=function(a){return function(e,t,r){var i=wS(MM(e)),s=$M(t),n=i.length,o=r===void 0?" ":wS(r),u,l;return s<=n||o===""?i:(u=s-n,l=CM(o,OM(u/o.length)),l.length>u&&(l=DM(l,0,u)),a?i+l:l+i)}};$S.exports={start:kS(!1),end:kS(!0)}});var CS=m((d1,MS)=>{"use strict";var VM=Yt();MS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(VM)});var DS=m(()=>{"use strict";var BM=X(),_M=LS().start,NM=CS();BM({target:"String",proto:!0,forced:NM},{padStart:function(e){return _M(this,e,arguments.length>1?arguments[1]:void 0)}})});var VS=m((f1,OS)=>{"use strict";DS();var FM=xt();OS.exports=FM("String","padStart")});var _S=m((m1,BS)=>{"use strict";var qM=VS();BS.exports=qM});var FS=m((b1,NS)=>{"use strict";var UM=_S();NS.exports=UM});var Vc="2.0.119-dev.df6b2fd8.0";var fe=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(fe||{}),It=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(It||{});var rs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(rs||{}),qn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(qn||{});var Un=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Un||{}),oi=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(oi||{});var mT=C(Xe(),1);import{assertNever as Dp,assertNonNullable as ex,isNonNullable as os,ValueSubject as To,Subject as tx,Subscription as rx,merge as ix,observableFrom as ax,fromEvent as $p,map as Lp,tap as Mp,filterChanged as sx,isNullable as Io,ErrorCategory as Cp}from"@vkontakte/videoplayer-shared/es2018";var Rp=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 us=class{constructor(e){this.connection$=new To(void 0);this.castState$=new To("NOT_AVAILABLE");this.errorEvent$=new tx;this.realCastState$=new To("NOT_AVAILABLE");this.subscription=new rx;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=os((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Rp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Cp.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(){os(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Io(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Io(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($p(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 Dp(i.sessionState)}})).add(ix($p(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Mp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Lp(i=>i.castState)),ax([r.getCastState()])).pipe(sx(),Lp(nx),Mp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=os(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();ex(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Io(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"?os(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:Cp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},nx=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 Dp(a)}};var zl=C(Xe(),1),Ky=C($r(),1),Jy=C(zo(),1);var _b=C(Vs(),1);import{assertNever as Rb}from"@vkontakte/videoplayer-shared/es2018";var ue=(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:Rb(t)}return a},Bs=(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:Rb(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as fR,Subject as _s,merge as $b}from"@vkontakte/videoplayer-shared/es2018";var $=class{constructor(e){this.transitionStarted$=new _s;this.transitionEnded$=new _s;this.transitionUpdated$=new _s;this.forceChanged$=new _s;this.stateChangeStarted$=$b(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=$b(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||fR(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 mR}from"@vkontakte/videoplayer-shared/es2018";var Lb=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 mR(a)}};import{assertNever as Fr,assertNonNullable as tr,debounce as Mb,ErrorCategory as Cb,fromEvent as rr,isNonNullable as Db,map as Ob,merge as Vb,observableFrom as bR,Subject as gR,Subscription as Ou,timeout as vR,getHighestQuality as SR}from"@vkontakte/videoplayer-shared/es2018";var yR=5,TR=5,IR=500,Bb=7e3,Li=class{constructor(e){this.subscription=new Ou;this.loadMediaTimeoutSubscription=new Ou;this.videoState=new $("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:Fr(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:Fr(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:Fr(e)}break}default:Fr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Lb(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 Ou;this.subscription.add(e),this.subscription.add(Vb(this.videoState.stateChangeStarted$.pipe(Ob(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Ob(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 gR;e.add(i.pipe(Mb(IR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(rr(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)>yR)&&i.next(o),s=o})),e.add(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(rr(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<TR&&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:Fr(n)}}),t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Vb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,bR(["init"])).pipe(Mb(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];tr(d);let c=SR(Object.keys(d));tr(c);let p=d[c];tr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];tr(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];tr(d),r=d.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];tr(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];tr(d),r=ue(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:Cb.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Fr(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 Db(o)&&(n.metadata.title=o),Db(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(vR(Bb).subscribe(()=>s(`timeout(${Bb})`)))});(0,_b.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:Cb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var tl=C(Xe(),1);import{clearVideoElement as Fb}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as ER}from"@vkontakte/videoplayer-shared/es2018";var Nb=a=>{try{a.pause(),a.playbackRate=0,ER(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as xR,Subscription as PR}from"@vkontakte/videoplayer-shared/es2018";var Vu=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)}},Bu=window.WeakMap?new WeakMap:new Vu,_u=window.WeakMap?new WeakMap:new Map,AR=(a,e=20)=>{let t=0;return xR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},me=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Fb(t):(t=document.createElement("video"),a.appendChild(t)),Bu.set(t,r);let i=new PR;return i.add(AR(t,e)),_u.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},be=a=>{let e=_u.get(a);e==null||e.unsubscribe(),_u.delete(a);let t=Bu.get(a);Bu.delete(a),t?Fb(a):Nb(a)};var Fu=C(Mi(),1);import{assertNonNullable as Ci,isNonNullable as et,isNullable as DR,fromEvent as qr,merge as Wb,observableFrom as Yb,filterChanged as zb,map as Di,Subject as Kb,Subscription as OR,ValueSubject as VR,ErrorCategory as BR}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Nu,isNullable as MR,Subscription as CR}from"@vkontakte/videoplayer-shared/es2018";var Ns=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=MR(i),l=new CR;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},Ze=(a,e,t)=>Ns(e,()=>a.loop,r=>{Nu(r)&&(a.loop=r)},{onError:t}),ge=(a,e,t,r)=>Ns(e,()=>({muted:a.muted,volume:a.volume}),i=>{Nu(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}),Ce=(a,e,t,r)=>Ns(e,()=>a.playbackRate,i=>{Nu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),At=Ns;var _R=a=>["__",a.language,a.label].join("|"),NR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},qu=class a{constructor(){this.available$=new Kb;this.current$=new VR(void 0);this.error$=new Kb;this.subscription=new OR;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:BR.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(At(t.internalTextTracks,()=>(0,Fu.default)(this.internalTracks),s=>{et(s)&&this.setInternal(s)},{equal:(s,n)=>et(s)&&et(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Di(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(At(t.externalTextTracks,()=>(0,Fu.default)(this.externalTracks),s=>{et(s)&&this.setExternal(s)},{equal:(s,n)=>et(s)&&et(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Di(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(At(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(At(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ci(this.video);let{textTracks:e}=this.video;this.subscription.add(qr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Wb(qr(e,"addtrack"),qr(e,"removetrack"),Yb(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),zb((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(Wb(qr(e,"change"),Yb(["init"])).pipe(Di(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Di(r=>r&&this.htmlTextTrackToITextTrack(r).id),zb()).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(qr(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(qr(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;et(t.align)&&(i.align=t.align),et(t.position)&&(i.position=t.position),et(t.size)&&(i.size=t.size),et(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Ci(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:_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:(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){Ci(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(DR(e)||!NR(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Ci(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){Ci(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)}},De=qu;var ot=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 Jb=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},Uu=a=>{let e=Jb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Xb=a=>{let e=Jb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Oe,map as wt,merge as eg,filterChanged as qR,isNonNullable as tg,Subject as UR,filter as rg,mapTo as ig,combine as HR,once as jR,ErrorCategory as QR,ValueSubject as ag,clientChecker as GR}from"@vkontakte/videoplayer-shared/es2018";var FR=3,Zb=(a,e,t=FR)=>{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 ve=a=>{let e=T=>Oe(a,T).pipe(ig(void 0)),r=eg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Oe(a,T))).pipe(wt(T=>T.type==="ended"?a.readyState<2:a.readyState<3),qR()),i=eg(Oe(a,"progress"),Oe(a,"timeupdate")).pipe(wt(()=>Zb(a.buffered,a.currentTime))),s=GR.isSafari?HR({play:e("play").pipe(jR()),playing:e("playing")}).pipe(ig(void 0)):e("playing"),n=Oe(a,"volumechange").pipe(wt(()=>({muted:a.muted,volume:a.volume}))),o=Oe(a,"ratechange").pipe(wt(()=>a.playbackRate)),u=Oe(a,"error").pipe(rg(()=>!!(a.error||a.played.length)),wt(()=>{var E;let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:QR.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=Oe(a,"timeupdate").pipe(wt(()=>a.currentTime)),d=new UR,c=.3,p;l.subscribe(T=>{a.loop&&tg(p)&&tg(T)&&p>=a.duration-c&&T<=c&&d.next(p),p=T});let h=e("pause").pipe(rg(()=>!a.error&&p!==a.duration)),f=Oe(a,"enterpictureinpicture"),b=Oe(a,"leavepictureinpicture"),g=new ag(Xb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new ag(Uu(a));return Oe(a,"fullscreenchange").pipe(wt(()=>Uu(a))).subscribe(v),{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$:Oe(a,"durationchange").pipe(wt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as kt}from"@vkontakte/videoplayer-shared/es2018";var Rt=a=>{switch(a){case"mobile":return kt.Q_144P;case"lowest":return kt.Q_240P;case"low":return kt.Q_360P;case"sd":case"medium":return kt.Q_480P;case"hd":case"high":return kt.Q_720P;case"fullhd":case"full":return kt.Q_1080P;case"quadhd":case"quad":return kt.Q_1440P;case"ultrahd":case"ultra":return kt.Q_2160P}};var $t=C(Ur(),1),gg=C(Xe(),1),qs=C($r(),1);import{isNonNullable as re,isNullable as ju,now as vg,isHigher as Qu,isHigherOrEqual as Gu,isInvariantQuality as fg,isLower as mg,isLowerOrEqual as Wu,videoSizeToQuality as t$,assertNotEmptyArray as Sg,assertNonNullable as r$}from"@vkontakte/videoplayer-shared/es2018";var Hu=!1,ut={},dg=a=>{Hu=a},pg=()=>{ut={}},hg=a=>{a(ut)},Oi=(a,e)=>{var t;Hu&&(ut.meta=(t=ut.meta)!=null?t:{},ut.meta[a]=e)},de=class{constructor(e){this.name=e}next(e){var r,i;if(!Hu)return;ut.series=(r=ut.series)!=null?r:{};let t=(i=ut.series[this.name])!=null?i:[];t.push([Date.now(),e]),ut.series[this.name]=t}};function Fs({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}var i$=new de("best_bitrate"),yg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Yu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Vi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=vg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Tg='Assertion "ABR Tracks is empty array" failed',Us=(a,e,t,r)=>{var u;let i=[...e].sort(Yu(1)),s=[...t].sort(Yu(1)),n=s.filter(l=>re(l.bitrate)&&re(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,$t.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,$t.default)(s,-1);return o&&(0,gg.default)(n,o)?o:n.length?(0,$t.default)(n,-1):(0,$t.default)(s,0)},bg=a=>"quality"in a,Ig=(a,e,t,r)=>{var n;let i=re((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&re(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&vg()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=bg(o)?"video":"audio",l=bg(o)?o.quality:o.bitrate;return e({message:`
|
|
6
|
+
var PT=Object.create;var Mc=Object.defineProperty;var AT=Object.getOwnPropertyDescriptor;var wT=Object.getOwnPropertyNames;var kT=Object.getPrototypeOf,RT=Object.prototype.hasOwnProperty;var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var $T=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of wT(e))!RT.call(a,i)&&i!==t&&Mc(a,i,{get:()=>e[i],enumerable:!(r=AT(e,i))||r.enumerable});return a};var B=(a,e,t)=>(t=a!=null?PT(kT(a)):{},$T(e||!a||!a.__esModule?Mc(t,"default",{value:a,enumerable:!0}):t,a));var z=m((Fn,Dc)=>{"use strict";var oi=function(a){return a&&a.Math===Math&&a};Dc.exports=oi(typeof globalThis=="object"&&globalThis)||oi(typeof window=="object"&&window)||oi(typeof self=="object"&&self)||oi(typeof global=="object"&&global)||oi(typeof Fn=="object"&&Fn)||function(){return this}()||Function("return this")()});var ue=m((KC,Oc)=>{"use strict";Oc.exports=function(a){try{return!!a()}catch(e){return!0}}});var ui=m((JC,Bc)=>{"use strict";var LT=ue();Bc.exports=!LT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var qn=m((XC,Fc)=>{"use strict";var MT=ui(),Nc=Function.prototype,Vc=Nc.apply,_c=Nc.call;Fc.exports=typeof Reflect=="object"&&Reflect.apply||(MT?_c.bind(Vc):function(){return _c.apply(Vc,arguments)})});var te=m((ZC,Hc)=>{"use strict";var qc=ui(),Uc=Function.prototype,Un=Uc.call,CT=qc&&Uc.bind.bind(Un,Un);Hc.exports=qc?CT:function(a){return function(){return Un.apply(a,arguments)}}});var Qt=m((eD,Gc)=>{"use strict";var jc=te(),DT=jc({}.toString),OT=jc("".slice);Gc.exports=function(a){return OT(DT(a),8,-1)}});var Hn=m((tD,Qc)=>{"use strict";var BT=Qt(),VT=te();Qc.exports=function(a){if(BT(a)==="Function")return VT(a)}});var Y=m((rD,Wc)=>{"use strict";var jn=typeof document=="object"&&document.all;Wc.exports=typeof jn=="undefined"&&jn!==void 0?function(a){return typeof a=="function"||a===jn}:function(a){return typeof a=="function"}});var xe=m((iD,Yc)=>{"use strict";var _T=ue();Yc.exports=!_T(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Pe=m((aD,zc)=>{"use strict";var NT=ui(),rs=Function.prototype.call;zc.exports=NT?rs.bind(rs):function(){return rs.apply(rs,arguments)}});var Gn=m(Xc=>{"use strict";var Kc={}.propertyIsEnumerable,Jc=Object.getOwnPropertyDescriptor,FT=Jc&&!Kc.call({1:2},1);Xc.f=FT?function(e){var t=Jc(this,e);return!!t&&t.enumerable}:Kc});var li=m((nD,Zc)=>{"use strict";Zc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var td=m((oD,ed)=>{"use strict";var qT=te(),UT=ue(),HT=Qt(),Qn=Object,jT=qT("".split);ed.exports=UT(function(){return!Qn("z").propertyIsEnumerable(0)})?function(a){return HT(a)==="String"?jT(a,""):Qn(a)}:Qn});var Ir=m((uD,rd)=>{"use strict";rd.exports=function(a){return a==null}});var xt=m((lD,id)=>{"use strict";var GT=Ir(),QT=TypeError;id.exports=function(a){if(GT(a))throw new QT("Can't call method on "+a);return a}});var Wt=m((cD,ad)=>{"use strict";var WT=td(),YT=xt();ad.exports=function(a){return WT(YT(a))}});var Ae=m((dD,sd)=>{"use strict";var zT=Y();sd.exports=function(a){return typeof a=="object"?a!==null:zT(a)}});var Er=m((pD,nd)=>{"use strict";nd.exports={}});var at=m((hD,ud)=>{"use strict";var Wn=Er(),Yn=z(),KT=Y(),od=function(a){return KT(a)?a:void 0};ud.exports=function(a,e){return arguments.length<2?od(Wn[a])||od(Yn[a]):Wn[a]&&Wn[a][e]||Yn[a]&&Yn[a][e]}});var ci=m((fD,ld)=>{"use strict";var JT=te();ld.exports=JT({}.isPrototypeOf)});var Yt=m((mD,pd)=>{"use strict";var XT=z(),cd=XT.navigator,dd=cd&&cd.userAgent;pd.exports=dd?String(dd):""});var Kn=m((bD,vd)=>{"use strict";var gd=z(),zn=Yt(),hd=gd.process,fd=gd.Deno,md=hd&&hd.versions||fd&&fd.version,bd=md&&md.v8,Ue,is;bd&&(Ue=bd.split("."),is=Ue[0]>0&&Ue[0]<4?1:+(Ue[0]+Ue[1]));!is&&zn&&(Ue=zn.match(/Edge\/(\d+)/),(!Ue||Ue[1]>=74)&&(Ue=zn.match(/Chrome\/(\d+)/),Ue&&(is=+Ue[1])));vd.exports=is});var Jn=m((gD,yd)=>{"use strict";var Sd=Kn(),ZT=ue(),eI=z(),tI=eI.String;yd.exports=!!Object.getOwnPropertySymbols&&!ZT(function(){var a=Symbol("symbol detection");return!tI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Sd&&Sd<41})});var Xn=m((vD,Td)=>{"use strict";var rI=Jn();Td.exports=rI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Zn=m((SD,Id)=>{"use strict";var iI=at(),aI=Y(),sI=ci(),nI=Xn(),oI=Object;Id.exports=nI?function(a){return typeof a=="symbol"}:function(a){var e=iI("Symbol");return aI(e)&&sI(e.prototype,oI(a))}});var di=m((yD,Ed)=>{"use strict";var uI=String;Ed.exports=function(a){try{return uI(a)}catch(e){return"Object"}}});var Ke=m((TD,xd)=>{"use strict";var lI=Y(),cI=di(),dI=TypeError;xd.exports=function(a){if(lI(a))return a;throw new dI(cI(a)+" is not a function")}});var pi=m((ID,Pd)=>{"use strict";var pI=Ke(),hI=Ir();Pd.exports=function(a,e){var t=a[e];return hI(t)?void 0:pI(t)}});var wd=m((ED,Ad)=>{"use strict";var eo=Pe(),to=Y(),ro=Ae(),fI=TypeError;Ad.exports=function(a,e){var t,r;if(e==="string"&&to(t=a.toString)&&!ro(r=eo(t,a))||to(t=a.valueOf)&&!ro(r=eo(t,a))||e!=="string"&&to(t=a.toString)&&!ro(r=eo(t,a)))return r;throw new fI("Can't convert object to primitive value")}});var He=m((xD,kd)=>{"use strict";kd.exports=!0});var Ld=m((PD,$d)=>{"use strict";var Rd=z(),mI=Object.defineProperty;$d.exports=function(a,e){try{mI(Rd,a,{value:e,configurable:!0,writable:!0})}catch(t){Rd[a]=e}return e}});var hi=m((AD,Dd)=>{"use strict";var bI=He(),gI=z(),vI=Ld(),Md="__core-js_shared__",Cd=Dd.exports=gI[Md]||vI(Md,{});(Cd.versions||(Cd.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 io=m((wD,Bd)=>{"use strict";var Od=hi();Bd.exports=function(a,e){return Od[a]||(Od[a]=e||{})}});var xr=m((kD,Vd)=>{"use strict";var SI=xt(),yI=Object;Vd.exports=function(a){return yI(SI(a))}});var je=m((RD,_d)=>{"use strict";var TI=te(),II=xr(),EI=TI({}.hasOwnProperty);_d.exports=Object.hasOwn||function(e,t){return EI(II(e),t)}});var ao=m(($D,Nd)=>{"use strict";var xI=te(),PI=0,AI=Math.random(),wI=xI(1 .toString);Nd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+wI(++PI+AI,36)}});var le=m((LD,qd)=>{"use strict";var kI=z(),RI=io(),Fd=je(),$I=ao(),LI=Jn(),MI=Xn(),Pr=kI.Symbol,so=RI("wks"),CI=MI?Pr.for||Pr:Pr&&Pr.withoutSetter||$I;qd.exports=function(a){return Fd(so,a)||(so[a]=LI&&Fd(Pr,a)?Pr[a]:CI("Symbol."+a)),so[a]}});var Gd=m((MD,jd)=>{"use strict";var DI=Pe(),Ud=Ae(),Hd=Zn(),OI=pi(),BI=wd(),VI=le(),_I=TypeError,NI=VI("toPrimitive");jd.exports=function(a,e){if(!Ud(a)||Hd(a))return a;var t=OI(a,NI),r;if(t){if(e===void 0&&(e="default"),r=DI(t,a,e),!Ud(r)||Hd(r))return r;throw new _I("Can't convert object to primitive value")}return e===void 0&&(e="number"),BI(a,e)}});var no=m((CD,Qd)=>{"use strict";var FI=Gd(),qI=Zn();Qd.exports=function(a){var e=FI(a,"string");return qI(e)?e:e+""}});var as=m((DD,Yd)=>{"use strict";var UI=z(),Wd=Ae(),oo=UI.document,HI=Wd(oo)&&Wd(oo.createElement);Yd.exports=function(a){return HI?oo.createElement(a):{}}});var uo=m((OD,zd)=>{"use strict";var jI=xe(),GI=ue(),QI=as();zd.exports=!jI&&!GI(function(){return Object.defineProperty(QI("div"),"a",{get:function(){return 7}}).a!==7})});var Xd=m(Jd=>{"use strict";var WI=xe(),YI=Pe(),zI=Gn(),KI=li(),JI=Wt(),XI=no(),ZI=je(),eE=uo(),Kd=Object.getOwnPropertyDescriptor;Jd.f=WI?Kd:function(e,t){if(e=JI(e),t=XI(t),eE)try{return Kd(e,t)}catch(r){}if(ZI(e,t))return KI(!YI(zI.f,e,t),e[t])}});var lo=m((VD,Zd)=>{"use strict";var tE=ue(),rE=Y(),iE=/#|\.prototype\./,fi=function(a,e){var t=sE[aE(a)];return t===oE?!0:t===nE?!1:rE(e)?tE(e):!!e},aE=fi.normalize=function(a){return String(a).replace(iE,".").toLowerCase()},sE=fi.data={},nE=fi.NATIVE="N",oE=fi.POLYFILL="P";Zd.exports=fi});var Ar=m((_D,tp)=>{"use strict";var ep=Hn(),uE=Ke(),lE=ui(),cE=ep(ep.bind);tp.exports=function(a,e){return uE(a),e===void 0?a:lE?cE(a,e):function(){return a.apply(e,arguments)}}});var co=m((ND,rp)=>{"use strict";var dE=xe(),pE=ue();rp.exports=dE&&pE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Je=m((FD,ip)=>{"use strict";var hE=Ae(),fE=String,mE=TypeError;ip.exports=function(a){if(hE(a))return a;throw new mE(fE(a)+" is not an object")}});var zt=m(sp=>{"use strict";var bE=xe(),gE=uo(),vE=co(),ss=Je(),ap=no(),SE=TypeError,po=Object.defineProperty,yE=Object.getOwnPropertyDescriptor,ho="enumerable",fo="configurable",mo="writable";sp.f=bE?vE?function(e,t,r){if(ss(e),t=ap(t),ss(r),typeof e=="function"&&t==="prototype"&&"value"in r&&mo in r&&!r[mo]){var i=yE(e,t);i&&i[mo]&&(e[t]=r.value,r={configurable:fo in r?r[fo]:i[fo],enumerable:ho in r?r[ho]:i[ho],writable:!1})}return po(e,t,r)}:po:function(e,t,r){if(ss(e),t=ap(t),ss(r),gE)try{return po(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new SE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var wr=m((UD,np)=>{"use strict";var TE=xe(),IE=zt(),EE=li();np.exports=TE?function(a,e,t){return IE.f(a,e,EE(1,t))}:function(a,e,t){return a[e]=t,a}});var X=m((HD,up)=>{"use strict";var mi=z(),xE=qn(),PE=Hn(),AE=Y(),wE=Xd().f,kE=lo(),kr=Er(),RE=Ar(),Rr=wr(),op=je();hi();var $E=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 xE(a,this,arguments)};return e.prototype=a.prototype,e};up.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?mi:i?mi[t]:mi[t]&&mi[t].prototype,o=r?kr:kr[t]||Rr(kr,t,{})[t],u=o.prototype,l,d,c,p,h,f,b,g,v;for(p in e)l=kE(r?p:t+(i?".":"#")+p,a.forced),d=!l&&n&&op(n,p),f=o[p],d&&(a.dontCallGetSet?(v=wE(n,p),b=v&&v.value):b=n[p]),h=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&d?g=RE(h,mi):a.wrap&&d?g=$E(h):s&&AE(h)?g=PE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Rr(g,"sham",!0),Rr(o,p,g),s&&(c=t+"Prototype",op(kr,c)||Rr(kr,c,{}),Rr(kr[c],p,h),a.real&&u&&(l||!u[p])&&Rr(u,p,h)))}});var cp=m((jD,lp)=>{"use strict";var LE=Math.ceil,ME=Math.floor;lp.exports=Math.trunc||function(e){var t=+e;return(t>0?ME:LE)(t)}});var bi=m((GD,dp)=>{"use strict";var CE=cp();dp.exports=function(a){var e=+a;return e!==e||e===0?0:CE(e)}});var hp=m((QD,pp)=>{"use strict";var DE=bi(),OE=Math.max,BE=Math.min;pp.exports=function(a,e){var t=DE(a);return t<0?OE(t+e,0):BE(t,e)}});var bo=m((WD,fp)=>{"use strict";var VE=bi(),_E=Math.min;fp.exports=function(a){var e=VE(a);return e>0?_E(e,9007199254740991):0}});var $r=m((YD,mp)=>{"use strict";var NE=bo();mp.exports=function(a){return NE(a.length)}});var go=m((zD,gp)=>{"use strict";var FE=Wt(),qE=hp(),UE=$r(),bp=function(a){return function(e,t,r){var i=FE(e),s=UE(i);if(s===0)return!a&&-1;var n=qE(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}};gp.exports={includes:bp(!0),indexOf:bp(!1)}});var gi=m((KD,vp)=>{"use strict";vp.exports=function(){}});var Sp=m(()=>{"use strict";var HE=X(),jE=go().includes,GE=ue(),QE=gi(),WE=GE(function(){return!Array(1).includes()});HE({target:"Array",proto:!0,forced:WE},{includes:function(e){return jE(this,e,arguments.length>1?arguments[1]:void 0)}});QE("includes")});var Pt=m((ZD,yp)=>{"use strict";var YE=at();yp.exports=YE});var Ip=m((eO,Tp)=>{"use strict";Sp();var zE=Pt();Tp.exports=zE("Array","includes")});var xp=m((tO,Ep)=>{"use strict";var KE=Ip();Ep.exports=KE});var Xe=m((rO,Pp)=>{"use strict";var JE=xp();Pp.exports=JE});var us=m((fO,Cp)=>{"use strict";var sx=io(),nx=ao(),Mp=sx("keys");Cp.exports=function(a){return Mp[a]||(Mp[a]=nx(a))}});var Op=m((mO,Dp)=>{"use strict";var ox=ue();Dp.exports=!ox(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ls=m((bO,Vp)=>{"use strict";var ux=je(),lx=Y(),cx=xr(),dx=us(),px=Op(),Bp=dx("IE_PROTO"),yo=Object,hx=yo.prototype;Vp.exports=px?yo.getPrototypeOf:function(a){var e=cx(a);if(ux(e,Bp))return e[Bp];var t=e.constructor;return lx(t)&&e instanceof t?t.prototype:e instanceof yo?hx:null}});var cs=m((gO,_p)=>{"use strict";_p.exports={}});var qp=m((vO,Fp)=>{"use strict";var fx=te(),To=je(),mx=Wt(),bx=go().indexOf,gx=cs(),Np=fx([].push);Fp.exports=function(a,e){var t=mx(a),r=0,i=[],s;for(s in t)!To(gx,s)&&To(t,s)&&Np(i,s);for(;e.length>r;)To(t,s=e[r++])&&(~bx(i,s)||Np(i,s));return i}});var Io=m((SO,Up)=>{"use strict";Up.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Eo=m((yO,Hp)=>{"use strict";var vx=qp(),Sx=Io();Hp.exports=Object.keys||function(e){return vx(e,Sx)}});var xo=m((TO,Yp)=>{"use strict";var Gp=xe(),yx=ue(),Qp=te(),Tx=ls(),Ix=Eo(),Ex=Wt(),xx=Gn().f,Wp=Qp(xx),Px=Qp([].push),Ax=Gp&&yx(function(){var a=Object.create(null);return a[2]=2,!Wp(a,2)}),jp=function(a){return function(e){for(var t=Ex(e),r=Ix(t),i=Ax&&Tx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Gp||(i?u in t:Wp(t,u)))&&Px(o,a?[u,t[u]]:t[u]);return o}};Yp.exports={entries:jp(!0),values:jp(!1)}});var zp=m(()=>{"use strict";var wx=X(),kx=xo().entries;wx({target:"Object",stat:!0},{entries:function(e){return kx(e)}})});var Jp=m((xO,Kp)=>{"use strict";zp();var Rx=Er();Kp.exports=Rx.Object.entries});var Zp=m((PO,Xp)=>{"use strict";var $x=Jp();Xp.exports=$x});var Lr=m((AO,eh)=>{"use strict";var Lx=Zp();eh.exports=Lx});var Kt=m((wO,th)=>{"use strict";th.exports={}});var ah=m((kO,ih)=>{"use strict";var Mx=z(),Cx=Y(),rh=Mx.WeakMap;ih.exports=Cx(rh)&&/native code/.test(String(rh))});var ko=m((RO,oh)=>{"use strict";var Dx=ah(),nh=z(),Ox=Ae(),Bx=wr(),Po=je(),Ao=hi(),Vx=us(),_x=cs(),sh="Object already initialized",wo=nh.TypeError,Nx=nh.WeakMap,ds,vi,ps,Fx=function(a){return ps(a)?vi(a):ds(a,{})},qx=function(a){return function(e){var t;if(!Ox(e)||(t=vi(e)).type!==a)throw new wo("Incompatible receiver, "+a+" required");return t}};Dx||Ao.state?(Ge=Ao.state||(Ao.state=new Nx),Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,ds=function(a,e){if(Ge.has(a))throw new wo(sh);return e.facade=a,Ge.set(a,e),e},vi=function(a){return Ge.get(a)||{}},ps=function(a){return Ge.has(a)}):(Jt=Vx("state"),_x[Jt]=!0,ds=function(a,e){if(Po(a,Jt))throw new wo(sh);return e.facade=a,Bx(a,Jt,e),e},vi=function(a){return Po(a,Jt)?a[Jt]:{}},ps=function(a){return Po(a,Jt)});var Ge,Jt;oh.exports={set:ds,get:vi,has:ps,enforce:Fx,getterFor:qx}});var Lo=m(($O,lh)=>{"use strict";var Ro=xe(),Ux=je(),uh=Function.prototype,Hx=Ro&&Object.getOwnPropertyDescriptor,$o=Ux(uh,"name"),jx=$o&&function(){}.name==="something",Gx=$o&&(!Ro||Ro&&Hx(uh,"name").configurable);lh.exports={EXISTS:$o,PROPER:jx,CONFIGURABLE:Gx}});var dh=m(ch=>{"use strict";var Qx=xe(),Wx=co(),Yx=zt(),zx=Je(),Kx=Wt(),Jx=Eo();ch.f=Qx&&!Wx?Object.defineProperties:function(e,t){zx(e);for(var r=Kx(t),i=Jx(t),s=i.length,n=0,o;s>n;)Yx.f(e,o=i[n++],r[o]);return e}});var Mo=m((MO,ph)=>{"use strict";var Xx=at();ph.exports=Xx("document","documentElement")});var Bo=m((CO,Sh)=>{"use strict";var Zx=Je(),eP=dh(),hh=Io(),tP=cs(),rP=Mo(),iP=as(),aP=us(),fh=">",mh="<",Do="prototype",Oo="script",gh=aP("IE_PROTO"),Co=function(){},vh=function(a){return mh+Oo+fh+a+mh+"/"+Oo+fh},bh=function(a){a.write(vh("")),a.close();var e=a.parentWindow.Object;return a=null,e},sP=function(){var a=iP("iframe"),e="java"+Oo+":",t;return a.style.display="none",rP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(vh("document.F=Object")),t.close(),t.F},hs,fs=function(){try{hs=new ActiveXObject("htmlfile")}catch(e){}fs=typeof document!="undefined"?document.domain&&hs?bh(hs):sP():bh(hs);for(var a=hh.length;a--;)delete fs[Do][hh[a]];return fs()};tP[gh]=!0;Sh.exports=Object.create||function(e,t){var r;return e!==null?(Co[Do]=Zx(e),r=new Co,Co[Do]=null,r[gh]=e):r=fs(),t===void 0?r:eP.f(r,t)}});var Mr=m((DO,yh)=>{"use strict";var nP=wr();yh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:nP(a,e,t),a}});var Fo=m((OO,Eh)=>{"use strict";var oP=ue(),uP=Y(),lP=Ae(),cP=Bo(),Th=ls(),dP=Mr(),pP=le(),hP=He(),No=pP("iterator"),Ih=!1,st,Vo,_o;[].keys&&(_o=[].keys(),"next"in _o?(Vo=Th(Th(_o)),Vo!==Object.prototype&&(st=Vo)):Ih=!0);var fP=!lP(st)||oP(function(){var a={};return st[No].call(a)!==a});fP?st={}:hP&&(st=cP(st));uP(st[No])||dP(st,No,function(){return this});Eh.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:Ih}});var ms=m((BO,Ph)=>{"use strict";var mP=le(),bP=mP("toStringTag"),xh={};xh[bP]="z";Ph.exports=String(xh)==="[object z]"});var Si=m((VO,Ah)=>{"use strict";var gP=ms(),vP=Y(),bs=Qt(),SP=le(),yP=SP("toStringTag"),TP=Object,IP=bs(function(){return arguments}())==="Arguments",EP=function(a,e){try{return a[e]}catch(t){}};Ah.exports=gP?bs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=EP(e=TP(a),yP))=="string"?t:IP?bs(e):(r=bs(e))==="Object"&&vP(e.callee)?"Arguments":r}});var kh=m((_O,wh)=>{"use strict";var xP=ms(),PP=Si();wh.exports=xP?{}.toString:function(){return"[object "+PP(this)+"]"}});var yi=m((NO,$h)=>{"use strict";var AP=ms(),wP=zt().f,kP=wr(),RP=je(),$P=kh(),LP=le(),Rh=LP("toStringTag");$h.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(RP(i,Rh)||wP(i,Rh,{configurable:!0,value:e}),r&&!AP&&kP(i,"toString",$P))}});var Mh=m((FO,Lh)=>{"use strict";var MP=Fo().IteratorPrototype,CP=Bo(),DP=li(),OP=yi(),BP=Kt(),VP=function(){return this};Lh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=CP(MP,{next:DP(+!r,t)}),OP(a,i,!1,!0),BP[i]=VP,a}});var Dh=m((qO,Ch)=>{"use strict";var _P=te(),NP=Ke();Ch.exports=function(a,e,t){try{return _P(NP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Bh=m((UO,Oh)=>{"use strict";var FP=Ae();Oh.exports=function(a){return FP(a)||a===null}});var _h=m((HO,Vh)=>{"use strict";var qP=Bh(),UP=String,HP=TypeError;Vh.exports=function(a){if(qP(a))return a;throw new HP("Can't set "+UP(a)+" as a prototype")}});var qo=m((jO,Nh)=>{"use strict";var jP=Dh(),GP=Ae(),QP=xt(),WP=_h();Nh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=jP(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return QP(i),WP(s),GP(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Kh=m((GO,zh)=>{"use strict";var YP=X(),zP=Pe(),gs=He(),Wh=Lo(),KP=Y(),JP=Mh(),Fh=ls(),qh=qo(),XP=yi(),ZP=wr(),Uo=Mr(),eA=le(),Uh=Kt(),Yh=Fo(),tA=Wh.PROPER,rA=Wh.CONFIGURABLE,Hh=Yh.IteratorPrototype,vs=Yh.BUGGY_SAFARI_ITERATORS,Ti=eA("iterator"),jh="keys",Ii="values",Gh="entries",Qh=function(){return this};zh.exports=function(a,e,t,r,i,s,n){JP(t,e,r);var o=function(v){if(v===i&&p)return p;if(!vs&&v&&v in d)return d[v];switch(v){case jh:return function(){return new t(this,v)};case Ii:return function(){return new t(this,v)};case Gh:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[Ti]||d["@@iterator"]||i&&d[i],p=!vs&&c||o(i),h=e==="Array"&&d.entries||c,f,b,g;if(h&&(f=Fh(h.call(new a)),f!==Object.prototype&&f.next&&(!gs&&Fh(f)!==Hh&&(qh?qh(f,Hh):KP(f[Ti])||Uo(f,Ti,Qh)),XP(f,u,!0,!0),gs&&(Uh[u]=Qh))),tA&&i===Ii&&c&&c.name!==Ii&&(!gs&&rA?ZP(d,"name",Ii):(l=!0,p=function(){return zP(c,this)})),i)if(b={values:o(Ii),keys:s?p:o(jh),entries:o(Gh)},n)for(g in b)(vs||l||!(g in d))&&Uo(d,g,b[g]);else YP({target:e,proto:!0,forced:vs||l},b);return(!gs||n)&&d[Ti]!==p&&Uo(d,Ti,p,{name:i}),Uh[e]=p,b}});var Xh=m((QO,Jh)=>{"use strict";Jh.exports=function(a,e){return{value:a,done:e}}});var jo=m((WO,af)=>{"use strict";var iA=Wt(),Ho=gi(),Zh=Kt(),tf=ko(),aA=zt().f,sA=Kh(),Ss=Xh(),nA=He(),oA=xe(),rf="Array Iterator",uA=tf.set,lA=tf.getterFor(rf);af.exports=sA(Array,"Array",function(a,e){uA(this,{type:rf,target:iA(a),index:0,kind:e})},function(){var a=lA(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ss(void 0,!0);switch(a.kind){case"keys":return Ss(t,!1);case"values":return Ss(e[t],!1)}return Ss([t,e[t]],!1)},"values");var ef=Zh.Arguments=Zh.Array;Ho("keys");Ho("values");Ho("entries");if(!nA&&oA&&ef.name!=="values")try{aA(ef,"name",{value:"values"})}catch(a){}});var nf=m((YO,sf)=>{"use strict";var cA=le(),dA=Kt(),pA=cA("iterator"),hA=Array.prototype;sf.exports=function(a){return a!==void 0&&(dA.Array===a||hA[pA]===a)}});var Go=m((zO,uf)=>{"use strict";var fA=Si(),of=pi(),mA=Ir(),bA=Kt(),gA=le(),vA=gA("iterator");uf.exports=function(a){if(!mA(a))return of(a,vA)||of(a,"@@iterator")||bA[fA(a)]}});var cf=m((KO,lf)=>{"use strict";var SA=Pe(),yA=Ke(),TA=Je(),IA=di(),EA=Go(),xA=TypeError;lf.exports=function(a,e){var t=arguments.length<2?EA(a):e;if(yA(t))return TA(SA(t,a));throw new xA(IA(a)+" is not iterable")}});var hf=m((JO,pf)=>{"use strict";var PA=Pe(),df=Je(),AA=pi();pf.exports=function(a,e,t){var r,i;df(a);try{if(r=AA(a,"return"),!r){if(e==="throw")throw t;return t}r=PA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return df(r),t}});var Ts=m((XO,gf)=>{"use strict";var wA=Ar(),kA=Pe(),RA=Je(),$A=di(),LA=nf(),MA=$r(),ff=ci(),CA=cf(),DA=Go(),mf=hf(),OA=TypeError,ys=function(a,e){this.stopped=a,this.result=e},bf=ys.prototype;gf.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=wA(e,r),l,d,c,p,h,f,b,g=function(S){return l&&mf(l,"normal",S),new ys(!0,S)},v=function(S){return i?(RA(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(d=DA(a),!d)throw new OA($A(a)+" is not iterable");if(LA(d)){for(c=0,p=MA(a);p>c;c++)if(h=v(a[c]),h&&ff(bf,h))return h;return new ys(!1)}l=CA(a,d)}for(f=s?a.next:l.next;!(b=kA(f,l)).done;){try{h=v(b.value)}catch(S){mf(l,"throw",S)}if(typeof h=="object"&&h&&ff(bf,h))return h}return new ys(!1)}});var Sf=m((ZO,vf)=>{"use strict";var BA=xe(),VA=zt(),_A=li();vf.exports=function(a,e,t){BA?VA.f(a,e,_A(0,t)):a[e]=t}});var yf=m(()=>{"use strict";var NA=X(),FA=Ts(),qA=Sf();NA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return FA(e,function(r,i){qA(t,r,i)},{AS_ENTRIES:!0}),t}})});var If=m((rB,Tf)=>{"use strict";jo();yf();var UA=Er();Tf.exports=UA.Object.fromEntries});var xf=m((iB,Ef)=>{"use strict";Ef.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 Af=m(()=>{"use strict";jo();var HA=xf(),jA=z(),GA=yi(),Pf=Kt();for(Is in HA)GA(jA[Is],Is),Pf[Is]=Pf.Array;var Is});var kf=m((nB,wf)=>{"use strict";var QA=If();Af();wf.exports=QA});var Qo=m((oB,Rf)=>{"use strict";var WA=kf();Rf.exports=WA});var $f=m(()=>{"use strict"});var Wo=m((cB,Lf)=>{"use strict";var Ei=z(),YA=Yt(),zA=Qt(),Es=function(a){return YA.slice(0,a.length)===a};Lf.exports=function(){return Es("Bun/")?"BUN":Es("Cloudflare-Workers")?"CLOUDFLARE":Es("Deno/")?"DENO":Es("Node.js/")?"NODE":Ei.Bun&&typeof Bun.version=="string"?"BUN":Ei.Deno&&typeof Deno.version=="object"?"DENO":zA(Ei.process)==="process"?"NODE":Ei.window&&Ei.document?"BROWSER":"REST"}()});var xs=m((dB,Mf)=>{"use strict";var KA=Wo();Mf.exports=KA==="NODE"});var Df=m((pB,Cf)=>{"use strict";var JA=zt();Cf.exports=function(a,e,t){return JA.f(a,e,t)}});var Vf=m((hB,Bf)=>{"use strict";var XA=at(),ZA=Df(),ew=le(),tw=xe(),Of=ew("species");Bf.exports=function(a){var e=XA(a);tw&&e&&!e[Of]&&ZA(e,Of,{configurable:!0,get:function(){return this}})}});var Nf=m((fB,_f)=>{"use strict";var rw=ci(),iw=TypeError;_f.exports=function(a,e){if(rw(e,a))return a;throw new iw("Incorrect invocation")}});var zo=m((mB,Ff)=>{"use strict";var aw=te(),sw=Y(),Yo=hi(),nw=aw(Function.toString);sw(Yo.inspectSource)||(Yo.inspectSource=function(a){return nw(a)});Ff.exports=Yo.inspectSource});var Jo=m((bB,Gf)=>{"use strict";var ow=te(),uw=ue(),qf=Y(),lw=Si(),cw=at(),dw=zo(),Uf=function(){},Hf=cw("Reflect","construct"),Ko=/^\s*(?:class|function)\b/,pw=ow(Ko.exec),hw=!Ko.test(Uf),xi=function(e){if(!qf(e))return!1;try{return Hf(Uf,[],e),!0}catch(t){return!1}},jf=function(e){if(!qf(e))return!1;switch(lw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return hw||!!pw(Ko,dw(e))}catch(t){return!0}};jf.sham=!0;Gf.exports=!Hf||uw(function(){var a;return xi(xi.call)||!xi(Object)||!xi(function(){a=!0})||a})?jf:xi});var Wf=m((gB,Qf)=>{"use strict";var fw=Jo(),mw=di(),bw=TypeError;Qf.exports=function(a){if(fw(a))return a;throw new bw(mw(a)+" is not a constructor")}});var Xo=m((vB,zf)=>{"use strict";var Yf=Je(),gw=Wf(),vw=Ir(),Sw=le(),yw=Sw("species");zf.exports=function(a,e){var t=Yf(a).constructor,r;return t===void 0||vw(r=Yf(t)[yw])?e:gw(r)}});var Jf=m((SB,Kf)=>{"use strict";var Tw=te();Kf.exports=Tw([].slice)});var Zf=m((yB,Xf)=>{"use strict";var Iw=TypeError;Xf.exports=function(a,e){if(a<e)throw new Iw("Not enough arguments");return a}});var Zo=m((TB,em)=>{"use strict";var Ew=Yt();em.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Ew)});var uu=m((IB,lm)=>{"use strict";var we=z(),xw=qn(),Pw=Ar(),tm=Y(),Aw=je(),um=ue(),rm=Mo(),ww=Jf(),im=as(),kw=Zf(),Rw=Zo(),$w=xs(),su=we.setImmediate,nu=we.clearImmediate,Lw=we.process,eu=we.Dispatch,Mw=we.Function,am=we.MessageChannel,Cw=we.String,tu=0,Pi={},sm="onreadystatechange",Ai,Xt,ru,iu;um(function(){Ai=we.location});var ou=function(a){if(Aw(Pi,a)){var e=Pi[a];delete Pi[a],e()}},au=function(a){return function(){ou(a)}},nm=function(a){ou(a.data)},om=function(a){we.postMessage(Cw(a),Ai.protocol+"//"+Ai.host)};(!su||!nu)&&(su=function(e){kw(arguments.length,1);var t=tm(e)?e:Mw(e),r=ww(arguments,1);return Pi[++tu]=function(){xw(t,void 0,r)},Xt(tu),tu},nu=function(e){delete Pi[e]},$w?Xt=function(a){Lw.nextTick(au(a))}:eu&&eu.now?Xt=function(a){eu.now(au(a))}:am&&!Rw?(ru=new am,iu=ru.port2,ru.port1.onmessage=nm,Xt=Pw(iu.postMessage,iu)):we.addEventListener&&tm(we.postMessage)&&!we.importScripts&&Ai&&Ai.protocol!=="file:"&&!um(om)?(Xt=om,we.addEventListener("message",nm,!1)):sm in im("script")?Xt=function(a){rm.appendChild(im("script"))[sm]=function(){rm.removeChild(this),ou(a)}}:Xt=function(a){setTimeout(au(a),0)});lm.exports={set:su,clear:nu}});var pm=m((EB,dm)=>{"use strict";var cm=z(),Dw=xe(),Ow=Object.getOwnPropertyDescriptor;dm.exports=function(a){if(!Dw)return cm[a];var e=Ow(cm,a);return e&&e.value}});var lu=m((xB,fm)=>{"use strict";var hm=function(){this.head=null,this.tail=null};hm.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}}};fm.exports=hm});var bm=m((PB,mm)=>{"use strict";var Bw=Yt();mm.exports=/ipad|iphone|ipod/i.test(Bw)&&typeof Pebble!="undefined"});var vm=m((AB,gm)=>{"use strict";var Vw=Yt();gm.exports=/web0s(?!.*chrome)/i.test(Vw)});var Pm=m((wB,xm)=>{"use strict";var Dr=z(),_w=pm(),Sm=Ar(),cu=uu().set,Nw=lu(),Fw=Zo(),qw=bm(),Uw=vm(),du=xs(),ym=Dr.MutationObserver||Dr.WebKitMutationObserver,Tm=Dr.document,Im=Dr.process,Ps=Dr.Promise,fu=_w("queueMicrotask"),Cr,pu,hu,As,Em;fu||(wi=new Nw,ki=function(){var a,e;for(du&&(a=Im.domain)&&a.exit();e=wi.get();)try{e()}catch(t){throw wi.head&&Cr(),t}a&&a.enter()},!Fw&&!du&&!Uw&&ym&&Tm?(pu=!0,hu=Tm.createTextNode(""),new ym(ki).observe(hu,{characterData:!0}),Cr=function(){hu.data=pu=!pu}):!qw&&Ps&&Ps.resolve?(As=Ps.resolve(void 0),As.constructor=Ps,Em=Sm(As.then,As),Cr=function(){Em(ki)}):du?Cr=function(){Im.nextTick(ki)}:(cu=Sm(cu,Dr),Cr=function(){cu(ki)}),fu=function(a){wi.head||Cr(),wi.add(a)});var wi,ki;xm.exports=fu});var wm=m((kB,Am)=>{"use strict";Am.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var ws=m((RB,km)=>{"use strict";km.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Zt=m(($B,Rm)=>{"use strict";var Hw=z();Rm.exports=Hw.Promise});var Or=m((LB,Cm)=>{"use strict";var jw=z(),Ri=Zt(),Gw=Y(),Qw=lo(),Ww=zo(),Yw=le(),$m=Wo(),zw=He(),mu=Kn(),Lm=Ri&&Ri.prototype,Kw=Yw("species"),bu=!1,Mm=Gw(jw.PromiseRejectionEvent),Jw=Qw("Promise",function(){var a=Ww(Ri),e=a!==String(Ri);if(!e&&mu===66||zw&&!(Lm.catch&&Lm.finally))return!0;if(!mu||mu<51||!/native code/.test(a)){var t=new Ri(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Kw]=r,bu=t.then(function(){})instanceof r,!bu)return!0}return!e&&($m==="BROWSER"||$m==="DENO")&&!Mm});Cm.exports={CONSTRUCTOR:Jw,REJECTION_EVENT:Mm,SUBCLASSING:bu}});var Br=m((MB,Om)=>{"use strict";var Dm=Ke(),Xw=TypeError,Zw=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Xw("Bad Promise constructor");e=r,t=i}),this.resolve=Dm(e),this.reject=Dm(t)};Om.exports.f=function(a){return new Zw(a)}});var eb=m(()=>{"use strict";var ek=X(),tk=He(),Ls=xs(),At=z(),Fr=Pe(),Bm=Mr(),Vm=qo(),rk=yi(),ik=Vf(),ak=Ke(),$s=Y(),sk=Ae(),nk=Nf(),ok=Xo(),Um=uu().set,Tu=Pm(),uk=wm(),lk=ws(),ck=lu(),Hm=ko(),Ms=Zt(),Iu=Or(),jm=Br(),Cs="Promise",Gm=Iu.CONSTRUCTOR,dk=Iu.REJECTION_EVENT,pk=Iu.SUBCLASSING,gu=Hm.getterFor(Cs),hk=Hm.set,Vr=Ms&&Ms.prototype,er=Ms,ks=Vr,Qm=At.TypeError,vu=At.document,Eu=At.process,Su=jm.f,fk=Su,mk=!!(vu&&vu.createEvent&&At.dispatchEvent),Wm="unhandledrejection",bk="rejectionhandled",_m=0,Ym=1,gk=2,xu=1,zm=2,Rs,Nm,vk,Fm,Km=function(a){var e;return sk(a)&&$s(e=a.then)?e:!1},Jm=function(a,e){var t=e.value,r=e.state===Ym,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{i?(r||(e.rejection===zm&&yk(e),e.rejection=xu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),d=!0)),u===a.promise?n(new Qm("Promise-chain cycle")):(l=Km(u))?Fr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},Xm=function(a,e){a.notified||(a.notified=!0,Tu(function(){for(var t=a.reactions,r;r=t.get();)Jm(r,a);a.notified=!1,e&&!a.rejection&&Sk(a)}))},Zm=function(a,e,t){var r,i;mk?(r=vu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),At.dispatchEvent(r)):r={promise:e,reason:t},!dk&&(i=At["on"+a])?i(r):a===Wm&&uk("Unhandled promise rejection",t)},Sk=function(a){Fr(Um,At,function(){var e=a.facade,t=a.value,r=qm(a),i;if(r&&(i=lk(function(){Ls?Eu.emit("unhandledRejection",t,e):Zm(Wm,e,t)}),a.rejection=Ls||qm(a)?zm:xu,i.error))throw i.value})},qm=function(a){return a.rejection!==xu&&!a.parent},yk=function(a){Fr(Um,At,function(){var e=a.facade;Ls?Eu.emit("rejectionHandled",e):Zm(bk,e,a.value)})},_r=function(a,e,t){return function(r){a(e,r,t)}},Nr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=gk,Xm(a,!0))},yu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Qm("Promise can't be resolved itself");var r=Km(e);r?Tu(function(){var i={done:!1};try{Fr(r,e,_r(yu,i,a),_r(Nr,i,a))}catch(s){Nr(i,s,a)}}):(a.value=e,a.state=Ym,Xm(a,!1))}catch(i){Nr({done:!1},i,a)}}};if(Gm&&(er=function(e){nk(this,ks),ak(e),Fr(Rs,this);var t=gu(this);try{e(_r(yu,t),_r(Nr,t))}catch(r){Nr(t,r)}},ks=er.prototype,Rs=function(e){hk(this,{type:Cs,done:!1,notified:!1,parent:!1,reactions:new ck,rejection:!1,state:_m,value:void 0})},Rs.prototype=Bm(ks,"then",function(e,t){var r=gu(this),i=Su(ok(this,er));return r.parent=!0,i.ok=$s(e)?e:!0,i.fail=$s(t)&&t,i.domain=Ls?Eu.domain:void 0,r.state===_m?r.reactions.add(i):Tu(function(){Jm(i,r)}),i.promise}),Nm=function(){var a=new Rs,e=gu(a);this.promise=a,this.resolve=_r(yu,e),this.reject=_r(Nr,e)},jm.f=Su=function(a){return a===er||a===vk?new Nm(a):fk(a)},!tk&&$s(Ms)&&Vr!==Object.prototype)){Fm=Vr.then,pk||Bm(Vr,"then",function(e,t){var r=this;return new er(function(i,s){Fr(Fm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Vr.constructor}catch(a){}Vm&&Vm(Vr,ks)}ek({global:!0,constructor:!0,wrap:!0,forced:Gm},{Promise:er});rk(er,Cs,!1,!0);ik(Cs)});var sb=m((OB,ab)=>{"use strict";var Tk=le(),rb=Tk("iterator"),ib=!1;try{tb=0,Pu={next:function(){return{done:!!tb++}},return:function(){ib=!0}},Pu[rb]=function(){return this},Array.from(Pu,function(){throw 2})}catch(a){}var tb,Pu;ab.exports=function(a,e){try{if(!e&&!ib)return!1}catch(i){return!1}var t=!1;try{var r={};r[rb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Au=m((BB,nb)=>{"use strict";var Ik=Zt(),Ek=sb(),xk=Or().CONSTRUCTOR;nb.exports=xk||!Ek(function(a){Ik.all(a).then(void 0,function(){})})});var ob=m(()=>{"use strict";var Pk=X(),Ak=Pe(),wk=Ke(),kk=Br(),Rk=ws(),$k=Ts(),Lk=Au();Pk({target:"Promise",stat:!0,forced:Lk},{all:function(e){var t=this,r=kk.f(t),i=r.resolve,s=r.reject,n=Rk(function(){var o=wk(t.resolve),u=[],l=0,d=1;$k(e,function(c){var p=l++,h=!1;d++,Ak(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 lb=m(()=>{"use strict";var Mk=X(),Ck=He(),Dk=Or().CONSTRUCTOR,ku=Zt(),Ok=at(),Bk=Y(),Vk=Mr(),ub=ku&&ku.prototype;Mk({target:"Promise",proto:!0,forced:Dk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Ck&&Bk(ku)&&(wu=Ok("Promise").prototype.catch,ub.catch!==wu&&Vk(ub,"catch",wu,{unsafe:!0}));var wu});var cb=m(()=>{"use strict";var _k=X(),Nk=Pe(),Fk=Ke(),qk=Br(),Uk=ws(),Hk=Ts(),jk=Au();_k({target:"Promise",stat:!0,forced:jk},{race:function(e){var t=this,r=qk.f(t),i=r.reject,s=Uk(function(){var n=Fk(t.resolve);Hk(e,function(o){Nk(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var db=m(()=>{"use strict";var Gk=X(),Qk=Br(),Wk=Or().CONSTRUCTOR;Gk({target:"Promise",stat:!0,forced:Wk},{reject:function(e){var t=Qk.f(this),r=t.reject;return r(e),t.promise}})});var Ru=m((GB,pb)=>{"use strict";var Yk=Je(),zk=Ae(),Kk=Br();pb.exports=function(a,e){if(Yk(a),zk(e)&&e.constructor===a)return e;var t=Kk.f(a),r=t.resolve;return r(e),t.promise}});var mb=m(()=>{"use strict";var Jk=X(),Xk=at(),hb=He(),Zk=Zt(),fb=Or().CONSTRUCTOR,eR=Ru(),tR=Xk("Promise"),rR=hb&&!fb;Jk({target:"Promise",stat:!0,forced:hb||fb},{resolve:function(e){return eR(rR&&this===tR?Zk:this,e)}})});var bb=m(()=>{"use strict";eb();ob();lb();cb();db();mb()});var yb=m(()=>{"use strict";var iR=X(),aR=He(),Ds=Zt(),sR=ue(),vb=at(),Sb=Y(),nR=Xo(),gb=Ru(),oR=Mr(),Lu=Ds&&Ds.prototype,uR=!!Ds&&sR(function(){Lu.finally.call({then:function(){}},function(){})});iR({target:"Promise",proto:!0,real:!0,forced:uR},{finally:function(a){var e=nR(this,vb("Promise")),t=Sb(a);return this.then(t?function(r){return gb(e,a()).then(function(){return r})}:a,t?function(r){return gb(e,a()).then(function(){throw r})}:a)}});!aR&&Sb(Ds)&&($u=vb("Promise").prototype.finally,Lu.finally!==$u&&oR(Lu,"finally",$u,{unsafe:!0}));var $u});var Ib=m((XB,Tb)=>{"use strict";$f();bb();yb();var lR=Pt();Tb.exports=lR("Promise","finally")});var xb=m((ZB,Eb)=>{"use strict";var cR=Ib();Eb.exports=cR});var Os=m((eV,Pb)=>{"use strict";var dR=xb();Pb.exports=dR});var _b=m(()=>{"use strict";var PR=X(),AR=xo().values;PR({target:"Object",stat:!0},{values:function(e){return AR(e)}})});var Fb=m((_V,Nb)=>{"use strict";_b();var wR=Er();Nb.exports=wR.Object.values});var Ub=m((NV,qb)=>{"use strict";var kR=Fb();qb.exports=kR});var Li=m((FV,Hb)=>{"use strict";var RR=Ub();Hb.exports=RR});var rg=m(()=>{"use strict";var GR=X(),QR=xr(),WR=$r(),YR=bi(),zR=gi();GR({target:"Array",proto:!0},{at:function(e){var t=QR(this),r=WR(t),i=YR(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});zR("at")});var ag=m((f_,ig)=>{"use strict";rg();var KR=Pt();ig.exports=KR("Array","at")});var ng=m((m_,sg)=>{"use strict";var JR=ag();sg.exports=JR});var Hr=m((b_,og)=>{"use strict";var XR=ng();og.exports=XR});var el=m((UN,Vg)=>{"use strict";var C$=Qt();Vg.exports=Array.isArray||function(e){return C$(e)==="Array"}});var Ng=m((HN,_g)=>{"use strict";var D$=TypeError,O$=9007199254740991;_g.exports=function(a){if(a>O$)throw D$("Maximum allowed index exceeded");return a}});var Ug=m((jN,qg)=>{"use strict";var B$=el(),V$=$r(),_$=Ng(),N$=Ar(),Fg=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,d=n?N$(n,o):!1,c,p;l<r;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&B$(c)?(p=V$(c),u=Fg(a,e,c,p,u,s-1)-1):(_$(u+1),a[u]=c),u++),l++;return u};qg.exports=Fg});var Qg=m((GN,Gg)=>{"use strict";var Hg=el(),F$=Jo(),q$=Ae(),U$=le(),H$=U$("species"),jg=Array;Gg.exports=function(a){var e;return Hg(a)&&(e=a.constructor,F$(e)&&(e===jg||Hg(e.prototype))?e=void 0:q$(e)&&(e=e[H$],e===null&&(e=void 0))),e===void 0?jg:e}});var Yg=m((QN,Wg)=>{"use strict";var j$=Qg();Wg.exports=function(a,e){return new(j$(a))(e===0?0:e)}});var zg=m(()=>{"use strict";var G$=X(),Q$=Ug(),W$=Ke(),Y$=xr(),z$=$r(),K$=Yg();G$({target:"Array",proto:!0},{flatMap:function(e){var t=Y$(this),r=z$(t),i;return W$(e),i=K$(t,0),i.length=Q$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Kg=m(()=>{"use strict";var J$=gi();J$("flatMap")});var Xg=m((JN,Jg)=>{"use strict";zg();Kg();var X$=Pt();Jg.exports=X$("Array","flatMap")});var ev=m((XN,Zg)=>{"use strict";var Z$=Xg();Zg.exports=Z$});var tl=m((ZN,tv)=>{"use strict";var eL=ev();tv.exports=eL});var Gi=m((lF,Tv)=>{"use strict";var uL=Si(),lL=String;Tv.exports=function(a){if(uL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return lL(a)}});var il=m((cF,Iv)=>{"use strict";Iv.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 Pv=m((dF,xv)=>{"use strict";var cL=te(),dL=xt(),pL=Gi(),sl=il(),Ev=cL("".replace),hL=RegExp("^["+sl+"]+"),fL=RegExp("(^|[^"+sl+"])["+sl+"]+$"),al=function(a){return function(e){var t=pL(dL(e));return a&1&&(t=Ev(t,hL,"")),a&2&&(t=Ev(t,fL,"$1")),t}};xv.exports={start:al(1),end:al(2),trim:al(3)}});var Rv=m((pF,kv)=>{"use strict";var mL=Lo().PROPER,bL=ue(),Av=il(),wv="\u200B\x85\u180E";kv.exports=function(a){return bL(function(){return!!Av[a]()||wv[a]()!==wv||mL&&Av[a].name!==a})}});var nl=m((hF,$v)=>{"use strict";var gL=Pv().start,vL=Rv();$v.exports=vL("trimStart")?function(){return gL(this)}:"".trimStart});var Mv=m(()=>{"use strict";var SL=X(),Lv=nl();SL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Lv},{trimLeft:Lv})});var Dv=m(()=>{"use strict";Mv();var yL=X(),Cv=nl();yL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Cv},{trimStart:Cv})});var Bv=m((vF,Ov)=>{"use strict";Dv();var TL=Pt();Ov.exports=TL("String","trimLeft")});var _v=m((SF,Vv)=>{"use strict";var IL=Bv();Vv.exports=IL});var Fv=m((yF,Nv)=>{"use strict";var EL=_v();Nv.exports=EL});var rS=m(()=>{"use strict"});var iS=m(()=>{"use strict"});var sS=m((jU,aS)=>{"use strict";var QL=Ae(),WL=Qt(),YL=le(),zL=YL("match");aS.exports=function(a){var e;return QL(a)&&((e=a[zL])!==void 0?!!e:WL(a)==="RegExp")}});var oS=m((GU,nS)=>{"use strict";var KL=Je();nS.exports=function(){var a=KL(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 cS=m((QU,lS)=>{"use strict";var JL=Pe(),XL=je(),ZL=ci(),eM=oS(),uS=RegExp.prototype;lS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in uS)&&!XL(a,"flags")&&ZL(uS,a)?JL(eM,a):e}});var pS=m((WU,dS)=>{"use strict";var ml=te(),tM=xr(),rM=Math.floor,hl=ml("".charAt),iM=ml("".replace),fl=ml("".slice),aM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,sM=/\$([$&'`]|\d{1,2})/g;dS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=sM;return i!==void 0&&(i=tM(i),u=aM),iM(s,u,function(l,d){var c;switch(hl(d,0)){case"$":return"$";case"&":return a;case"`":return fl(e,0,t);case"'":return fl(e,n);case"<":c=i[fl(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var h=rM(p/10);return h===0?l:h<=o?r[h-1]===void 0?hl(d,1):r[h-1]+hl(d,1):l}c=r[p-1]}return c===void 0?"":c})}});var mS=m(()=>{"use strict";var nM=X(),oM=Pe(),gl=te(),hS=xt(),uM=Y(),lM=Ir(),cM=sS(),zr=Gi(),dM=pi(),pM=cS(),hM=pS(),fM=le(),mM=He(),bM=fM("replace"),gM=TypeError,bl=gl("".indexOf),vM=gl("".replace),fS=gl("".slice),SM=Math.max;nM({target:"String",proto:!0},{replaceAll:function(e,t){var r=hS(this),i,s,n,o,u,l,d,c,p,h,f=0,b="";if(!lM(e)){if(i=cM(e),i&&(s=zr(hS(pM(e))),!~bl(s,"g")))throw new gM("`.replaceAll` does not allow non-global regexes");if(n=dM(e,bM),n)return oM(n,e,r,t);if(mM&&i)return vM(zr(r),e,t)}for(o=zr(r),u=zr(e),l=uM(t),l||(t=zr(t)),d=u.length,c=SM(1,d),p=bl(o,u);p!==-1;)h=l?zr(t(u,p,o)):hM(u,o,p,[],void 0,t),b+=fS(o,f,p)+h,f=p+d,p=p+c>o.length?-1:bl(o,u,p+c);return f<o.length&&(b+=fS(o,f)),b}})});var gS=m((KU,bS)=>{"use strict";rS();iS();mS();var yM=Pt();bS.exports=yM("String","replaceAll")});var SS=m((JU,vS)=>{"use strict";var TM=gS();vS.exports=TM});var TS=m((XU,yS)=>{"use strict";var IM=SS();yS.exports=IM});var ES=m((ZU,IS)=>{"use strict";var EM=bi(),xM=Gi(),PM=xt(),AM=RangeError;IS.exports=function(e){var t=xM(PM(this)),r="",i=EM(e);if(i<0||i===1/0)throw new AM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var kS=m((e1,wS)=>{"use strict";var AS=te(),wM=bo(),xS=Gi(),kM=ES(),RM=xt(),$M=AS(kM),LM=AS("".slice),MM=Math.ceil,PS=function(a){return function(e,t,r){var i=xS(RM(e)),s=wM(t),n=i.length,o=r===void 0?" ":xS(r),u,l;return s<=n||o===""?i:(u=s-n,l=$M(o,MM(u/o.length)),l.length>u&&(l=LM(l,0,u)),a?i+l:l+i)}};wS.exports={start:PS(!1),end:PS(!0)}});var $S=m((t1,RS)=>{"use strict";var CM=Yt();RS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(CM)});var LS=m(()=>{"use strict";var DM=X(),OM=kS().start,BM=$S();DM({target:"String",proto:!0,forced:BM},{padStart:function(e){return OM(this,e,arguments.length>1?arguments[1]:void 0)}})});var CS=m((a1,MS)=>{"use strict";LS();var VM=Pt();MS.exports=VM("String","padStart")});var OS=m((s1,DS)=>{"use strict";var _M=CS();DS.exports=_M});var VS=m((n1,BS)=>{"use strict";var NM=OS();BS.exports=NM});var Cc="2.0.119-dev.e9ac9f0e.0";var me=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(me||{}),Et=(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))(Et||{});var ts=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ts||{}),_n=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(_n||{});var Nn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Nn||{});var hT=B(Xe(),1);import{assertNever as Lp,assertNonNullable as XE,isNonNullable as ns,ValueSubject as vo,Subject as ZE,Subscription as ex,merge as tx,observableFrom as rx,fromEvent as wp,map as kp,tap as Rp,filterChanged as ix,isNullable as So,ErrorCategory as $p}from"@vkontakte/videoplayer-shared/es2018";var Ap=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 os=class{constructor(e){this.connection$=new vo(void 0);this.castState$=new vo("NOT_AVAILABLE");this.errorEvent$=new ZE;this.realCastState$=new vo("NOT_AVAILABLE");this.subscription=new ex;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=ns((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Ap("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:$p.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(){ns(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();So(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();So(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(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 Lp(i.sessionState)}})).add(tx(wp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Rp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),kp(i=>i.castState)),rx([r.getCastState()])).pipe(ix(),kp(ax),Rp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=ns(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();XE(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(So(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"?ns(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:$p.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},ax=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 Lp(a)}};var Ql=B(Xe(),1),Wy=B(Lr(),1),Yy=B(Qo(),1);var Ob=B(Os(),1);import{assertNever as Ab}from"@vkontakte/videoplayer-shared/es2018";var ce=(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:Ab(t)}return a},Bs=(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:Ab(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as pR,Subject as Vs,merge as wb}from"@vkontakte/videoplayer-shared/es2018";var L=class{constructor(e){this.transitionStarted$=new Vs;this.transitionEnded$=new Vs;this.transitionUpdated$=new Vs;this.forceChanged$=new Vs;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||pR(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 hR}from"@vkontakte/videoplayer-shared/es2018";var kb=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 hR(a)}};import{assertNever as qr,assertNonNullable as tr,debounce as Rb,ErrorCategory as $b,fromEvent as rr,isNonNullable as Lb,map as Mb,merge as Cb,observableFrom as fR,Subject as mR,Subscription as Mu,timeout as bR,getHighestQuality as gR}from"@vkontakte/videoplayer-shared/es2018";var vR=5,SR=5,yR=500,Db=7e3,$i=class{constructor(e){this.subscription=new Mu;this.loadMediaTimeoutSubscription=new Mu;this.videoState=new L("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(kb(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 Mu;this.subscription.add(e),this.subscription.add(Cb(this.videoState.stateChangeStarted$.pipe(Mb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Mb(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 mR;e.add(i.pipe(Rb(yR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(rr(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)>vR)&&i.next(o),s=o})),e.add(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(rr(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<SR&&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(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(rr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Cb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,fR(["init"])).pipe(Rb(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];tr(d);let c=gR(Object.keys(d));tr(c);let p=d[c];tr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];tr(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];tr(d),r=d.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];tr(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];tr(d),r=ce(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:$b.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 Lb(o)&&(n.metadata.title=o),Lb(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(Db).subscribe(()=>s(`timeout(${Db})`)))});(0,Ob.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:$b.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Xu=B(Xe(),1);import{clearVideoElement as Vb}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as TR}from"@vkontakte/videoplayer-shared/es2018";var Bb=a=>{try{a.pause(),a.playbackRate=0,TR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as IR,Subscription as ER}from"@vkontakte/videoplayer-shared/es2018";var Cu=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)}},Du=window.WeakMap?new WeakMap:new Cu,Ou=window.WeakMap?new WeakMap:new Map,xR=(a,e=20)=>{let t=0;return IR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},be=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Vb(t):(t=document.createElement("video"),a.appendChild(t)),Du.set(t,r);let i=new ER;return i.add(xR(t,e)),Ou.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ge=a=>{let e=Ou.get(a);e==null||e.unsubscribe(),Ou.delete(a);let t=Du.get(a);Du.delete(a),t?Vb(a):Bb(a)};var Vu=B(Li(),1);import{assertNonNullable as Mi,isNonNullable as et,isNullable as MR,fromEvent as Ur,merge as jb,observableFrom as Gb,filterChanged as Qb,map as Ci,Subject as Wb,Subscription as CR,ValueSubject as DR,ErrorCategory as OR}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as Bu,isNullable as $R,Subscription as LR}from"@vkontakte/videoplayer-shared/es2018";var _s=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=$R(i),l=new LR;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},Ze=(a,e,t)=>_s(e,()=>a.loop,r=>{Bu(r)&&(a.loop=r)},{onError:t}),ve=(a,e,t,r)=>_s(e,()=>({muted:a.muted,volume:a.volume}),i=>{Bu(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}),De=(a,e,t,r)=>_s(e,()=>a.playbackRate,i=>{Bu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),wt=_s;var BR=a=>["__",a.language,a.label].join("|"),VR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},_u=class a{constructor(){this.available$=new Wb;this.current$=new DR(void 0);this.error$=new Wb;this.subscription=new CR;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:OR.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(wt(t.internalTextTracks,()=>(0,Vu.default)(this.internalTracks),s=>{et(s)&&this.setInternal(s)},{equal:(s,n)=>et(s)&&et(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ci(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(wt(t.externalTextTracks,()=>(0,Vu.default)(this.externalTracks),s=>{et(s)&&this.setExternal(s)},{equal:(s,n)=>et(s)&&et(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ci(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(wt(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(wt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Mi(this.video);let{textTracks:e}=this.video;this.subscription.add(Ur(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(jb(Ur(e,"addtrack"),Ur(e,"removetrack"),Gb(["init"])).pipe(Ci(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Qb((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(jb(Ur(e,"change"),Gb(["init"])).pipe(Ci(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ci(r=>r&&this.htmlTextTrackToITextTrack(r).id),Qb()).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(Ur(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(Ur(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;et(t.align)&&(i.align=t.align),et(t.position)&&(i.position=t.position),et(t.size)&&(i.size=t.size),et(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Mi(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:BR(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){Mi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(MR(e)||!VR(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){Mi(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){Mi(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Oe=_u;var ot=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 Yb=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},Nu=a=>{let e=Yb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},zb=a=>{let e=Yb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Be,map as kt,merge as Jb,filterChanged as NR,isNonNullable as Xb,Subject as FR,filter as Zb,mapTo as eg,combine as qR,once as UR,ErrorCategory as HR,ValueSubject as tg,clientChecker as jR}from"@vkontakte/videoplayer-shared/es2018";var _R=3,Kb=(a,e,t=_R)=>{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 Se=a=>{let e=y=>Be(a,y).pipe(eg(void 0)),r=Jb(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Be(a,y))).pipe(kt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),NR()),i=Jb(Be(a,"progress"),Be(a,"timeupdate")).pipe(kt(()=>Kb(a.buffered,a.currentTime))),s=jR.isSafari?qR({play:e("play").pipe(UR()),playing:e("playing")}).pipe(eg(void 0)):e("playing"),n=Be(a,"volumechange").pipe(kt(()=>({muted:a.muted,volume:a.volume}))),o=Be(a,"ratechange").pipe(kt(()=>a.playbackRate)),u=Be(a,"error").pipe(Zb(()=>!!(a.error||a.played.length)),kt(()=>{var E;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:HR.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(E=a.error)!=null?E:void 0}})),l=Be(a,"timeupdate").pipe(kt(()=>a.currentTime)),d=new FR,c=.3,p;l.subscribe(y=>{a.loop&&Xb(p)&&Xb(y)&&p>=a.duration-c&&y<=c&&d.next(p),p=y});let h=e("pause").pipe(Zb(()=>!a.error&&p!==a.duration)),f=Be(a,"enterpictureinpicture"),b=Be(a,"leavepictureinpicture"),g=new tg(zb(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new tg(Nu(a));return Be(a,"fullscreenchange").pipe(kt(()=>Nu(a))).subscribe(v),{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$:Be(a,"durationchange").pipe(kt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v}};import{VideoQuality as Rt}from"@vkontakte/videoplayer-shared/es2018";var $t=a=>{switch(a){case"mobile":return Rt.Q_144P;case"lowest":return Rt.Q_240P;case"low":return Rt.Q_360P;case"sd":case"medium":return Rt.Q_480P;case"hd":case"high":return Rt.Q_720P;case"fullhd":case"full":return Rt.Q_1080P;case"quadhd":case"quad":return Rt.Q_1440P;case"ultrahd":case"ultra":return Rt.Q_2160P}};var Lt=B(Hr(),1),fg=B(Xe(),1),Ns=B(Lr(),1);import{isNonNullable as re,isNullable as qu,now as mg,isHigher as Uu,isHigherOrEqual as Hu,isInvariantQuality as dg,isLower as pg,isLowerOrEqual as ju,videoSizeToQuality as ZR,assertNotEmptyArray as bg,assertNonNullable as e$}from"@vkontakte/videoplayer-shared/es2018";var Fu=!1,ut={},ug=a=>{Fu=a},lg=()=>{ut={}},cg=a=>{a(ut)},Di=(a,e)=>{var t;Fu&&(ut.meta=(t=ut.meta)!=null?t:{},ut.meta[a]=e)},pe=class{constructor(e){this.name=e}next(e){var r,i;if(!Fu)return;ut.series=(r=ut.series)!=null?r:{};let t=(i=ut.series[this.name])!=null?i:[];t.push([Date.now(),e]),ut.series[this.name]=t}};var t$=new pe("best_bitrate"),gg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var Gu=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Oi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=mg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},vg='Assertion "ABR Tracks is empty array" failed',Fs=(a,e,t,r)=>{var u;let i=[...e].sort(Gu(1)),s=[...t].sort(Gu(1)),n=s.filter(l=>re(l.bitrate)&&re(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Lt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Lt.default)(s,-1);return o&&(0,fg.default)(n,o)?o:n.length?(0,Lt.default)(n,-1):(0,Lt.default)(s,0)},hg=a=>"quality"in a,Sg=(a,e,t,r)=>{var n;let i=re((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&re(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&mg()-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=hg(o)?"video":"audio",l=hg(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},r$=(a,e)=>Math.log(e)/Math.log(a),Mt=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{var _,k,w,H,J,A;bg(a,vg);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let O=r.pixelRatioLogBase,[M=0,Z=0,Le=0]=r.pixelRatioLogCoefficients,mt=r$(O,M*T+Z)+Le;Number.isFinite(mt)&&(b*=mt)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,v=r.considerPlaybackRate&&re(o)?o:1,S=a.filter(T=>!dg(T.quality)).sort((T,O)=>Uu(T.quality,O.quality)?-1:1),y=(_=(0,Lt.default)(S,-1))==null?void 0:_.quality,E=(k=(0,Lt.default)(S,0))==null?void 0:k.quality,I=qu(i)||re(i.min)&&re(i.max)&&pg(i.max,i.min)||re(i.min)&&E&&Uu(i.min,E)||re(i.max)&&y&&pg(i.max,y),R=v*gg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),C={},$=S.filter(T=>{let O=!0;if(g)if(T.size)O=T.size.width<=g.width&&T.size.height<=g.height;else{let ne=g&&ZR(g);O=ne?ju(T.quality,ne):!0}if(!O)return C[T.quality]="FitsContainer",!1;let M=h||t;if(!(re(M)&&isFinite(M)&&re(T.bitrate)?M-s>=T.bitrate*R:!0))return C[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&re(r.minBufferToSwitchUp)&&u&&!dg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Uu(T.quality,u.quality))return C[T.quality]="Buffer",!1;if(!!c&&Hu(T.quality,c))return C[T.quality]="DroppedFramesLimit",!1;if(!!p&&Hu(T.quality,p))return C[T.quality]="StallsLimit",!1;let F=I||(qu(i.max)||ju(T.quality,i.max))&&(qu(i.min)||Hu(T.quality,i.min)),se=re(d)&&!d?ju(T.quality,r.backgroundVideoQualityLimit):!0;return!F||!se?(C[T.quality]="FitsQualityLimits",!1):!0})[0];$&&$.bitrate&&t$.next($.bitrate);let V=(w=$!=null?$:(0,Lt.default)(S,-1))!=null?w:a[0];return V.quality!==((H=l==null?void 0:l.last)==null?void 0:H.quality)&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(
|
|
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,Ns.default)(r!=null?r:{}).map(([T,O])=>`${T}: ${O}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
containerSizeLimit: ${(
|
|
20
|
+
containerSizeLimit: ${(J=g==null?void 0:g.width)!=null?J:0} x ${(A=g==null?void 0:g.width)!=null?A:0},
|
|
21
21
|
estimatedThroughput: ${t},
|
|
22
22
|
stallsPredictedThroughput: ${h},
|
|
23
23
|
reserve: ${s},
|
|
24
24
|
playbackRate: ${o},
|
|
25
|
-
playbackRateFactor: ${
|
|
25
|
+
playbackRateFactor: ${v},
|
|
26
26
|
forwardBufferHealth: ${n},
|
|
27
|
-
bitrateFactor: ${
|
|
27
|
+
bitrateFactor: ${R},
|
|
28
28
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
29
29
|
droppedVideoMaxQualityLimit: ${c},
|
|
30
30
|
stallsVideoMaxQualityLimit: ${p},
|
|
31
|
-
limitsAreInvalid: ${
|
|
31
|
+
limitsAreInvalid: ${I},
|
|
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,Ns.default)(C).map(([T,O])=>`${T}: ${O}`).join(`
|
|
37
37
|
`)||"All tracks are available"}
|
|
38
38
|
|
|
39
|
-
[best video track] ${
|
|
40
|
-
[selected video track] ${
|
|
41
|
-
`}),
|
|
39
|
+
[best video track] ${$==null?void 0:$.quality}
|
|
40
|
+
[selected video track] ${V==null?void 0:V.quality}
|
|
41
|
+
`}),Sg(r,f,V,l)},yg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;bg(t,vg);let d=i.considerPlaybackRate&&re(s)?s:1,c=[...t].sort(Gu(-1)),p=a.bitrate;e$(p);let h=d*gg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=Fs(a,e,t,i.minVideoAudioRatio),g=l||r;return re(g)&&isFinite(g)&&(f=c.find(S=>re(S.bitrate)&&re(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),f||(f=b),(f==null?void 0:f.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
|
|
42
42
|
[AUDIO TRACKS ABR]
|
|
43
43
|
[available audio tracks]
|
|
44
|
-
${t.map(
|
|
44
|
+
${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
|
|
45
45
|
`)}
|
|
46
46
|
|
|
47
47
|
[tuning]
|
|
48
|
-
${(0,
|
|
48
|
+
${(0,Ns.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
|
|
49
49
|
`)}
|
|
50
50
|
|
|
51
51
|
[limit params]
|
|
@@ -59,14 +59,14 @@ var wT=Object.create;var Oc=Object.defineProperty;var kT=Object.getOwnPropertyDe
|
|
|
59
59
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
60
60
|
|
|
61
61
|
[selected audio track] ${f==null?void 0:f.id}
|
|
62
|
-
`}),f&&Ig(i,u,f,o)};var ie=a=>new URL(a).hostname;import{assertNever as Cg,assertNonNullable as Dg,combine as A$,debounce as w$,ErrorCategory as Og,filter as Vg,filterChanged as k$,isNonNullable as Zu,map as Ws,merge as Bg,observableFrom as R$,once as $$,Subscription as L$,ValueSubject as el,videoQualityToHeight as M$,videoSizeToQuality as C$}from"@vkontakte/videoplayer-shared/es2018";var Pg=C(Xe(),1),xg=a=>{if(a instanceof DOMException&&(0,Pg.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"))},Se=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!xg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return xg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as js,isNullable as u$,assertNonNullable as Ni}from"@vkontakte/videoplayer-shared/es2018";var wg=C(Mi(),1);import{isNonNullable as Ag,assertNonNullable as Hs,now as n$}from"@vkontakte/videoplayer-shared/es2018";function ae(){return n$()}function zu(a){return ae()-a}function Ku(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function kg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Hr(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;Hs(d);let k=zu(d),w;if(k<b){w=b-k,setTimeout(g,w);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,A()},v=k=>(s=k,O),y=k=>(c=k,O),T=()=>(h="json",O),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,c&&c(),t&&t()}},I=k=>(p=k,O),A=()=>{d=ae(),n=new i,n.open("get",a);let k=0,w,H=0,J=()=>(Hs(d),Math.max(d,Math.max(w||0,H||0)));if(s&&n.addEventListener("progress",S=>{let R=ae();s.updateChunk&&S.loaded>k&&(s.updateChunk(J(),S.loaded-k),k=S.loaded,w=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;Hs(n);let S=n.status;if(S>=200&&S<300){if(n.response.byteLength&&s){let R=n.response.byteLength-k;R&&s.updateChunk&&s.updateChunk(J(),R)}n.responseType==="json"&&!(0,wg.default)(n.response).length?E():(c&&c(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){let S=()=>{Hs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(H=ae(),n.removeEventListener("readystatechange",S))};n.addEventListener("readystatechange",S)}return n.responseType=h,n.send(),O},O={withBitrateReporting:v,withParallel:I,withJSONResponse:T,withRetryCount:k=>(l=k,O),withRetryInterval:(k,w)=>(Ag(k)&&(b=k),Ag(w)&&(f=w),O),withTimeout:k=>(o=k,O),withFinally:y,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return O}var Bi=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 Rg=C(Mi(),1);var _i=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ae(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ae()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Hr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ae()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ae();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Rg.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 l$}from"@vkontakte/videoplayer-shared/es2018";var Qs=1e4,Ju=3;var c$=6e4,d$=10,p$=1,h$=500,Fi=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 l$,this.chunkRateEstimator=new Bi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ku(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=Ku(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||js(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{kg(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new _i(Ju,Qs,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 E=s&&(!d||d===this.rep);return E||t("Not running!"),E},p=(E,I,A)=>{u&&u.abort(),u=Hr(this.urlResolver.resolve(E,!1),I,A,()=>this._retryCallback()).withTimeout(Qs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ju).withFinally(()=>{u=null}).send()},h=(E,I,A)=>{Ni(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=E=>{let I=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),r.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let A=ae()-1e4,F=0;for(let L=0;L<this.bufferStates.length;L++){let q=this.bufferStates[L];E=Math.min(E,q.buf),q.ts<A&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${E} drop=${F} jitter=${this.sourceJitter}`);let D=E-p$;this.sourceJitter>=0?D-=this.sourceJitter/2:this.sourceJitter-=1,D>3?f(1.15):D>1?f(1.1):D>.3?f(1.05):f(1)}},v=E=>{let I,A=()=>I&&I.start?I.start.length:0,F=S=>I.start[S]/1e3,D=S=>I.dur[S]/1e3,L=S=>I.fragIndex+S,q=(S,R)=>({chunkIdx:L(S),startTS:F(S),dur:D(S),discontinuity:R}),O=()=>{let S=0;if(I&&I.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,j=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,V=R;this.sourceJitter>1&&(V+=this.sourceJitter-1);let le=I.dur.length-1;for(;le>=0&&(V-=I.dur[le],!(V<=0));--le);S=Math.min(le,I.dur.length-1-j),S=Math.max(S,0)}return q(S,!0)},k=S=>{let R=A();if(!(R<=0)){if(js(S)){for(let j=0;j<R;j++)if(F(j)>S)return q(j)}return O()}},w=S=>{let R=A(),j=S?S.chunkIdx+1:0,V=j-I.fragIndex;if(!(R<=0)){if(!S||V<0||V-R>d$)return t(`Resync: offset=${V} bChunks=${R} chunk=`+JSON.stringify(S)),O();if(!(V>=R))return q(j-I.fragIndex,!1)}},H=(S,R,j)=>{l&&l.abort(),l=Hr(this.urlResolver.resolve(S,!0,this.lowLatency),R,j,()=>this._retryCallback()).withTimeout(Qs).withRetryCount(Ju).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(S,R)=>{H(E,j=>{if(!c())return;I=j;let V=!!I.lowLatency;V!==this.lowLatency&&b(V);let le=0;for(let We=0;We<I.dur.length;++We)le+=I.dur[We];le>0&&(Ni(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(le/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,S(k(R))},()=>this._handleNetworkError())},nextChunk:w}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ni(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:E=>{let{videoElement:I,logger:A}=this.params,F=v(e.jidxUrl),D,L,q,O,k=0,w,H,J,S=()=>{w&&(clearTimeout(w),w=void 0);let _=Math.max(h$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Z=k+_,Ee=ae(),Le=Math.min(1e4,Z-Ee);k=Ee;let mt=()=>{l||c()&&F.seek(()=>{c()&&(k=ae(),R(),S())})};Le>0?w=window.setTimeout(()=>{this.paused?S():mt()},Le):mt()},R=()=>{let _;for(;_=F.nextChunk(O);)O=_,ei(_);let Z=F.nextChunk(q);if(Z){if(q&&Z.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?S():(y(),this._initPlayerWith(e));return}We(Z)}else S()},j=(_,Z)=>{if(!c()||!this.sourceBuffer)return;let Ee,Le,mt,hr=bt=>{window.setTimeout(()=>{c()&&j(_,Z)},bt)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),hr(100);else{let bt=ae(),qt=I.currentTime;!this.paused&&I.buffered.length>1&&H===qt&&bt-J>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),H!==qt&&(H=qt,J=bt);let fr=this._getBufferSizeSec();if(fr>30)A(`Buffered ${fr} seconds; delaying appendBuffer`),hr(2e3);else try{this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(this.bufferStates.push({ts:bt,buf:fr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Z&&Z()}catch(ti){if(ti.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),mt=this.sourceBuffer.buffered.length,mt!==0&&(Ee=this.sourceBuffer.buffered.start(0),Le=qt,Le-Ee>4&&this.sourceBuffer.remove(Ee,Le-3)),hr(1e3);else throw ti}}},V=()=>{L&&D&&(A([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(q)]),j(L,function(){L=null,R()}))},le=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),We=_=>{c()&&h(le(_),(Z,Ee)=>{if(c()){if(Ee/=1e3,L=Z,q=_,n=_.startTS,Ee){let Le=Math.min(10,_.dur/Ee);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Le:Le}V()}},()=>this._handleNetworkError())},ei=_=>{c()&&(Ni(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(le(_),!1)))},Ft=_=>{c()&&(e.cachedHeader=_,j(_,()=>{D=!0,V()}))};s=!0,F.seek(_=>{if(c()){if(k=ae(),!_){S();return}O=_,!u$(E)||_.startTS>E?We(_):(q=_,R())}},E),e.cachedHeader?Ft(e.cachedHeader):p(e.headerUrl,Ft,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),js(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,Ni(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return js(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=ae();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&&zu(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=ae();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=Hr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Qs).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;Se(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))},c$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Mg=C($r(),1);import{debounce as f$,filter as $g,fromEvent as m$,interval as b$,isHigher as g$,isInvariantQuality as v$,isLower as S$,merge as y$,Subject as Lg,Subscription as T$}from"@vkontakte/videoplayer-shared/es2018";var Xu=class{constructor(){this.onDroopedVideoFramesLimit$=new Lg;this.subscription=new T$;this.playing=!1;this.tracks=[];this.forceChecker$=new Lg;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&&!v$(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&&g$(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=b$(this.droppedFramesChecker.checkTime).pipe($g(()=>this.playing),$g(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(f$(this.droppedFramesChecker.checkTime)),r=y$(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,Mg.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>S$(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}},Gs=Xu;import{map as I$,Observable as E$}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as x$}from"@vkontakte/videoplayer-shared/es2018";var qi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var P$=(a,e)=>new E$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||qi()))},{...r,...e});i.observe(a);let s=x$(document,"visibilitychange").pipe(I$(n=>!document.hidden||qi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ve=P$;var D$=["paused","playing","ready"],O$=["paused","playing","ready"],Ui=class{constructor(e){this.subscription=new L$;this.videoState=new $("stopped");this.representations$=new el([]);this.textTracksManager=new De;this.droppedFramesManager=new Gs;this.maxSeekBackTime$=new el(1/0);this.zeroTime$=new el(void 0);this.liveOffset=new ot;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:Og.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=Rt(u.name))!=null?r:C$(u.video),c=u.bitrate/1e3,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),Zu(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,tl.default)(O$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,tl.default)(D$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ue(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(ue(this.params.source.url,u))}return;default:return Cg(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Og.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Bg(this.videoState.stateChangeStarted$.pipe(Ws(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ws(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ve(this.video);this.subscription.add(this.representations$.pipe(Ws(i=>i.map(({track:s})=>s)),Vg(i=>!!i.length),$$()).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(k$(),Ws(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(A$({zeroTime:this.zeroTime$.pipe(Vg(Zu)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ze(this.video,this.params.desiredState.isLooped,t)).add(ge(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ce(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(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&M$(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 Cg(i.to)}},t)).add(Bg(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,R$(["init"])).pipe(w$(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),be(this.video)}createLiveDashPlayer(){let e=new Fi({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&&Zu(t)?t:Lt(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;Dg(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;Dg(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(ue(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var _g=Ui;var Ty=C(Xe(),1);var tt=(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 bC,assertNonNullable as gC,debounce as vC,ErrorCategory as Nl,filter as vy,filterChanged as Ra,fromEvent as SC,isNonNullable as Sy,map as Fl,merge as Tn,observableFrom as yC,observeElementSize as TC,once as yy,Subscription as IC,ValueSubject as EC}from"@vkontakte/videoplayer-shared/es2018";var Ys=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}},jr=class extends Ys{constructor(){super(),this.listeners||Ys.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)}},Hi=class{constructor(){Object.defineProperty(this,"signal",{value:new jr,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&&(Hi.prototype[Symbol.toStringTag]="AbortController",jr.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 rl(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 ji=zs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ng=ji?rl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ji?Ng.fetch:window.fetch,zN=ji?Ng.Request:window.Request,ke=ji?Hi:window.AbortController,KN=ji?jr:window.AbortSignal;var Bl=C(al(),1);var sn=C(Ur(),1);var ct=()=>window.ManagedMediaSource||window.MediaSource,Ks=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},sv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},nv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as on,clientChecker as nn}from"@vkontakte/videoplayer-shared/es2018";var Be=document.createElement("video"),nL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',oL='video/mp4; codecs="hev1.1.6.L93.B0"',gv='video/webm; codecs="vp09.00.10.08"',vv='video/webm; codecs="av01.0.00M.08"',uL='audio/mp4; codecs="mp4a.40.2"',lL='audio/webm; codecs="opus"',ov,uv,Qi={mms:Ks(),mse:sv(),hls:!!((ov=Be.canPlayType)!=null&&ov.call(Be,"application/x-mpegurl")||(uv=Be.canPlayType)!=null&&uv.call(Be,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},lv,cv,ye={mp4:!!((lv=Be.canPlayType)!=null&&lv.call(Be,"video/mp4")),webm:!!((cv=Be.canPlayType)!=null&&cv.call(Be,"video/webm")),cmaf:!0},Xs,dv,Zs,pv,en,hv,tn,fv,rn,mv,an,bv,Te={h264:!!((dv=(Xs=ct())==null?void 0:Xs.isTypeSupported)!=null&&dv.call(Xs,nL)),h265:!!((pv=(Zs=ct())==null?void 0:Zs.isTypeSupported)!=null&&pv.call(Zs,oL)),vp9:!!((hv=(en=ct())==null?void 0:en.isTypeSupported)!=null&&hv.call(en,gv)),av1:!!((fv=(tn=ct())==null?void 0:tn.isTypeSupported)!=null&&fv.call(tn,vv)),aac:!!((mv=(rn=ct())==null?void 0:rn.isTypeSupported)!=null&&mv.call(rn,uL)),opus:!!((bv=(an=ct())==null?void 0:an.isTypeSupported)!=null&&bv.call(an,lL))},Qr=(Te.h264||Te.h265)&&Te.aac,ir,cL=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:vv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:gv}})]);ir={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{cL()}catch(a){console.error(a)}var Gr=Qi.hls&&ye.mp4,Sv=()=>Object.keys(Te).filter(a=>Te[a]),yv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Qi.mse&&(!r||!!window.MediaStreamTrack)||Qi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&ye.mp4&&Qr;case"DASH_WEBM":return i&&ye.webm&&Te.vp9&&Te.opus;case"DASH_WEBM_AV1":return i&&ye.webm&&Te.av1&&Te.opus;case"DASH_STREAMS":return i&&(ye.mp4&&Qr||ye.webm&&(Te.vp9||Te.av1)&&(Te.opus||Te.aac));case"DASH_LIVE":return i&&ye.mp4&&Qr;case"DASH_LIVE_CMAF":return i&&ye.mp4&&Qr&&ye.cmaf;case"DASH_ONDEMAND":return i&&ye.mp4&&Qr;case"HLS":case"HLS_ONDEMAND":return Gr||e&&i&&ye.mp4&&Qr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Gr;case"MPEG":return ye.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Qi.webrtc&&Qi.ws&&Te.h264&&(ye.mp4||ye.webm);default:return on(s)}})},Js=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 ir?ir[t].smooth?[t,e]:ir[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ir?ir[t].powerEfficient?[t,e]:ir[e].powerEfficient?[e,t]:[t,e]:[e,t];default:on(a)}return[e,t]},Tv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Js(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(nn.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",...Js(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Js(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Js(a),...i,"HLS","HLS_ONDEMAND"];default:on(e)}return Gr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Iv=({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=nn.isMac&&nn.isSafari;if(nn.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:on(a)}else Gr&&!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"]},sl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ev=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,sn.default)(t.value.split("."),0)}for(let t of a){let r=(0,sn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,sn.default)(e.value.split("."),0)};var jv=C(Hv(),1);import{ErrorCategory as Wi}from"@vkontakte/videoplayer-shared/es2018";var Qv=a=>{if(!a)return{id:"EmptyResponse",category:Wi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Wi.NETWORK,message:`UV Error ${a}`};let e=(0,jv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Wi.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:Wi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Wi.PARSER,message:"Response is valid XML, but parser failed"}};var Mt=(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 Dl,assertNonNullable as lr,clientChecker as tC,combine as Pa,ErrorCategory as Vt,filter as bn,filterChanged as Ol,flattenObject as Aa,fromEvent as cr,getTraceSubscriptionMethod as rC,interval as Vl,isNonNullable as ly,map as wa,merge as dr,now as iC,Subject as cy,Subscription as dy,tap as aC,throttle as sC,ValueSubject as K}from"@vkontakte/videoplayer-shared/es2018";var cn=C(Xe(),1),Kr=C(Ur(),1),dn=C(al(),1);var wL=(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)},kL=a=>window.clearTimeout(a),Gv=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Wv=!Gv(window.requestIdleCallback)||!Gv(window.cancelIdleCallback),cl=Wv?wL:window.requestIdleCallback,Yi=Wv?kL:window.cancelIdleCallback;var ty=C(Vs(),1);import{assertNever as RL,ErrorCategory as Yv,clientChecker as dl,Subject as zv}from"@vkontakte/videoplayer-shared/es2018";var $L=18,Kv=!1;try{Kv=dl.isSafari&&!!dl.macVersion&&dl.macVersion<=$L}catch(a){console.error(a)}var pl=class{constructor(e){this.bufferFull$=new zv;this.error$=new zv;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:Yv.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Kv&&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:Yv.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:RL(t)}}},Jv=pl;var hl=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 nr,assertNonNullable as pe,ErrorCategory as Dt,fromEvent as Rl,getExponentialDelay as $l,isNonNullable as un,isNullable as _e,now as ln,once as QM,Subject as GM,Subscription as WM,ValueSubject as zr}from"@vkontakte/videoplayer-shared/es2018";var U=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 Wr=class extends U{};var zi=class extends U{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 Ki=class extends U{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 Ji=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var W=class extends U{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Xi=class extends W{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 Zi=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends U{constructor(e,t){super(e,t),this.data=this.content}};var ar=class extends W{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 ta=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ia=class extends W{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 aa=class extends W{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var sa=class extends W{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var na=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends W{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 ua=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var la=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ca=class extends W{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var da=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pa=class extends W{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 ha=class extends W{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 fa=class extends W{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 ML={ftyp:Ki,moov:Ji,mvhd:Xi,moof:Zi,mdat:ea,sidx:ar,trak:ta,mdia:na,mfhd:ca,tkhd:oa,traf:da,tfhd:pa,tfdt:ha,trun:fa,minf:ua,sv3d:ra,st3d:ia,prhd:aa,proj:la,equi:sa,uuid:zi,unknown:Wr},dt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=ML[e];return r?new r(t,new a):new Wr(t,new a)}};var Ct=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 DL=new TextDecoder("ascii"),OL=a=>DL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",VL=a=>{let e=new ar(a,new dt),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})},BL=(a,e)=>{let r=new dt().parse(a),i=new Ct(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)},_L=a=>{let t=new dt().parse(a),r=new Ct(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},NL=a=>{var i;let t=new dt().parse(a);return(i=new Ct(t).find("sidx"))==null?void 0:i.timescale},FL=(a,e)=>{let r=new dt().parse(a),s=new Ct(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},qL=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 dt().parse(a),i=new Ct(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},Xv={validateData:OL,parseInit:qL,getIndexRange:()=>{},parseSegments:VL,parseFeedableSegmentChunk:BL,getChunkEndTime:FL,getServerLatencyTimestamps:_L,getTimescaleFromIndex:NL};var ba=C(Xe(),1);import{assertNonNullable as ml,isNonNullable as rS,isNullable as HL}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as UL}from"@vkontakte/videoplayer-shared/es2018";var Zv={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"}},eS=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=ma(a,t),i=r in Zv,s=i?Zv[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=ma(u),c=l*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}},ma=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Qe=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ma(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:UL(e)}},sr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=eS(r);if(!e(i))return;i.type==="master"&&sr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},tS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=eS(a);return sr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Qe(o,n):s===17026?t=Qe(o,n):s===17029&&(r=Qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var iS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],jL=[231,22612,22743,167,171,163,160,175],QL=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return sr(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Qe(f,h);l=ma(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=Qe(f,h):p===17545?i=Qe(f,h):p===21420&&l===475249515?u=Qe(f,h):p===374648427?sr(f,({tag:g,type:v,value:y})=>g===30321?(d=Qe(y,v)===1,!1):!0):s&&n&&(0,ba.default)(iS,p)&&(o=!0),!o}),ml(e,"Failed to parse webm Segment start"),ml(t,"Failed to parse webm Segment end"),ml(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}}}},GL=a=>{if(HL(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},WL=(a,e)=>{let t=!1,r=!1,i=o=>rS(o.time)&&rS(o.position),s=[],n;return sr(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=Qe(l,u));break;case 183:break;case 241:n&&(n.position=Qe(l,u));break;default:t&&(0,ba.default)(iS,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}}})},YL=a=>{let e=0,t=!1;try{sr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ba.default)(jL,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ba.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},aS={validateData:tS,parseInit:QL,getIndexRange:GL,parseSegments:WL,parseFeedableSegmentChunk:YL};var ga=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return aS;case"mp4":return Xv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Il=C(xS(),1),WS=C($r(),1),YS=C(FS(),1),zS=C(Ur(),1);var qS=C(Xe(),1),Tl=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,qS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as jS,isNullable as QS}from"@vkontakte/videoplayer-shared/es2018";var US=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var HS=a=>{var e;try{let t=HM(),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 HM(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
62
|
+
`}),f&&Sg(i,u,f,o)};var ie=a=>new URL(a).hostname;import{assertNever as $g,assertNonNullable as Lg,combine as E$,debounce as x$,ErrorCategory as Mg,filter as Cg,filterChanged as P$,isNonNullable as Ku,map as Gs,merge as Dg,observableFrom as A$,once as w$,Subscription as k$,ValueSubject as Ju,videoQualityToHeight as R$,videoSizeToQuality as $$}from"@vkontakte/videoplayer-shared/es2018";var Ig=B(Xe(),1),Tg=a=>{if(a instanceof DOMException&&(0,Ig.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"))},ye=async(a,e)=>{let t=a.muted;try{await a.play()}catch(r){if(!Tg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{await a.play()}catch(i){return Tg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Us,isNullable as s$,assertNonNullable as _i}from"@vkontakte/videoplayer-shared/es2018";var xg=B(Li(),1);import{isNonNullable as Eg,assertNonNullable as qs,now as i$}from"@vkontakte/videoplayer-shared/es2018";function ae(){return i$()}function Qu(a){return ae()-a}function Wu(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 Pg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function jr(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;qs(d);let k=Qu(d),w;if(k<b){w=b-k,setTimeout(g,w);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,R()},v=k=>(s=k,_),S=k=>(c=k,_),y=()=>(h="json",_),E=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,c&&c(),t&&t()}},I=k=>(p=k,_),R=()=>{d=ae(),n=new i,n.open("get",a);let k=0,w,H=0,J=()=>(qs(d),Math.max(d,Math.max(w||0,H||0)));if(s&&n.addEventListener("progress",A=>{let T=ae();s.updateChunk&&A.loaded>k&&(s.updateChunk(J(),A.loaded-k),k=A.loaded,w=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;qs(n);let A=n.status;if(A>=200&&A<300){if(n.response.byteLength&&s){let T=n.response.byteLength-k;T&&s.updateChunk&&s.updateChunk(J(),T)}n.responseType==="json"&&!(0,xg.default)(n.response).length?E():(c&&c(),e(n.response))}else E()}),n.addEventListener("error",()=>{E()}),p){let A=()=>{qs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(H=ae(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=h,n.send(),_},_={withBitrateReporting:v,withParallel:I,withJSONResponse:y,withRetryCount:k=>(l=k,_),withRetryInterval:(k,w)=>(Eg(k)&&(b=k),Eg(w)&&(f=w),_),withTimeout:k=>(o=k,_),withFinally:S,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return _}var Bi=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 Ag=B(Li(),1);var Vi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ae(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ae()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=jr(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ae()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ae();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Ag.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 n$}from"@vkontakte/videoplayer-shared/es2018";var Hs=1e4,Yu=3;var o$=6e4,u$=10,l$=1,c$=500,Ni=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 n$,this.chunkRateEstimator=new Bi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Wu(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=Wu(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||Us(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=()=>{Pg(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 Vi(Yu,Hs,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 E=s&&(!d||d===this.rep);return E||t("Not running!"),E},p=(E,I,R)=>{u&&u.abort(),u=jr(this.urlResolver.resolve(E,!1),I,R,()=>this._retryCallback()).withTimeout(Hs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Yu).withFinally(()=>{u=null}).send()},h=(E,I,R)=>{_i(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=E=>{let I=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),r.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=ae()-1e4,C=0;for(let $=0;$<this.bufferStates.length;$++){let V=this.bufferStates[$];E=Math.min(E,V.buf),V.ts<R&&C++}this.bufferStates.splice(0,C),t(`update playback rate; minBuffer=${E} drop=${C} jitter=${this.sourceJitter}`);let G=E-l$;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?f(1.15):G>1?f(1.1):G>.3?f(1.05):f(1)}},v=E=>{let I,R=()=>I&&I.start?I.start.length:0,C=A=>I.start[A]/1e3,G=A=>I.dur[A]/1e3,$=A=>I.fragIndex+A,V=(A,T)=>({chunkIdx:$(A),startTS:C(A),dur:G(A),discontinuity:T}),_=()=>{let A=0;if(I&&I.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,O=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,M=T;this.sourceJitter>1&&(M+=this.sourceJitter-1);let Z=I.dur.length-1;for(;Z>=0&&(M-=I.dur[Z],!(M<=0));--Z);A=Math.min(Z,I.dur.length-1-O),A=Math.max(A,0)}return V(A,!0)},k=A=>{let T=R();if(!(T<=0)){if(Us(A)){for(let O=0;O<T;O++)if(C(O)>A)return V(O)}return _()}},w=A=>{let T=R(),O=A?A.chunkIdx+1:0,M=O-I.fragIndex;if(!(T<=0)){if(!A||M<0||M-T>u$)return t(`Resync: offset=${M} bChunks=${T} chunk=`+JSON.stringify(A)),_();if(!(M>=T))return V(O-I.fragIndex,!1)}},H=(A,T,O)=>{l&&l.abort(),l=jr(this.urlResolver.resolve(A,!0,this.lowLatency),T,O,()=>this._retryCallback()).withTimeout(Hs).withRetryCount(Yu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,T)=>{H(E,O=>{if(!c())return;I=O;let M=!!I.lowLatency;M!==this.lowLatency&&b(M);let Z=0;for(let Le=0;Le<I.dur.length;++Le)Z+=I.dur[Le];Z>0&&(_i(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/I.dur.length)),i({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,A(k(T))},()=>this._handleNetworkError())},nextChunk:w}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),_i(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:E=>{let{videoElement:I,logger:R}=this.params,C=v(e.jidxUrl),G,$,V,_,k=0,w,H,J,A=()=>{w&&(clearTimeout(w),w=void 0);let F=Math.max(c$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),se=k+F,ne=ae(),Me=Math.min(1e4,se-ne);k=ne;let bt=()=>{l||c()&&C.seek(()=>{c()&&(k=ae(),T(),A())})};Me>0?w=window.setTimeout(()=>{this.paused?A():bt()},Me):bt()},T=()=>{let F;for(;F=C.nextChunk(_);)_=F,mt(F);let se=C.nextChunk(V);if(se){if(V&&se.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?A():(S(),this._initPlayerWith(e));return}Le(se)}else A()},O=(F,se)=>{if(!c()||!this.sourceBuffer)return;let ne,Me,bt,fr=gt=>{window.setTimeout(()=>{c()&&O(F,se)},gt)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),fr(100);else{let gt=ae(),qt=I.currentTime;!this.paused&&I.buffered.length>1&&H===qt&>-J>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),H!==qt&&(H=qt,J=gt);let mr=this._getBufferSizeSec();if(mr>30)R(`Buffered ${mr} seconds; delaying appendBuffer`),fr(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:gt,buf:mr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),se&&se()}catch(ti){if(ti.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),bt=this.sourceBuffer.buffered.length,bt!==0&&(ne=this.sourceBuffer.buffered.start(0),Me=qt,Me-ne>4&&this.sourceBuffer.remove(ne,Me-3)),fr(1e3);else throw ti}}},M=()=>{$&&G&&(R([`Appending chunk, sz=${$.byteLength}:`,JSON.stringify(V)]),O($,function(){$=null,T()}))},Z=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),Le=F=>{c()&&h(Z(F),(se,ne)=>{if(c()){if(ne/=1e3,$=se,V=F,n=F.startTS,ne){let Me=Math.min(10,F.dur/ne);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Me:Me}M()}},()=>this._handleNetworkError())},mt=F=>{c()&&(_i(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(F),!1)))},hr=F=>{c()&&(e.cachedHeader=F,O(F,()=>{G=!0,M()}))};s=!0,C.seek(F=>{if(c()){if(k=ae(),!F){A();return}_=F,!s$(E)||F.startTS>E?Le(F):(V=F,T())}},E),e.cachedHeader?hr(e.cachedHeader):p(e.headerUrl,hr,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Us(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,_i(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Us(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=ae();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&&Qu(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=ae();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=jr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Hs).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;ye(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))},o$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Rg=B(Lr(),1);import{debounce as d$,filter as wg,fromEvent as p$,interval as h$,isHigher as f$,isInvariantQuality as m$,isLower as b$,merge as g$,Subject as kg,Subscription as v$}from"@vkontakte/videoplayer-shared/es2018";var zu=class{constructor(){this.onDroopedVideoFramesLimit$=new kg;this.subscription=new v$;this.playing=!1;this.tracks=[];this.forceChecker$=new kg;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&&!m$(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&&f$(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(p$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=h$(this.droppedFramesChecker.checkTime).pipe(wg(()=>this.playing),wg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(d$(this.droppedFramesChecker.checkTime)),r=g$(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,Rg.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}},js=zu;import{map as S$,Observable as y$}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as T$}from"@vkontakte/videoplayer-shared/es2018";var Fi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var I$=(a,e)=>new y$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Fi()))},{...r,...e});i.observe(a);let s=T$(document,"visibilitychange").pipe(S$(n=>!document.hidden||Fi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ve=I$;var L$=["paused","playing","ready"],M$=["paused","playing","ready"],qi=class{constructor(e){this.subscription=new k$;this.videoState=new L("stopped");this.representations$=new Ju([]);this.textTracksManager=new Oe;this.droppedFramesManager=new js;this.maxSeekBackTime$=new Ju(1/0);this.zeroTime$=new Ju(void 0);this.liveOffset=new ot;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:Mg.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=$t(u.name))!=null?r:$$(u.video),c=u.bitrate/1e3,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),Ku(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,Xu.default)(M$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,Xu.default)(L$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ce(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(ce(this.params.source.url,u))}return;default:return $g(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Mg.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Dg(this.videoState.stateChangeStarted$.pipe(Gs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Gs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Se(this.video);this.subscription.add(this.representations$.pipe(Gs(i=>i.map(({track:s})=>s)),Cg(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(P$(),Gs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(E$({zeroTime:this.zeroTime$.pipe(Cg(Ku)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(Ze(this.video,this.params.desiredState.isLooped,t)).add(ve(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(De(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(Ve(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&R$(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 $g(i.to)}},t)).add(Dg(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,A$(["init"])).pipe(x$(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),ge(this.video)}createLiveDashPlayer(){let e=new Ni({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&&Ku(t)?t:Mt(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;Lg(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;Lg(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(ce(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Og=qi;var vy=B(Xe(),1);var tt=(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 h0,assertNonNullable as f0,debounce as m0,ErrorCategory as Bl,filter as my,filterChanged as ka,fromEvent as b0,isNonNullable as by,map as Vl,merge as Sn,observableFrom as g0,observeElementSize as v0,once as gy,Subscription as S0,ValueSubject as y0}from"@vkontakte/videoplayer-shared/es2018";var Qs=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}},Gr=class extends Qs{constructor(){super(),this.listeners||Qs.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)}},Ui=class{constructor(){Object.defineProperty(this,"signal",{value:new Gr,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&&(Ui.prototype[Symbol.toStringTag]="AbortController",Gr.prototype[Symbol.toStringTag]="AbortSignal");function Ws(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 Zu(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Ws({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 Hi=Ws({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Bg=Hi?Zu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=Hi?Bg.fetch:window.fetch,NN=Hi?Bg.Request:window.Request,ke=Hi?Ui:window.AbortController,FN=Hi?Gr:window.AbortSignal;var Dl=B(tl(),1);var rn=B(Hr(),1);var ct=()=>window.ManagedMediaSource||window.MediaSource,Ys=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},rv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},iv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as sn,clientChecker as an}from"@vkontakte/videoplayer-shared/es2018";var _e=document.createElement("video"),iL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',aL='video/mp4; codecs="hev1.1.6.L93.B0"',fv='video/webm; codecs="vp09.00.10.08"',mv='video/webm; codecs="av01.0.00M.08"',sL='audio/mp4; codecs="mp4a.40.2"',nL='audio/webm; codecs="opus"',av,sv,ji={mms:Ys(),mse:rv(),hls:!!((av=_e.canPlayType)!=null&&av.call(_e,"application/x-mpegurl")||(sv=_e.canPlayType)!=null&&sv.call(_e,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},nv,ov,Te={mp4:!!((nv=_e.canPlayType)!=null&&nv.call(_e,"video/mp4")),webm:!!((ov=_e.canPlayType)!=null&&ov.call(_e,"video/webm")),cmaf:!0},Ks,uv,Js,lv,Xs,cv,Zs,dv,en,pv,tn,hv,Ie={h264:!!((uv=(Ks=ct())==null?void 0:Ks.isTypeSupported)!=null&&uv.call(Ks,iL)),h265:!!((lv=(Js=ct())==null?void 0:Js.isTypeSupported)!=null&&lv.call(Js,aL)),vp9:!!((cv=(Xs=ct())==null?void 0:Xs.isTypeSupported)!=null&&cv.call(Xs,fv)),av1:!!((dv=(Zs=ct())==null?void 0:Zs.isTypeSupported)!=null&&dv.call(Zs,mv)),aac:!!((pv=(en=ct())==null?void 0:en.isTypeSupported)!=null&&pv.call(en,sL)),opus:!!((hv=(tn=ct())==null?void 0:tn.isTypeSupported)!=null&&hv.call(tn,nL))},Qr=(Ie.h264||Ie.h265)&&Ie.aac,ir,oL=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:mv}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:fv}})]);ir={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{oL()}catch(a){console.error(a)}var Wr=ji.hls&&Te.mp4,bv=()=>Object.keys(Ie).filter(a=>Ie[a]),gv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ji.mse&&(!r||!!window.MediaStreamTrack)||ji.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Te.mp4&&Qr;case"DASH_WEBM":return i&&Te.webm&&Ie.vp9&&Ie.opus;case"DASH_WEBM_AV1":return i&&Te.webm&&Ie.av1&&Ie.opus;case"DASH_STREAMS":return i&&(Te.mp4&&Qr||Te.webm&&(Ie.vp9||Ie.av1)&&(Ie.opus||Ie.aac));case"DASH_LIVE":return i&&Te.mp4&&Qr;case"DASH_LIVE_CMAF":return i&&Te.mp4&&Qr&&Te.cmaf;case"DASH_ONDEMAND":return i&&Te.mp4&&Qr;case"HLS":case"HLS_ONDEMAND":return Wr||e&&i&&Te.mp4&&Qr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Wr;case"MPEG":return Te.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ji.webrtc&&ji.ws&&Ie.h264&&(Te.mp4||Te.webm);default:return sn(s)}})},zs=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 ir?ir[t].smooth?[t,e]:ir[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ir?ir[t].powerEfficient?[t,e]:ir[e].powerEfficient?[e,t]:[t,e]:[e,t];default:sn(a)}return[e,t]},vv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...zs(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(an.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",...zs(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...zs(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...zs(a),...i,"HLS","HLS_ONDEMAND"];default:sn(e)}return Wr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Sv=({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=an.isMac&&an.isSafari;if(an.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:sn(a)}else Wr&&!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"]},rl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],yv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,rn.default)(t.value.split("."),0)}for(let t of a){let r=(0,rn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,rn.default)(e.value.split("."),0)};var qv=B(Fv(),1);import{ErrorCategory as Qi}from"@vkontakte/videoplayer-shared/es2018";var Uv=a=>{if(!a)return{id:"EmptyResponse",category:Qi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Qi.NETWORK,message:`UV Error ${a}`};let e=(0,qv.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Qi.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:Qi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Qi.PARSER,message:"Response is valid XML, but parser failed"}};var Ct=(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 Ll,assertNonNullable as lr,clientChecker as XM,combine as xa,ErrorCategory as Vt,filter as fn,filterChanged as Ml,flattenObject as Pa,fromEvent as cr,getTraceSubscriptionMethod as ZM,interval as Cl,isNonNullable as ny,map as Aa,merge as dr,now as e0,Subject as oy,Subscription as uy,tap as t0,throttle as r0,ValueSubject as K}from"@vkontakte/videoplayer-shared/es2018";var un=B(Xe(),1),Jr=B(Hr(),1),ln=B(tl(),1);var xL=(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)},PL=a=>window.clearTimeout(a),Hv=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),jv=!Hv(window.requestIdleCallback)||!Hv(window.cancelIdleCallback),ol=jv?xL:window.requestIdleCallback,Wi=jv?PL:window.cancelIdleCallback;var XS=B(Os(),1);import{assertNever as AL,ErrorCategory as Gv,clientChecker as ul,Subject as Qv}from"@vkontakte/videoplayer-shared/es2018";var wL=18,Wv=!1;try{Wv=ul.isSafari&&!!ul.macVersion&&ul.macVersion<=wL}catch(a){console.error(a)}var ll=class{constructor(e){this.bufferFull$=new Qv;this.error$=new Qv;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:Gv.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Wv&&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:Gv.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:AL(t)}}},Yv=ll;var cl=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 nr,assertNonNullable as he,ErrorCategory as Ot,fromEvent as Al,getExponentialDelay as wl,isNonNullable as nn,isNullable as Ne,now as on,once as UM,Subject as HM,Subscription as jM,ValueSubject as Kr}from"@vkontakte/videoplayer-shared/es2018";var U=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 Yr=class extends U{};var Yi=class extends U{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 zi=class extends U{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 Ki=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var W=class extends U{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ji=class extends W{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 Xi=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zi=class extends U{constructor(e,t){super(e,t),this.data=this.content}};var ar=class extends W{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 ea=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ta=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ra=class extends W{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 ia=class extends W{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var aa=class extends W{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var sa=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var na=class extends W{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 oa=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ua=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var la=class extends W{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ca=class extends U{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends W{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 pa=class extends W{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 ha=class extends W{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 RL={ftyp:zi,moov:Ki,mvhd:Ji,moof:Xi,mdat:Zi,sidx:ar,trak:ea,mdia:sa,mfhd:la,tkhd:na,traf:ca,tfhd:da,tfdt:pa,trun:ha,minf:oa,sv3d:ta,st3d:ra,prhd:ia,proj:ua,equi:aa,uuid:Yi,unknown:Yr},dt=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=RL[e];return r?new r(t,new a):new Yr(t,new a)}};var Dt=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 LL=new TextDecoder("ascii"),ML=a=>LL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",CL=a=>{let e=new ar(a,new dt),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})},DL=(a,e)=>{let r=new dt().parse(a),i=new Dt(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)},OL=a=>{let t=new dt().parse(a),r=new Dt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},BL=a=>{var i;let t=new dt().parse(a);return(i=new Dt(t).find("sidx"))==null?void 0:i.timescale},VL=(a,e)=>{let r=new dt().parse(a),s=new Dt(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},_L=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 dt().parse(a),i=new Dt(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},zv={validateData:ML,parseInit:_L,getIndexRange:()=>{},parseSegments:CL,parseFeedableSegmentChunk:DL,getChunkEndTime:VL,getServerLatencyTimestamps:OL,getTimescaleFromIndex:BL};var ma=B(Xe(),1);import{assertNonNullable as pl,isNonNullable as Zv,isNullable as FL}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as NL}from"@vkontakte/videoplayer-shared/es2018";var Kv={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"}},Jv=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=fa(a,t),i=r in Kv,s=i?Kv[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=fa(u),c=l*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}},fa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Qe=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return fa(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:NL(e)}},sr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=Jv(r);if(!e(i))return;i.type==="master"&&sr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},Xv=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=Jv(a);return sr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Qe(o,n):s===17026?t=Qe(o,n):s===17029&&(r=Qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var eS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],qL=[231,22612,22743,167,171,163,160,175],UL=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return sr(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Qe(f,h);l=fa(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=Qe(f,h):p===17545?i=Qe(f,h):p===21420&&l===475249515?u=Qe(f,h):p===374648427?sr(f,({tag:g,type:v,value:S})=>g===30321?(d=Qe(S,v)===1,!1):!0):s&&n&&(0,ma.default)(eS,p)&&(o=!0),!o}),pl(e,"Failed to parse webm Segment start"),pl(t,"Failed to parse webm Segment end"),pl(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}}}},HL=a=>{if(FL(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},jL=(a,e)=>{let t=!1,r=!1,i=o=>Zv(o.time)&&Zv(o.position),s=[],n;return sr(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=Qe(l,u));break;case 183:break;case 241:n&&(n.position=Qe(l,u));break;default:t&&(0,ma.default)(eS,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}}})},GL=a=>{let e=0,t=!1;try{sr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ma.default)(qL,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ma.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},tS={validateData:Xv,parseInit:UL,getIndexRange:HL,parseSegments:jL,parseFeedableSegmentChunk:GL};var ba=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 zv}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Sl=B(TS(),1),jS=B(Lr(),1),GS=B(VS(),1),QS=B(Hr(),1);var _S=B(Xe(),1),vl=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,_S.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as qS,isNullable as US}from"@vkontakte/videoplayer-shared/es2018";var NS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var FS=a=>{var e;try{let t=FM(),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 FM(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<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 GS=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},pt=(a,e)=>{let t=a;t=(0,Il.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,WS.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Il.default)(t,n,(o,u)=>QS(s)?o:QS(u)?s:(0,YS.default)(s,parseInt(u,10),"0"))}return t},KS=(a,e)=>{var I,A,F,D,L,q,O,k,w,H,J,S,R,j,V,le,We,ei,Ft,_,Z,Ee,Le,mt,hr,bt,qt,fr,ti,rc,ic,ac,sc,nc,oc,uc,lc,cc,dc,pc,hc,fc,mc,bc,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc;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(se=>{var Ha,gt;return(gt=(Ha=se.textContent)==null?void 0:Ha.trim())!=null?gt:""}),u=(I=(0,zS.default)(o,0))!=null?I:"",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],v=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)h=GS(f);else if(b){let se=GS(b);jS(se)&&(h=se)}else v&&(h=parseInt(v,10));let y=0,T=(F=(A=s.getAttribute("profiles"))==null?void 0:A.split(","))!=null?F:[];for(let se of l){let Ha=(D=se.getAttribute("id"))!=null?D:"id"+(y++).toString(10),gt=(L=se.getAttribute("mimeType"))!=null?L:"",Vn=(q=se.getAttribute("codecs"))!=null?q:"",Bn=(O=se.getAttribute("contentType"))!=null?O:gt==null?void 0:gt.split("/")[0],bT=(w=(k=se.getAttribute("profiles"))==null?void 0:k.split(","))!=null?w:[],Cc=(J=HS((H=se.getAttribute("lang"))!=null?H:""))!=null?J:{},gT=(j=(R=(S=se.querySelector("Label"))==null?void 0:S.textContent)==null?void 0:R.trim())!=null?j:void 0,vT=se.querySelectorAll("Representation"),ST=se.querySelector("SegmentTemplate"),yT=(le=(V=se.querySelector("Role"))==null?void 0:V.getAttribute("value"))!=null?le:void 0,ri=Bn,ee={id:Ha,language:Cc.language,isDefault:yT==="main",label:gT,codecs:Vn,hdr:ri==="video"&&Tl(Vn),mime:gt,representations:[]};for(let G of vT){let TT=(We=G.getAttribute("lang"))!=null?We:void 0,IT=(ei=G.getAttribute("label"))!=null?ei:void 0,ET=(Z=(_=(Ft=G.querySelector("BaseURL"))==null?void 0:Ft.textContent)==null?void 0:_.trim())!=null?Z:"",ja=new URL(ET||u,e).toString(),mr=(Ee=G.getAttribute("mimeType"))!=null?Ee:gt,Qa=(mt=(Le=G.getAttribute("codecs"))!=null?Le:Vn)!=null?mt:"",Ga;if(Bn==="text"){let vt=G.getAttribute("id")||"",Wa=((hr=Cc.privateuse)==null?void 0:hr.includes("x-auto"))||vt.includes("_auto"),Ut=G.querySelector("SegmentTemplate");if(Ut){let ii={representationId:(bt=G.getAttribute("id"))!=null?bt:void 0,bandwidth:(qt=G.getAttribute("bandwidth"))!=null?qt:void 0},Ya=parseInt((fr=G.getAttribute("bandwidth"))!=null?fr:"",10)/1e3,za=(rc=parseInt((ti=Ut.getAttribute("startNumber"))!=null?ti:"",10))!=null?rc:1,br=parseInt((ic=Ut.getAttribute("timescale"))!=null?ic:"",10),_n=(ac=Ut.querySelectorAll("SegmentTimeline S"))!=null?ac:[],gr=Ut.getAttribute("media");if(!gr)continue;let Ka=[],Ja=0,Xa="",vr=0,ai=za,ce=0;for(let Ne of _n){let Ht=parseInt((sc=Ne.getAttribute("d"))!=null?sc:"",10),Me=parseInt((nc=Ne.getAttribute("r"))!=null?nc:"",10)||0,St=parseInt((oc=Ne.getAttribute("t"))!=null?oc:"",10);ce=Number.isFinite(St)?St:ce;let jt=Ht/br*1e3,yt=ce/br*1e3;for(let Ye=0;Ye<Me+1;Ye++){let Tt=pt(gr,{...ii,segmentNumber:ai.toString(10),segmentTime:(ce+Ye*Ht).toString(10)}),Sr=(yt!=null?yt:0)+Ye*jt,ni=Sr+jt;ai++,Ka.push({time:{from:Sr,to:ni},url:Tt})}ce+=(Me+1)*Ht,Ja+=(Me+1)*jt}vr=ce/br*1e3,Xa=pt(gr,{...ii,segmentNumber:ai.toString(10),segmentTime:ce.toString(10)});let si={time:{from:vr,to:1/0},url:Xa},it={type:"template",baseUrl:ja,segmentTemplateUrl:gr,initUrl:"",totalSegmentsDurationMs:Ja,segments:Ka,nextSegmentBeyondManifest:si,timescale:br};Ga={id:vt,kind:"text",segmentReference:it,profiles:[],duration:h,bitrate:Ya,mime:"",codecs:"",width:0,height:0,isAuto:Wa}}else Ga={id:vt,isAuto:Wa,kind:"text",url:ja}}else{let vt=(lc=(uc=G.getAttribute("contentType"))!=null?uc:mr==null?void 0:mr.split("/")[0])!=null?lc:Bn,Wa=(dc=(cc=se.getAttribute("profiles"))==null?void 0:cc.split(","))!=null?dc:[],Ut=parseInt((pc=G.getAttribute("width"))!=null?pc:"",10),ii=parseInt((hc=G.getAttribute("height"))!=null?hc:"",10),Ya=parseInt((fc=G.getAttribute("bandwidth"))!=null?fc:"",10)/1e3,za=(mc=G.getAttribute("frameRate"))!=null?mc:"",br=(bc=G.getAttribute("quality"))!=null?bc:void 0,_n=za?US(za):void 0,gr=(gc=G.getAttribute("id"))!=null?gc:"id"+(y++).toString(10),Ka=vt==="video"?`${ii}p`:vt==="audio"?`${Ya}Kbps`:Qa,Ja=`${gr}@${Ka}`,Xa=[...T,...bT,...Wa],vr,ai=G.querySelector("SegmentBase"),ce=(vc=G.querySelector("SegmentTemplate"))!=null?vc:ST;if(ai){let it=(yc=(Sc=G.querySelector("SegmentBase Initialization"))==null?void 0:Sc.getAttribute("range"))!=null?yc:"",[Ne,Ht]=it.split("-").map(Tt=>parseInt(Tt,10)),Me={from:Ne,to:Ht},St=(Tc=G.querySelector("SegmentBase"))==null?void 0:Tc.getAttribute("indexRange"),[jt,yt]=St?St.split("-").map(Tt=>parseInt(Tt,10)):[],Ye=St?{from:jt,to:yt}:void 0;vr={type:"byteRange",url:ja,initRange:Me,indexRange:Ye}}else if(ce){let it={representationId:(Ic=G.getAttribute("id"))!=null?Ic:void 0,bandwidth:(Ec=G.getAttribute("bandwidth"))!=null?Ec:void 0},Ne=parseInt((xc=ce.getAttribute("timescale"))!=null?xc:"",10),Ht=(Pc=ce.getAttribute("initialization"))!=null?Pc:"",Me=ce.getAttribute("media"),St=(wc=parseInt((Ac=ce.getAttribute("startNumber"))!=null?Ac:"",10))!=null?wc:1,jt=pt(Ht,it);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let yt=(kc=ce.querySelectorAll("SegmentTimeline S"))!=null?kc:[],Ye=[],Tt=0,Sr="",ni=0;if(yt.length){let Za=St,Fe=0;for(let yr of yt){let ze=parseInt((Rc=yr.getAttribute("d"))!=null?Rc:"",10),Qt=parseInt(($c=yr.getAttribute("r"))!=null?$c:"",10)||0,es=parseInt((Lc=yr.getAttribute("t"))!=null?Lc:"",10);Fe=Number.isFinite(es)?es:Fe;let Nn=ze/Ne*1e3,Fn=Fe/Ne*1e3;for(let ts=0;ts<Qt+1;ts++){let PT=pt(Me,{...it,segmentNumber:Za.toString(10),segmentTime:(Fe+ts*ze).toString(10)}),Dc=(Fn!=null?Fn:0)+ts*Nn,AT=Dc+Nn;Za++,Ye.push({time:{from:Dc,to:AT},url:PT})}Fe+=(Qt+1)*ze,Tt+=(Qt+1)*Nn}ni=Fe/Ne*1e3,Sr=pt(Me,{...it,segmentNumber:Za.toString(10),segmentTime:Fe.toString(10)})}else if(jS(h)){let Fe=parseInt((Mc=ce.getAttribute("duration"))!=null?Mc:"",10)/Ne*1e3,yr=Math.ceil(h/Fe),ze=0;for(let Qt=1;Qt<yr;Qt++){let es=pt(Me,{...it,segmentNumber:Qt.toString(10),segmentTime:ze.toString(10)});Ye.push({time:{from:ze,to:ze+Fe},url:es}),ze+=Fe}ni=ze,Sr=pt(Me,{...it,segmentNumber:yr.toString(10),segmentTime:ze.toString(10)})}let xT={time:{from:ni,to:1/0},url:Sr};vr={type:"template",baseUrl:ja,segmentTemplateUrl:Me,initUrl:jt,totalSegmentsDurationMs:Tt,segments:Ye,nextSegmentBeyondManifest:xT,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!vt||!mr)continue;let si={video:"video",audio:"audio",text:"text"}[vt];if(!si)continue;ri||(ri=si),Ga={id:Ja,kind:si,segmentReference:vr,profiles:Xa,duration:h,bitrate:Ya,mime:mr,codecs:Qa,width:Ut,height:ii,fps:_n,quality:br}}ee.language||(ee.language=TT),ee.label||(ee.label=IT),ee.mime||(ee.mime=mr),ee.codecs||(ee.codecs=Qa),ee.hdr||(ee.hdr=ri==="video"&&Tl(Qa)),ee.representations.push(Ga)}ri&&i[ri].push(ee)}return{dynamic:d,liveAvailabilityStartTime:p,duration:h,streams:i,baseUrls:o}};var Pl=C(Ur(),1);import{videoSizeToQuality as jM}from"@vkontakte/videoplayer-shared/es2018";var JS=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Rt(s):void 0)!=null?u:jM({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},XS=({id:a,bitrate:e})=>({id:a,bitrate:e}),ZS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ey=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Al=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Pl.default)(r.split("."),0),isDefault:i}),wl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Pl.default)(i.split("."),0)}),kl=a=>"url"in a,Re=a=>a.type==="template",va=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Sa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new zr(0);this.currentSegmentLength$=new zr(0);this.onLastSegment$=new zr(!1);this.fullyBuffered$=new zr(!1);this.playingRepresentation$=new zr(void 0);this.playingRepresentationInit$=new zr(void 0);this.error$=new GM;this.gaps=[];this.subscription=new WM;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ke;this.switchAbortController=new ke;this.destroyAbortController=new ke;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=nr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);pe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Jv(this.sourceBuffer),this.subscription.add(Rl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Rl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Dt.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,hl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=tt(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);pe(r,"No init buffer for starting representation"),pe(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=nr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);pe(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(_e(s)||_e(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),pe(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();un(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=nr(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,dn.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||!Re(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);pe(i);let s=this.segments.get(r);pe(s,"No segments for starting representation");let n=this.initData.get(r);if(pe(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 ke,nr(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);pe(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(_e(o)||_e(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),pe(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();un(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 ke,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,d;if(_e(e)||_e(this.downloadingRepresentationId)||_e(this.playingRepresentationId)||_e(this.sourceBuffer)||un(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(pe(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=tt(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)&&hl(this.sourceBuffer.buffered)>=this.bufferLimit){let c=tt(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,cn.default)(o,i))c="high";else{let p=(0,Kr.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&&tt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Kr.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;un(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,dn.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,dn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Re(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,Kr.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;pe(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(!Re(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=pt(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&&Yi&&Yi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Yi&&Yi(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,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=r+v||h<=r+v;return(c==="none"||c==="partially_ejected"&&g&&y&&this.sourceBuffer&&!(Mt(this.sourceBuffer.buffered,p)&&Mt(this.sourceBuffer.buffered,h)))&&g&&y});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,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}async loadSegments(e,t,r="auto"){Re(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await nr(o,async function*(){let d=$l(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=ln(),!d)return;let c=new DataView(d),p=ga(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?await Promise.all(l):await 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]),va(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())Re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await nr(n,async function*(){let u=$l(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Rl(window,"online").pipe(QM()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=ln(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),va(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Re(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Kr.default)(e,0).byte.from,to:(0,Kr.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=ln(),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:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Re(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=ln();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:Dt.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,cn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=ga(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-r,c=l.byte.to-r,p=c-d+1,h=d<i,f=c<=i;if(!h)continue;let b=ga(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(pe(this.sourceBuffer),Mt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Mt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Dt.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",kl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");pe(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=cl(()=>(0,ty.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?nr(this.destroyAbortController.signal,async function*(){let o=$l(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ga(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&Re(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:Dt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||_e(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({...u.time}),i=n(i);let l=kl(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,cn.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?(await 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||_e(e)?0:tt(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){pe(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=cl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Dt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(_e(this.sourceBuffer)||_e(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 ya=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ry=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 Ta,assertNever as ay,fromEvent as sy,merge as YM,now as Ia,Subscription as zM,ValueSubject as Ll,flattenObject as Jr}from"@vkontakte/videoplayer-shared/es2018";var iy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var pn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Ll(void 0);this.lastConnectionReused$=new Ll(void 0);this.lastRequestFirstBytes$=new Ll(void 0);this.abortAllController=new ke;this.subscription=new zM;this.fetchManifest=Ta(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ya(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=iy(r));let i=yield lt(r,{signal:this.abortAllController.signal}).catch(Ea);return i?(t.log("success",Jr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Jr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Ta(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var O,k;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let w=new URL(l,location.href);w.searchParams.append("bytes",`${r.from}-${r.to}`),l=w.toString();break}default:ay(t)}this.requestQuic&&(l=ya(l));let p=this.abortAllController.signal,h;if(n){let w=new ke;if(h=YM(sy(this.abortAllController.signal,"abort"),sy(n,"abort")).subscribe(()=>{try{w.abort()}catch(H){Ea(H)}}),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch(H){Ea(H)}p=w.signal}let f=Ia();c.log("startRequest",Jr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield lt(l,{priority:s,headers:d,signal:p}).catch(Ea),g=Ia();if(!b)return c.error("error",{message:"No response in request"}),c.end(),h==null||h.unsubscribe(),null;if((O=this.throughputEstimator)==null||O.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let w=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:w}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let w=Ia(),H={requestStartedAt:f,requestEndedAt:w,duration:w-f};return c.log("endRequest",Jr(H)),c.end(),b.arrayBuffer()}let[v,y]=b.body.tee(),T=v.getReader();o&&((k=this.throughputEstimator)==null||k.trackStream(y,u));let E=0,I=new Uint8Array(0),A=!1,F=w=>{h==null||h.unsubscribe(),A=!0,Ea(w)},D=Ta(p,async function*({done:w,value:H}){if(E===0&&this.lastRequestFirstBytes$.next(Ia()-f),p.aborted){h==null||h.unsubscribe();return}if(!w&&H){let J=new Uint8Array(I.length+H.length);J.set(I),J.set(H,I.length),I=J,E+=H.byteLength,i==null||i(new DataView(I.buffer),E),yield T==null?void 0:T.read().then(D,F)}}.bind(this));yield T==null?void 0:T.read().then(D,F),h==null||h.unsubscribe();let L=Ia(),q={failed:A,requestStartedAt:f,requestEndedAt:L,duration:L-f};return A?(c.error("endRequest",Jr(q)),c.end(),null):(c.log("endRequest",Jr(q)),c.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=Ta(this.abortAllController.signal,async function*(e,t,r){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,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=(v=e.indexRange)!=null?v: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 y=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!y)return null;b=new DataView(y)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=Ta(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=ry(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:ay(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ea=a=>{if(!va(a))throw a};var or=(a,e,t)=>t*e+(1-t)*a,Ml=(a,e)=>a.reduce((t,r)=>t+r,0)/e,ny=(a,e,t,r)=>{let i=0,s=t,n=Ml(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 KM,ValueSubject as oy}from"@vkontakte/videoplayer-shared/es2018";var Ot=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 oy(e.initial),this.debounced$=new oy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new de(`raw_${t}`),this.smoothedSeries$=new de(`smoothed_${t}`),this.reportedSeries$=new de(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(KM(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 hn=class extends Ot{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=or(this.slow,e,this.params.emaAlphaSlow),this.fast=or(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var fn=class extends Ot{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ml(this.pastMeasures,this.takenMeasures);this.emaSmoothed=or(this.emaSmoothed,e,this.params.emaAlpha);let r=ny(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var mn=class extends Ot{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?or(this.smoothed,t,this.params.emaAlpha):t}};var ur=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new hn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new fn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new mn({initial:e,label:"liveEdgeDelay",...t})}};var Cl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as JM,ValueSubject as XM}from"@vkontakte/videoplayer-shared/es2018";var xa=class a{constructor(e,t){this.currentRepresentation$=new XM(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(!JM(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({...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&&Re(t.segmentReference))}};var nC=["timeupdate","progress","play","seeked","stalled","waiting"],oC=["timeupdate","progress","loadeddata","playing","seeked"];var gn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new dy;this.representationSubscription=new dy;this.state$=new $("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new cy;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.liveDuration$=new K(0);this.liveAvailabilityStartTime$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.isLowLatency$=new K(!1);this.isActiveLowLatency$=new K(!1);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new cy;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=Dl(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ue(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:Vt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Dl(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Vt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=KS(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Qv(e))!=null?n:{id:"ManifestParsing",category:Vt.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=ct())==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=Ev(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);tC.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",Aa(s)),s}.bind(this));this.initRepresentations=Dl(this.destroyController.signal,async function*(e,t,r){var p;this.tracer.log("initRepresentationsStart",Aa({initialVideo:e,initialAudio:t,sourceHls:r})),lr(this.manifest),lr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=h=>{this.representationSubscription.add(cr(h,"error").pipe(bn(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Vt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?nv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ks())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 Sa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ly(t)){let h=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new Sa("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}xa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new xa(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(Vl(1e3).subscribe(h=>{var f;if((f=this.element)!=null&&f.paused){let b=Bs(this.manifestUrlString,2);this.manifestUrlString=ue(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(dr(...oC.map(h=>cr(this.element,h))).pipe(wa(h=>this.element?tt(this.element.buffered,this.element.currentTime*1e3):0),Ol(),aC(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(dr(cr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ol()).subscribe(f=>Cl(this.element,1))),this.representationSubscription.add(Pa({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(bn(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(Pa({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(bn(({isLive:f})=>f),wa(f=>({...f})),Ol((f,b)=>b.bufferLength<f.bufferLength),wa(({rtt:f,bufferLength:b,segmentServerLatency:g})=>{let v=Bs(this.manifestUrlString,2);return(f/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Pa({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=f-g,E=1;Math.abs(T)>v&&(E=1+Math.sign(T)*y),Cl(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,v;let b=0;if(f){let y=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var I,A;return(A=(I=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?A:y}))-y}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let h=0;this.representationSubscription.add(Pa({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(sC(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:b})=>{if(lr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Bs(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,A=isFinite(f)?f:b,F=this.isActiveLowLatency$.getValue(),D=y<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(F&&D);let L="none";if(F?L="active_low_latency":this.isLowLatency$.getValue()&&D?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(q=>q.proceedLowLatencyLive()),L="active_low_latency"):v!==0&&A<T?L="live_forward_buffering":A<T+I&&(L="live_with_target_offset"),isFinite(f)&&(h=f>h?f:h),L==="live_forward_buffering"||L==="live_with_target_offset"){let q=h-(T+E),O=this.normolizeLiveOffset(Math.trunc(v+q/g)),k=Math.abs(O-v),w;!f||k<=this.tuning.dashCmafLive.offsetCalculationError?w=v:O>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=O:w=0,this.manifestUrlString=ue(this.manifestUrlString,w,2)}L!=="none"&&L!=="active_low_latency"&&(h=0,this.updateLive())}))}let l=dr(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(wa(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=dr(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(wa(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add(dr(this.forceEnded$,Pa({allBuffersFull:l,someBufferEnded:d}).pipe(bn(({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:Vt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(dr(...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,Bl.default)((0,Bl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Re(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&ly(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=Vl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Vt.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 pn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=ur.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;lr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ue(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){lr(this.element),this.state$.setState("running"),this.subscription.add(dr(...nC.map(e=>cr(this.element,e)),cr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Vt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(cr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(cr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Mt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,v,y,T,E,I,A;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=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,d=(E=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?E: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 F=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(F),(A=this.audioBufferManager)==null||A.maintain(F),i.position=F}this.tracer.log("stallIntervalCallback",Aa(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Vl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Vt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u;lr(this.element),lr(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),Mt(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",Aa({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=rC(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={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={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Aa(t)))}}};var vn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Sn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var py=`attribute vec2 a_vertex;
|
|
69
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var HS=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},pt=(a,e)=>{let t=a;t=(0,Sl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,jS.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Sl.default)(t,n,(o,u)=>US(s)?o:US(u)?s:(0,GS.default)(s,parseInt(u,10),"0"))}return t},WS=(a,e)=>{var I,R,C,G,$,V,_,k,w,H,J,A,T,O,M,Z,Le,mt,hr,F,se,ne,Me,bt,fr,gt,qt,mr,ti,Zl,ec,tc,rc,ic,ac,sc,nc,oc,uc,lc,cc,dc,pc,hc,fc,mc,bc,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc;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(oe=>{var Ua,vt;return(vt=(Ua=oe.textContent)==null?void 0:Ua.trim())!=null?vt:""}),u=(I=(0,QS.default)(o,0))!=null?I:"",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],v=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)h=HS(f);else if(b){let oe=HS(b);qS(oe)&&(h=oe)}else v&&(h=parseInt(v,10));let S=0,y=(C=(R=s.getAttribute("profiles"))==null?void 0:R.split(","))!=null?C:[];for(let oe of l){let Ua=(G=oe.getAttribute("id"))!=null?G:"id"+(S++).toString(10),vt=($=oe.getAttribute("mimeType"))!=null?$:"",Cn=(V=oe.getAttribute("codecs"))!=null?V:"",Dn=(_=oe.getAttribute("contentType"))!=null?_:vt==null?void 0:vt.split("/")[0],fT=(w=(k=oe.getAttribute("profiles"))==null?void 0:k.split(","))!=null?w:[],$c=(J=FS((H=oe.getAttribute("lang"))!=null?H:""))!=null?J:{},mT=(O=(T=(A=oe.querySelector("Label"))==null?void 0:A.textContent)==null?void 0:T.trim())!=null?O:void 0,bT=oe.querySelectorAll("Representation"),gT=oe.querySelector("SegmentTemplate"),vT=(Z=(M=oe.querySelector("Role"))==null?void 0:M.getAttribute("value"))!=null?Z:void 0,ri=Dn,ee={id:Ua,language:$c.language,isDefault:vT==="main",label:mT,codecs:Cn,hdr:ri==="video"&&vl(Cn),mime:vt,representations:[]};for(let Q of bT){let ST=(Le=Q.getAttribute("lang"))!=null?Le:void 0,yT=(mt=Q.getAttribute("label"))!=null?mt:void 0,TT=(se=(F=(hr=Q.querySelector("BaseURL"))==null?void 0:hr.textContent)==null?void 0:F.trim())!=null?se:"",Ha=new URL(TT||u,e).toString(),br=(ne=Q.getAttribute("mimeType"))!=null?ne:vt,ja=(bt=(Me=Q.getAttribute("codecs"))!=null?Me:Cn)!=null?bt:"",Ga;if(Dn==="text"){let St=Q.getAttribute("id")||"",Qa=((fr=$c.privateuse)==null?void 0:fr.includes("x-auto"))||St.includes("_auto"),Ut=Q.querySelector("SegmentTemplate");if(Ut){let ii={representationId:(gt=Q.getAttribute("id"))!=null?gt:void 0,bandwidth:(qt=Q.getAttribute("bandwidth"))!=null?qt:void 0},Wa=parseInt((mr=Q.getAttribute("bandwidth"))!=null?mr:"",10)/1e3,Ya=(Zl=parseInt((ti=Ut.getAttribute("startNumber"))!=null?ti:"",10))!=null?Zl:1,gr=parseInt((ec=Ut.getAttribute("timescale"))!=null?ec:"",10),On=(tc=Ut.querySelectorAll("SegmentTimeline S"))!=null?tc:[],vr=Ut.getAttribute("media");if(!vr)continue;let za=[],Ka=0,Ja="",Sr=0,ai=Ya,de=0;for(let Fe of On){let Ht=parseInt((rc=Fe.getAttribute("d"))!=null?rc:"",10),Ce=parseInt((ic=Fe.getAttribute("r"))!=null?ic:"",10)||0,yt=parseInt((ac=Fe.getAttribute("t"))!=null?ac:"",10);de=Number.isFinite(yt)?yt:de;let jt=Ht/gr*1e3,Tt=de/gr*1e3;for(let Ye=0;Ye<Ce+1;Ye++){let It=pt(vr,{...ii,segmentNumber:ai.toString(10),segmentTime:(de+Ye*Ht).toString(10)}),yr=(Tt!=null?Tt:0)+Ye*jt,ni=yr+jt;ai++,za.push({time:{from:yr,to:ni},url:It})}de+=(Ce+1)*Ht,Ka+=(Ce+1)*jt}Sr=de/gr*1e3,Ja=pt(vr,{...ii,segmentNumber:ai.toString(10),segmentTime:de.toString(10)});let si={time:{from:Sr,to:1/0},url:Ja},it={type:"template",baseUrl:Ha,segmentTemplateUrl:vr,initUrl:"",totalSegmentsDurationMs:Ka,segments:za,nextSegmentBeyondManifest:si,timescale:gr};Ga={id:St,kind:"text",segmentReference:it,profiles:[],duration:h,bitrate:Wa,mime:"",codecs:"",width:0,height:0,isAuto:Qa}}else Ga={id:St,isAuto:Qa,kind:"text",url:Ha}}else{let St=(nc=(sc=Q.getAttribute("contentType"))!=null?sc:br==null?void 0:br.split("/")[0])!=null?nc:Dn,Qa=(uc=(oc=oe.getAttribute("profiles"))==null?void 0:oc.split(","))!=null?uc:[],Ut=parseInt((lc=Q.getAttribute("width"))!=null?lc:"",10),ii=parseInt((cc=Q.getAttribute("height"))!=null?cc:"",10),Wa=parseInt((dc=Q.getAttribute("bandwidth"))!=null?dc:"",10)/1e3,Ya=(pc=Q.getAttribute("frameRate"))!=null?pc:"",gr=(hc=Q.getAttribute("quality"))!=null?hc:void 0,On=Ya?NS(Ya):void 0,vr=(fc=Q.getAttribute("id"))!=null?fc:"id"+(S++).toString(10),za=St==="video"?`${ii}p`:St==="audio"?`${Wa}Kbps`:ja,Ka=`${vr}@${za}`,Ja=[...y,...fT,...Qa],Sr,ai=Q.querySelector("SegmentBase"),de=(mc=Q.querySelector("SegmentTemplate"))!=null?mc:gT;if(ai){let it=(gc=(bc=Q.querySelector("SegmentBase Initialization"))==null?void 0:bc.getAttribute("range"))!=null?gc:"",[Fe,Ht]=it.split("-").map(It=>parseInt(It,10)),Ce={from:Fe,to:Ht},yt=(vc=Q.querySelector("SegmentBase"))==null?void 0:vc.getAttribute("indexRange"),[jt,Tt]=yt?yt.split("-").map(It=>parseInt(It,10)):[],Ye=yt?{from:jt,to:Tt}:void 0;Sr={type:"byteRange",url:Ha,initRange:Ce,indexRange:Ye}}else if(de){let it={representationId:(Sc=Q.getAttribute("id"))!=null?Sc:void 0,bandwidth:(yc=Q.getAttribute("bandwidth"))!=null?yc:void 0},Fe=parseInt((Tc=de.getAttribute("timescale"))!=null?Tc:"",10),Ht=(Ic=de.getAttribute("initialization"))!=null?Ic:"",Ce=de.getAttribute("media"),yt=(xc=parseInt((Ec=de.getAttribute("startNumber"))!=null?Ec:"",10))!=null?xc:1,jt=pt(Ht,it);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");let Tt=(Pc=de.querySelectorAll("SegmentTimeline S"))!=null?Pc:[],Ye=[],It=0,yr="",ni=0;if(Tt.length){let Xa=yt,qe=0;for(let Tr of Tt){let ze=parseInt((Ac=Tr.getAttribute("d"))!=null?Ac:"",10),Gt=parseInt((wc=Tr.getAttribute("r"))!=null?wc:"",10)||0,Za=parseInt((kc=Tr.getAttribute("t"))!=null?kc:"",10);qe=Number.isFinite(Za)?Za:qe;let Bn=ze/Fe*1e3,Vn=qe/Fe*1e3;for(let es=0;es<Gt+1;es++){let ET=pt(Ce,{...it,segmentNumber:Xa.toString(10),segmentTime:(qe+es*ze).toString(10)}),Lc=(Vn!=null?Vn:0)+es*Bn,xT=Lc+Bn;Xa++,Ye.push({time:{from:Lc,to:xT},url:ET})}qe+=(Gt+1)*ze,It+=(Gt+1)*Bn}ni=qe/Fe*1e3,yr=pt(Ce,{...it,segmentNumber:Xa.toString(10),segmentTime:qe.toString(10)})}else if(qS(h)){let qe=parseInt((Rc=de.getAttribute("duration"))!=null?Rc:"",10)/Fe*1e3,Tr=Math.ceil(h/qe),ze=0;for(let Gt=1;Gt<Tr;Gt++){let Za=pt(Ce,{...it,segmentNumber:Gt.toString(10),segmentTime:ze.toString(10)});Ye.push({time:{from:ze,to:ze+qe},url:Za}),ze+=qe}ni=ze,yr=pt(Ce,{...it,segmentNumber:Tr.toString(10),segmentTime:ze.toString(10)})}let IT={time:{from:ni,to:1/0},url:yr};Sr={type:"template",baseUrl:Ha,segmentTemplateUrl:Ce,initUrl:jt,totalSegmentsDurationMs:It,segments:Ye,nextSegmentBeyondManifest:IT,timescale:Fe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!St||!br)continue;let si={video:"video",audio:"audio",text:"text"}[St];if(!si)continue;ri||(ri=si),Ga={id:Ka,kind:si,segmentReference:Sr,profiles:Ja,duration:h,bitrate:Wa,mime:br,codecs:ja,width:Ut,height:ii,fps:On,quality:gr}}ee.language||(ee.language=ST),ee.label||(ee.label=yT),ee.mime||(ee.mime=br),ee.codecs||(ee.codecs=ja),ee.hdr||(ee.hdr=ri==="video"&&vl(ja)),ee.representations.push(Ga)}ri&&i[ri].push(ee)}return{dynamic:d,liveAvailabilityStartTime:p,duration:h,streams:i,baseUrls:o}};var Il=B(Hr(),1);import{videoSizeToQuality as qM}from"@vkontakte/videoplayer-shared/es2018";var YS=({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:qM({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},zS=({id:a,bitrate:e})=>({id:a,bitrate:e}),KS=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),JS=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),El=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Il.default)(r.split("."),0),isDefault:i}),xl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Il.default)(i.split("."),0)}),Pl=a=>"url"in a,Re=a=>a.type==="template",ga=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var va=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Kr(0);this.currentSegmentLength$=new Kr(0);this.onLastSegment$=new Kr(!1);this.fullyBuffered$=new Kr(!1);this.playingRepresentation$=new Kr(void 0);this.playingRepresentationInit$=new Kr(void 0);this.error$=new HM;this.gaps=[];this.subscription=new jM;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ke;this.switchAbortController=new ke;this.destroyAbortController=new ke;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=nr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);he(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Yv(this.sourceBuffer),this.subscription.add(Al(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ot.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Al(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ot.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,cl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=tt(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);he(r,"No init buffer for starting representation"),he(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=nr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);he(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ne(s)||Ne(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),he(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();nn(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=nr(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,ln.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||!Re(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);he(i);let s=this.segments.get(r);he(s,"No segments for starting representation");let n=this.initData.get(r);if(he(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 ke,nr(this.switchAbortController.signal,async function*(r,i=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);he(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Ne(o)||Ne(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),he(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();nn(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 ke,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,d;if(Ne(e)||Ne(this.downloadingRepresentationId)||Ne(this.playingRepresentationId)||Ne(this.sourceBuffer)||nn(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(he(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=tt(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)&&cl(this.sourceBuffer.buffered)>=this.bufferLimit){let c=tt(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,un.default)(o,i))c="high";else{let p=(0,Jr.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&&tt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Jr.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;nn(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,ln.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,ln.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Re(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,Jr.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;he(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(!Re(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=pt(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&&Wi&&Wi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Wi&&Wi(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,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(c==="none"||c==="partially_ejected"&&g&&S&&this.sourceBuffer&&!(Ct(this.sourceBuffer.buffered,p)&&Ct(this.sourceBuffer.buffered,h)))&&g&&S});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,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}async loadSegments(e,t,r="auto"){Re(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await nr(o,async function*(){let d=wl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=on(),!d)return;let c=new DataView(d),p=ba(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?await Promise.all(l):await 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]),ga(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())Re(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await nr(n,async function*(){let u=wl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Al(window,"online").pipe(UM()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=on(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),ga(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Re(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,Jr.default)(e,0).byte.from,to:(0,Jr.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=on(),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:Ot.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Re(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=on();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:Ot.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,un.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){i();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=ba(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let d=l.byte.from-r,c=l.byte.to-r,p=c-d+1,h=d<i,f=c<=i;if(!h)continue;let b=ba(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,i-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v!=null&&v.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(he(this.sourceBuffer),Ct(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ct(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Ot.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",Pl(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");he(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=ol(()=>(0,XS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?nr(this.destroyAbortController.signal,async function*(){let o=wl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ba(e.mime),i)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&Re(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:Ot.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ne(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({...u.time}),i=n(i);let l=Pl(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,un.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?(await 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||Ne(e)?0:tt(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){he(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=ol(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ot.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ne(this.sourceBuffer)||Ne(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 Sa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ZS=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 ya,assertNever as ty,fromEvent as ry,merge as GM,now as Ta,Subscription as QM,ValueSubject as kl,flattenObject as Xr}from"@vkontakte/videoplayer-shared/es2018";var ey=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var cn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new kl(void 0);this.lastConnectionReused$=new kl(void 0);this.lastRequestFirstBytes$=new kl(void 0);this.abortAllController=new ke;this.subscription=new QM;this.fetchManifest=ya(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Sa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=ey(r));let i=yield lt(r,{signal:this.abortAllController.signal}).catch(Ia);return i?(t.log("success",Xr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",Xr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ya(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var _,k;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let w=new URL(l,location.href);w.searchParams.append("bytes",`${r.from}-${r.to}`),l=w.toString();break}default:ty(t)}this.requestQuic&&(l=Sa(l));let p=this.abortAllController.signal,h;if(n){let w=new ke;if(h=GM(ry(this.abortAllController.signal,"abort"),ry(n,"abort")).subscribe(()=>{try{w.abort()}catch(H){Ia(H)}}),this.abortAllController.signal.aborted||n.aborted)try{w.abort()}catch(H){Ia(H)}p=w.signal}let f=Ta();c.log("startRequest",Xr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield lt(l,{priority:s,headers:d,signal:p}).catch(Ia),g=Ta();if(!b)return c.error("error",{message:"No response in request"}),c.end(),h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(g-f),!b.ok||!b.body){h==null||h.unsubscribe();let w=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:w}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!i&&!o){h==null||h.unsubscribe();let w=Ta(),H={requestStartedAt:f,requestEndedAt:w,duration:w-f};return c.log("endRequest",Xr(H)),c.end(),b.arrayBuffer()}let[v,S]=b.body.tee(),y=v.getReader();o&&((k=this.throughputEstimator)==null||k.trackStream(S,u));let E=0,I=new Uint8Array(0),R=!1,C=w=>{h==null||h.unsubscribe(),R=!0,Ia(w)},G=ya(p,async function*({done:w,value:H}){if(E===0&&this.lastRequestFirstBytes$.next(Ta()-f),p.aborted){h==null||h.unsubscribe();return}if(!w&&H){let J=new Uint8Array(I.length+H.length);J.set(I),J.set(H,I.length),I=J,E+=H.byteLength,i==null||i(new DataView(I.buffer),E),yield y==null?void 0:y.read().then(G,C)}}.bind(this));yield y==null?void 0:y.read().then(G,C),h==null||h.unsubscribe();let $=Ta(),V={failed:R,requestStartedAt:f,requestEndedAt:$,duration:$-f};return R?(c.error("endRequest",Xr(V)),c.end(),null):(c.log("endRequest",Xr(V)),c.end(),I.buffer)}.bind(this));this.fetchByteRangeRepresentation=ya(this.abortAllController.signal,async function*(e,t,r){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,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=(v=e.indexRange)!=null?v: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 S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=ya(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(i)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=ZS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:ty(i)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Ia=a=>{if(!ga(a))throw a};var or=(a,e,t)=>t*e+(1-t)*a,Rl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,iy=(a,e,t,r)=>{let i=0,s=t,n=Rl(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 WM,ValueSubject as ay}from"@vkontakte/videoplayer-shared/es2018";var Bt=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 ay(e.initial),this.debounced$=new ay(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new pe(`raw_${t}`),this.smoothedSeries$=new pe(`smoothed_${t}`),this.reportedSeries$=new pe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(WM(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 dn=class extends Bt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=or(this.slow,e,this.params.emaAlphaSlow),this.fast=or(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var pn=class extends Bt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Rl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=or(this.emaSmoothed,e,this.params.emaAlpha);let r=iy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var hn=class extends Bt{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?or(this.smoothed,t,this.params.emaAlpha):t}};var ur=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new dn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new pn({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 hn({initial:e,label:"liveEdgeDelay",...t})}};var $l=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as YM,ValueSubject as zM}from"@vkontakte/videoplayer-shared/es2018";var Ea=class a{constructor(e,t){this.currentRepresentation$=new zM(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(!YM(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({...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&&Re(t.segmentReference))}};var i0=["timeupdate","progress","play","seeked","stalled","waiting"],a0=["timeupdate","progress","loadeddata","playing","seeked"];var mn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new uy;this.representationSubscription=new uy;this.state$=new L("none");this.currentVideoRepresentation$=new K(void 0);this.currentVideoRepresentationInit$=new K(void 0);this.currentAudioRepresentation$=new K(void 0);this.currentVideoSegmentLength$=new K(0);this.currentAudioSegmentLength$=new K(0);this.error$=new oy;this.lastConnectionType$=new K(void 0);this.lastConnectionReused$=new K(void 0);this.lastRequestFirstBytes$=new K(void 0);this.currentLiveTextRepresentation$=new K(null);this.isLive$=new K(!1);this.liveDuration$=new K(0);this.liveAvailabilityStartTime$=new K(void 0);this.bufferLength$=new K(0);this.liveLatency$=new K(void 0);this.liveLoadBufferLength$=new K(0);this.livePositionFromPlayer$=new K(0);this.isLowLatency$=new K(!1);this.isActiveLowLatency$=new K(!1);this.currentStallDuration$=new K(0);this.videoLastDataObtainedTimestamp$=new K(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new oy;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=Ll(this.destroyController.signal,async function*(e,t,r){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ce(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:Vt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Ll(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Vt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=WS(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=Uv(e))!=null?n:{id:"ManifestParsing",category:Vt.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=ct())==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=yv(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);XM.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s={...t,streams:i};return this.tracer.log("updateManifestEnd",Pa(s)),s}.bind(this));this.initRepresentations=Ll(this.destroyController.signal,async function*(e,t,r){var p;this.tracer.log("initRepresentationsStart",Pa({initialVideo:e,initialAudio:t,sourceHls:r})),lr(this.manifest),lr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=h=>{this.representationSubscription.add(cr(h,"error").pipe(fn(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Vt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?iv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ys())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 va("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ny(t)){let h=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new va("audio",this.source,h,n),this.bufferManagers.push(this.audioBufferManager)}Ea.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ea(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(Cl(1e3).subscribe(h=>{var f;if((f=this.element)!=null&&f.paused){let b=Bs(this.manifestUrlString,2);this.manifestUrlString=ce(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(dr(...a0.map(h=>cr(this.element,h))).pipe(Aa(h=>this.element?tt(this.element.buffered,this.element.currentTime*1e3):0),Ml(),t0(h=>{h>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(dr(cr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ml()).subscribe(f=>$l(this.element,1))),this.representationSubscription.add(xa({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(fn(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(xa({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(fn(({isLive:f})=>f),Aa(f=>({...f})),Ml((f,b)=>b.bufferLength<f.bufferLength),Aa(({rtt:f,bufferLength:b,segmentServerLatency:g})=>{let v=Bs(this.manifestUrlString,2);return(f/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(xa({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=f-g,E=1;Math.abs(y)>v&&(E=1+Math.sign(y)*S),$l(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,v;let b=0;if(f){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var I,R;return(R=(I=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?R:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let h=0;this.representationSubscription.add(xa({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(r0(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:b})=>{if(lr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Bs(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,I=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,R=isFinite(f)?f:b,C=this.isActiveLowLatency$.getValue(),G=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(C&&G);let $="none";if(C?$="active_low_latency":this.isLowLatency$.getValue()&&G?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(V=>V.proceedLowLatencyLive()),$="active_low_latency"):v!==0&&R<y?$="live_forward_buffering":R<y+I&&($="live_with_target_offset"),isFinite(f)&&(h=f>h?f:h),$==="live_forward_buffering"||$==="live_with_target_offset"){let V=h-(y+E),_=this.normolizeLiveOffset(Math.trunc(v+V/g)),k=Math.abs(_-v),w;!f||k<=this.tuning.dashCmafLive.offsetCalculationError?w=v:_>0&&k>this.tuning.dashCmafLive.offsetCalculationError?w=_:w=0,this.manifestUrlString=ce(this.manifestUrlString,w,2)}$!=="none"&&$!=="active_low_latency"&&(h=0,this.updateLive())}))}let l=dr(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(Aa(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),d=dr(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(Aa(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add(dr(this.forceEnded$,xa({allBuffersFull:l,someBufferEnded:d}).pipe(fn(({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:Vt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(dr(...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,Dl.default)((0,Dl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Re(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&ny(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=Cl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Vt.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 cn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=ur.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,i,s;lr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ce(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio)),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))}initBuffer(){lr(this.element),this.state$.setState("running"),this.subscription.add(dr(...i0.map(e=>cr(this.element,e)),cr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Vt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(cr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(cr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ct(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,v,S,y,E,I,R;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=e0(),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=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,d=(E=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?E: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 C=this.element.currentTime*1e3;(I=this.videoBufferManager)==null||I.maintain(C),(R=this.audioBufferManager)==null||R.maintain(C),i.position=C}this.tracer.log("stallIntervalCallback",Pa(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Cl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Vt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)}seek(e,t){var i,s,n,o,u;lr(this.element),lr(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),Ct(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",Pa({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=ZM(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={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={...t,gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",Pa(t)))}}};var bn=class{constructor(e,t){this.fov=e,this.orientation=t}};var gn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var ly=`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 cy=`#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 yn=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 vn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Sn(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(py,this.gl.VERTEX_SHADER),r=this.createShader(hy,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 cC,now as fy,Subscription as dC,filter as pC,combine as my,ValueSubject as by,isNonNullable as hC}from"@vkontakte/videoplayer-shared/es2018";var _l=class{constructor(){this.isSeeked$=new by(!1);this.isBuffering$=new by(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new dC}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(my({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(pC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(my({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(cC(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=fy(),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,hC(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=fy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},gy=_l;var pr=class{constructor(e){this.subscription=new IC;this.videoState=new $("stopped");this.elementSize$=new EC(void 0);this.textTracksManager=new De;this.droppedFramesManager=new Gs;this.stallsManager=new gy;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Vi;this.audioTrackSwitchHistory=new Vi;this.syncPlayback=()=>{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 bC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new yn(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.elementSize$.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=me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new gn({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=ve(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Nl.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(vy(c=>!!c.length),yy()).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(Fl(c=>c.to.state!=="none"),Ra());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ra()),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(vy(Sy),yy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Fl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ze(this.video,t.isLooped,i)),this.subscription.add(ge(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ce(this.video,t.playbackRate,r.playbackRateState$,i)),s(TC(this.video),this.elementSize$),s(Ve(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(gC(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(Al(b));let g=[];for(let v of b.representations){let y=XS(v);g.push(y),this.audioTracksMap.set(y,{stream:b,representation:v})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let h=[];for(let f of p.video){h.push(wl(f));let b=[];for(let g of f.representations){let v=JS({...g,streamId:f.id});v&&(b.push(v),this.videoTracksMap.set(v,{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=ZS(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:Nl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Tn(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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,SC(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(!(0,Ty.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(y=>{var T;return((T=this.videoTracksMap.get(y))==null?void 0:T.representation.id)===f.id});Sy(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.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 y=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",b.id,y).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.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ra()).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(wl(f))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ra()).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(Al(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(Fl(({to:c})=>c==="ready"),Ra());this.subscription.add(Tn(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(Tn(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Tn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,yC(["init"])).pipe(vC(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var A,F,D,L,q,O,k,w,H,J,S,R,j;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(A=e.videoTrack.getState())==null?void 0:A.id,n=[...this.videoTracksMap.keys()].find(({id:V})=>V===i),o=t.currentVideoTrack$.getValue(),u=((L=(D=e.videoStream.getState())!=null?D:n&&((F=this.videoTracksMap.get(n))==null?void 0:F.stream))!=null?L: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=tt(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=(q=e.audioStream.getState())!=null?q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(O=[...this.audioStreamsMap.keys()].find(({id:V})=>V===(f==null?void 0:f.id)))!=null?O:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let V=Us(n,d,(k=this.audioStreamsMap.get(b))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(w=V==null?void 0:V.bitrate)!=null?w:-1/0)}if(o){let V=Us(o,d,(H=this.audioStreamsMap.get(b))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(J=V==null?void 0:V.bitrate)!=null?J:-1/0)}}let v=Lt(d,{container:this.elementSize$.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}),y=r?v!=null?v:n:n!=null?n:v,T=b&&Eg(y,d,(S=this.audioStreamsMap.get(b))!=null?S:[],{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}),E=(R=this.videoTracksMap.get(y))==null?void 0:R.representation,I=T&&((j=this.audioTracksMap.get(T))==null?void 0:j.representation);if(E&&I)return[E,I];if(E&&!I&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Se(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:Nl.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),be(this.video),this.tracer.end()}};var $a=class extends pr{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 Iy,interval as xC,map as Ey}from"@vkontakte/videoplayer-shared/es2018";var La=class extends pr{constructor(e){super(e),this.liveOffset=new ot,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(Ey(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Iy({interval:xC(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(Iy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Ey(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=ey(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 Py=C(Vs(),1);import{assertNever as Ma,assertNonNullable as xy,debounce as PC,ErrorCategory as In,filter as AC,isNonNullable as wC,isNullable as kC,map as En,merge as RC,Observable as $C,observableFrom as LC,Subscription as MC,videoSizeToQuality as CC}from"@vkontakte/videoplayer-shared/es2018";var Ge={};var Xr=(a,e)=>new $C(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ca=class{constructor(e){this.subscription=new MC;this.videoState=new $("initializing");this.textTracksManager=new De;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:Ma(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ma(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ma(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:Ma(e)}break;default:Ma(t)}};this.video=me(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),be(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:In.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Py.default)(import("hls.js").then(i=>{e||(Ge.Hls=i.default,Ge.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){xy(Ge.Hls,"hls.js not loaded"),this.hls=new Ge.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){xy(Ge.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:In.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=ve(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(Ze(this.video,e.isLooped,r)),this.subscription.add(ge(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ce(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ve(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(En(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Xr(this.hls,Ge.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:In.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(Xr(this.hls,Ge.Events.MANIFEST_PARSED).pipe(En(({levels:l})=>l.reduce((d,c)=>{var y,T;let p=c.name||c.height.toString(10),{width:h,height:f}=c,b=(T=Rt((y=c.attrs.QUALITY)!=null?y:""))!=null?T:CC({width:h,height:f});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),s(Xr(this.hls,Ge.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(Xr(this.hls,Ge.Events.LEVEL_LOADING).pipe(En(({url:l})=>ie(l))),t.hostname$),s(Xr(this.hls,Ge.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(At(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=Xr(this.hls,Ge.Events.LEVEL_SWITCHED).pipe(En(({level:l})=>n(this.hls.levels[l])));o.pipe(AC(wC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(At(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(kC(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=RC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,LC(["init"])).pipe(PC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await Se(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:In.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 Ay="X-Playback-Duration",ql=async a=>{var i;let e=await lt(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Ay)?parseInt(e.headers.get(Ay),10):void 0};import{assertNever as NC,combine as FC,debounce as qC,ErrorCategory as Pn,filter as UC,filterChanged as HC,isNonNullable as ky,isNullable as An,map as Ry,merge as jC,observableFrom as QC,Subscription as GC,ValueSubject as jl,VideoQuality as WC}from"@vkontakte/videoplayer-shared/es2018";var Hl=C(zo(),1);import{videoSizeToQuality as DC,getExponentialDelay as OC}from"@vkontakte/videoplayer-shared/es2018";var VC=a=>{let e=null;if(a.QUALITY&&(e=Rt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=DC({width:t,height:r})}return e!=null?e:null},BC=(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,Hl.default)(l[1].split(",").map(y=>y.split("="))),p=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,h=VC(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[y,T]=c.RESOLUTION.split("x").map(E=>parseInt(E,10));y&&T&&(g={width:y,height:T})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(d){let c=(0,Hl.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}},_C=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Ul=0,wy=async(a,e=a,t)=>{let i=await(await lt(a)).text();Ul+=1;try{let{qualityManifests:s,textTracks:n}=BC(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(Ul<=t.manifestRetryMaxCount)return await _C(OC(Ul-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),wy(a,e,t)}return{qualityManifests:[],textTracks:[]}},xn=wy;var Da=class{constructor(e){this.subscription=new GC;this.videoState=new $("stopped");this.textTracksManager=new De;this.manifests$=new jl([]);this.liveOffset=new ot;this.manifestStartTime$=new jl(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 NC(t)}};var t;this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:WC.INVARIANT,url:this.params.source.url},xn(ue(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:Pn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Pn.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(ie(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new jl((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:Pn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=ve(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(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(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(HC(),Ry(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&&ky(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(ie(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(FC({startTime:this.manifestStartTime$.pipe(UC(ky)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Ry(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=jC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,QC(["init"])).pipe(qC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){var o,u;let e=this.selectManifest();if(An(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=ue(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ql(n).then(l=>{var d;if(!An(l))this.maxSeekBackTime$.next(l);else{let c=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();if(An(c)||!isFinite(c))try{lt(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();ql(b).then(g=>{An(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){Se(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:Pn.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 YC,debounce as zC,ErrorCategory as Ql,fromEvent as Gl,isNonNullable as KC,isNullable as JC,map as $y,merge as Ly,observableFrom as My,Subscription as XC,ValueSubject as ZC,VideoQuality as e0,clientChecker as t0}from"@vkontakte/videoplayer-shared/es2018";var Oa=class{constructor(e){this.subscription=new XC;this.videoState=new $("stopped");this.textTracksManager=new De;this.manifests$=new ZC([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),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 YC(t)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:e0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),xn(ue(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:Ql.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:Ql.WTF,message:"HlsProvider internal logic error",thrown:o})},i=ve(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($y(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ze(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(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&&KC(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(ie(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($y(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)),!t0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Ly(Gl(o,"addtrack"),Gl(o,"removetrack"),Gl(o,"change"),My(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Ly(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,My(["init"])).pipe(zC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),be(this.video)}prepare(){var s,n;let e=this.selectManifest();if(JC(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(){Se(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:Ql.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Vy=C($r(),1),Va=C(Mi(),1);import{assertNever as r0,assertNonNullable as Cy,debounce as i0,ErrorCategory as Dy,isHigher as a0,isHigherOrEqual as s0,isInvariantQuality as Oy,isLowerOrEqual as n0,isNonNullable as o0,merge as u0,observableFrom as l0,Subscription as c0,map as d0}from"@vkontakte/videoplayer-shared/es2018";var Ba=class{constructor(e){this.subscription=new c0;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new De;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 r0(e)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Vy.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,Va.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:Dy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=ve(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(d0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ze(this.video,t.isLooped,r)),this.subscription.add(ge(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ce(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(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&&o0(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=u0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,l0(["init"])).pipe(i0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),be(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Cy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Cy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ya(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ie(t))}playIfAllowed(){Se(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:Dy.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,Va.default)(this.trackUrls).find(c=>!Oy(c.track.quality)&&n0(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&&s0(d.quality,u.quality)&&(t=u),!t){let c=(0,Va.default)(this.trackUrls).filter(h=>!Oy(h.track.quality)&&a0(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Va.default)(this.trackUrls).map(l=>l.track);t=Lt(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 _y,debounce as m0,merge as Ny,observableFrom as b0,Subscription as g0,map as Fy,ValueSubject as v0,ErrorCategory as Yl,VideoQuality as S0}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as p0}from"@vkontakte/videoplayer-shared/es2018";var By=["stun:videostun.mycdn.me:80"],h0=1e3,f0=3,Wl=()=>null,wn=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=Wl;this.externalStopCallback=Wl;this.externalErrorCallback=Wl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:By}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:p0.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),h0)}normalizeOptions(e={}){let t={stunServerList:By,maxRetryNumber:f0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var _a=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new v0(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 _y(e)}};this.subscription=new g0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=me(e.container,e.tuning),this.liveStreamClient=new wn(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),be(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Yl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Ny(this.videoState.stateChangeStarted$.pipe(Fy(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Fy(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=ve(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(Ve(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(ge(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 _y(n.to)}},r)).add(Ny(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,b0(["init"])).pipe(m0(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:S0.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Yl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Se(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:Yl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Na=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 qa,assertNonNullable as Bt,ErrorCategory as kn,filter as Gy,isNonNullable as Wy,isNullable as w0,map as k0,merge as R0,once as $0,Subject as Ie,Subscription as Yy,ValueSubject as M,flattenObject as zy}from"@vkontakte/videoplayer-shared/es2018";import{Observable as y0,map as qy,Subscription as T0,Subject as I0}from"@vkontakte/videoplayer-shared/es2018";var Uy=a=>new y0(e=>{let t=new T0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(qy(({from:l,to:d})=>`${l}-${d}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(qy(({type:l})=>l!==void 0)),n=new I0,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 E0,Subscription as x0,combine as P0,filter as jy,once as Qy}from"@vkontakte/videoplayer-shared/es2018";function Hy(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as A0}from"@vkontakte/videoplayer-shared/es2018";var Fa=class Fa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ke;this.subscriptions=new x0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(jy(s=>!!s.type),Qy()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){A0.isSafari&&e!=="MPEG"||this.subscriptions.add(P0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(jy(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),Qy()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=Hy();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Fa.errorId,category:E0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Fa.errorId} exception`,thrown:e})}};Fa.errorId="VolumeMultiplierManager";var Zr=Fa;var L0={chunkDuration:5e3,maxParallelRequests:5},Ua=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new Ie;this.noAvailableProvidersError$=new Ie;this.volumeMultiplierError$=new Ie;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new Ie,warning$:new Ie,willSeekEvent$:new Ie,soundProhibitedEvent$:new Ie,seekedEvent$:new Ie,loopedEvent$:new Ie,endedEvent$:new Ie,firstBytesEvent$:new Ie,loadedMetadataEvent$:new Ie,firstFrameEvent$:new Ie,canplay$:new Ie,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new Yy;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=yv([...Iv(this.params.tuning),...Tv(this.params.tuning)],this.params.tuning).filter(l=>Wy(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,zl.default)(i,l)),...t.filter(l=>(0,zl.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",zy(s)),this.screenFormatsIterator=new Na(s);let n=[...sl(!0),...sl(!1)];this.chromecastFormatsIterator=new Na(n.filter(l=>Wy(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Zr.isSupported()&&(this.volumeMultiplierManager=new Zr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(w0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:kn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return qa(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 Bt(o),new $a({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new La({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Bt(o),Gr||!this.params.tuning.useHlsJs?new Oa({...n,source:o}):new Ca({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Da({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Ba({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new _g({...n,source:o,config:{...L0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new _a({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 qa(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 Bt(o),new Li({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 qa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return qa(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 qa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,Jy.default)((0,Ky.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new Yy,t=!1,r=0;return e.add(R0(this.providerOutput.error$.pipe(Gy(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),Uy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(k0(i=>({id:`ProviderHangup:${i}`,category:kn.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(Gy(({to:s})=>s==="playing"),$0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===kn.NETWORK,u=i.category===kn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...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",zy(n))})),e}};import{fromEvent as Rn,once as M0,combine as C0,Subscription as Xy,ValueSubject as Kl,map as D0,filter as O0,isNonNullable as $n,now as $e,safeStorage as Jl}from"@vkontakte/videoplayer-shared/es2018";var V0=5e3,Zy="one_video_throughput",eT="one_video_rtt",ht=window.navigator.connection,tT=()=>{let a=ht==null?void 0:ht.downlink;if($n(a)&&a!==10)return a*1e3},rT=()=>{let a=ht==null?void 0:ht.rtt;if($n(a)&&a!==3e3)return a},iT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},Xl=class a{constructor(e){this.subscription=new Xy;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(Zy)||(e.useBrowserEstimation?tT():void 0)||V0,r=(s=(i=a.load(eT))!=null?i:e.useBrowserEstimation?rT():void 0)!=null?s:0;if(this.throughput$=new Kl(t),this.rtt$=new Kl(r),this.rttAdjustedThroughput$=new Kl(iT(t,r,e.rttPenaltyRequestSize)),this.throughput=ur.getSmoothedValue(t,-1,e),this.rtt=ur.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=tT();u&&this.throughput.next(u);let l=rT();$n(l)&&this.rtt.next(l)};ht&&"onchange"in ht&&this.subscription.add(Rn(ht,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Jl.set(Zy,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Jl.set(eT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(C0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(D0(({throughput:n,rtt:o})=>iT(n,o,e.rttPenaltyRequestSize)),O0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=$e(),i=new Xy;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Rn(e,"progress").pipe(M0()).subscribe(s=>{t=s.loaded,r=$e()}));break;case 1:case 0:i.add(Rn(e,"loadstart").subscribe(()=>{t=0,r=$e()}));break}i.add(Rn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=$e(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=$e(),n=0,o=$e(),u=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(i,$e()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=$e();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,s=$e()}else n+=c.byteLength;o=$e()}else i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&$e()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,$e()-o,this.concurrentDownloads.size),n=0,o=$e());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Jl.get(e);if($n(t))return(r=parseInt(t,10))!=null?r:void 0}},aT=Xl;import{fillWithDefault as B0,VideoQuality as Ln}from"@vkontakte/videoplayer-shared/es2018";var sT={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:Ln.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Ln.Q_720P,trafficSavingLimit:Ln.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ln.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},nT=a=>{var e;return{...B0(a,sT),configName:[...(e=a.configName)!=null?e:[],...sT.configName]}};import{assertNonNullable as Mn,combine as ft,ErrorCategory as Cn,filter as he,filterChanged as N,fromEvent as ec,isNonNullable as j0,isNullable as Q0,Logger as G0,map as B,mapTo as cT,merge as _t,now as Dn,once as rt,Subject as Q,Subscription as dT,tap as pT,ValueSubject as P,isHigher as W0,isInvariantQuality as hT,flattenObject as Nt,throttle as tc,getTraceSubscriptionMethod as fT,Tracer as Y0,InternalsExposure as z0}from"@vkontakte/videoplayer-shared/es2018";import{merge as _0,map as N0,filter as oT,isNonNullable as F0}from"@vkontakte/videoplayer-shared/es2018";var Zl=({seekState:a,position$:e})=>_0(a.stateChangeEnded$.pipe(N0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),oT(F0)),e.pipe(oT(()=>a.getState().state==="none")));import{assertNonNullable as q0}from"@vkontakte/videoplayer-shared/es2018";var uT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return q0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as U0,once as H0}from"@vkontakte/videoplayer-shared/es2018";var lT=(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(U0(i=>i.length>0),H0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var On=class{constructor(e={configName:[]},t=Y0.createRootTracer(!1)){this.subscription=new dT;this.logger=new G0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),isLowLatency:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),predefinedQualityLimitType$:new P("unknown"),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new Q,ready$:new Q,started$:new Q,playing$:new Q,paused$:new Q,stopped$:new Q,willStart$:new Q,willResume$:new Q,willPause$:new Q,willStop$:new Q,willDestruct$:new Q,watchCoverageRecord$:new Q,watchCoverageLive$:new Q,managedError$:new Q,fatalError$:new Q,ended$:new Q,looped$:new Q,seeked$:new Q,willSeek$:new Q,autoplaySoundProhibited$:new Q,firstBytes$:new Q,loadedMetadata$:new Q,firstFrame$:new Q,canplay$:new Q,log$:new Q};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:hg};if(this.initLogs(),this.tuning=nT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new us({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new aT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new z0("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,mT.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:Cn.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Nt(r)),this.domContainer=uT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new Ua({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(o=this.internalsExposure)==null||o.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!qi()?(this.tracer.log("request play from hidden tab"),ec(document,"visibilitychange").pipe(rt()).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){Mn(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(he(r=>r.length>0),rt()).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",Nt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.desiredState.autoVideoTrackLimits.startTransitionTo(i),this}setPlaybackRate(e){var r;Mn(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",Nt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return lT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(Q0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return j0(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(_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(B(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Fs({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(he(({from:e})=>e==="stopped"),rt()).subscribe(()=>{this.initedAt=Dn(),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",Nt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Cn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(rt()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Nt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(B(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(B(n=>n.destination),N()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ft({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(B(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>hT(u)?1:hT(l)?-1:W0(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(N()).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(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(N((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(N()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(N()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(N()).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(B(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(ft({hasLiveOffsetByPaused:_t(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(B(n=>n.to),N(),B(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(ft({atLiveEdge:ft({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(B(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),N(),pT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(B(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ft({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(B(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),N(),pT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(B(n=>n.muted),N()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(B(n=>n.volume),N()).subscribe(this.info.volume$)).add(Zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(_t(e.providerOutput.endedEvent$.pipe(cT(!0)),e.providerOutput.seekedEvent$.pipe(cT(!1))).pipe(N()).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(B(n=>({id:n?`No${n}`:"NoProviders",category:Cn.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(rt(),B(n=>n!=null?n:Dn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(rt(),B(()=>Dn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(rt(),B(()=>Dn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(he(({to:n})=>n==="playing"),rt()).subscribe(()=>r.next(!1)));let i=0,s=_t(e.providerOutput.isBuffering$,t,r).pipe(B(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),N());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(_t(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(_t(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(B(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new dT;this.subscription.add(t),this.subscription.add(e.current$.pipe(N((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(he(r=>r.length>0),rt()).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=Lt(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(_t(this.desiredState.videoTrack.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(B(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;Mn(this.providerContainer),Mn(e),pg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>dg(r)),this.providerContainer.current$.subscribe(({type:r})=>Oi("provider",r)),e.duration$.subscribe(r=>Oi("duration",r)),e.availableVideoTracks$.pipe(he(r=>!!r.length),rt()).subscribe(r=>Oi("tracks",r)),this.events.fatalError$.subscribe(new de("fatalError")),this.events.managedError$.subscribe(new de("managedError")),e.position$.subscribe(new de("position")),e.currentVideoTrack$.pipe(B(r=>r==null?void 0:r.quality)).subscribe(new de("quality")),this.info.currentBuffer$.subscribe(new de("buffer")),e.isBuffering$.subscribe(new de("isBuffering"))].forEach(r=>this.subscription.add(r)),Oi("codecs",Sv())}initTracerSubscription(){let e=fT(this.tracer.log.bind(this.tracer)),t=fT(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(N()).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(ft({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(he(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),N((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(he(r=>r>0),N()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(he(r=>r>0),N()).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(ft({currentBuffer:this.info.currentBuffer$.pipe(he(r=>r.end>0),N((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(N())}).pipe(tc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(N()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(N()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(N()).subscribe(e("canChangePlaybackSpeed"))).add(ft({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(he(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),tc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(N(),he(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(N(),he(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(N()).subscribe(e("muted"))).add(this.info.volume$.pipe(N()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(N(),he(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ft({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(he(({throughputEstimation:r,rtt:i})=>!!r&&!!i),tc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(N(),he(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Cn.DOM,message:String(i)})})};this.subscription.add(_t(ec(document,"visibilitychange"),ec(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",Nt({quality:t,availableTracks:Nt(e),track:Nt(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 hz,Observable as fz,Subject as mz,ValueSubject as bz,VideoQuality as gz}from"@vkontakte/videoplayer-shared/es2018";var vz=`@vkontakte/videoplayer-core@${Vc}`;export{rs as ChromecastState,qn as HttpConnectionType,fz as Observable,fe as PlaybackState,On as Player,oi as PredefinedQualityLimits,vz as SDK_VERSION,mz as Subject,hz as Subscription,Un as Surface,Vc as VERSION,bz as ValueSubject,It as VideoFormat,gz as VideoQuality};
|
|
123
|
+
`;var vn=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 bn(this.params.fov,this.params.orientation),this.cameraRotationManager=new gn(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(ly,this.gl.VERTEX_SHADER),r=this.createShader(cy,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 o0,now as dy,Subscription as u0,filter as l0,combine as py,ValueSubject as hy,isNonNullable as c0}from"@vkontakte/videoplayer-shared/es2018";var Ol=class{constructor(){this.isSeeked$=new hy(!1);this.isBuffering$=new hy(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new u0}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(l0(({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(o0(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=dy(),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,c0(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=dy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},fy=Ol;var pr=class{constructor(e){this.subscription=new S0;this.videoState=new L("stopped");this.elementSize$=new y0(void 0);this.textTracksManager=new Oe;this.droppedFramesManager=new js;this.stallsManager=new fy;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Oi;this.audioTrackSwitchHistory=new Oi;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 h0(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new vn(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.elementSize$.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=be(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new mn({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=Se(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Bl.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(my(c=>!!c.length),gy()).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(Vl(c=>c.to.state!=="none"),ka());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ka()),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(my(by),gy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Vl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ze(this.video,t.isLooped,i)),this.subscription.add(ve(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,i)),s(v0(this.video),this.elementSize$),s(Ve(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(f0(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let b of p.audio){f.push(El(b));let g=[];for(let v of b.representations){let S=zS(v);g.push(S),this.audioTracksMap.set(S,{stream:b,representation:v})}this.audioStreamsMap.set(b,g)}this.params.output.availableAudioStreams$.next(f)}let h=[];for(let f of p.video){h.push(xl(f));let b=[];for(let g of f.representations){let v=YS({...g,streamId:f.id});v&&(b.push(v),this.videoTracksMap.set(v,{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=KS(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:Bl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Sn(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.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,b0(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),p=this.player.state$.getTransition();if(!(0,vy.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(S=>{var y;return((y=this.videoTracksMap.get(S))==null?void 0:y.representation.id)===f.id});by(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.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 S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",b.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.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ka()).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(xl(f))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ka()).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(El(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(Vl(({to:c})=>c==="ready"),ka());this.subscription.add(Sn(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(Sn(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Sn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,g0(["init"])).pipe(m0(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var R,C,G,$,V,_,k,w,H,J,A,T,O;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(R=e.videoTrack.getState())==null?void 0:R.id,n=[...this.videoTracksMap.keys()].find(({id:M})=>M===i),o=t.currentVideoTrack$.getValue(),u=(($=(G=e.videoStream.getState())!=null?G:n&&((C=this.videoTracksMap.get(n))==null?void 0:C.stream))!=null?$:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:M})=>M===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=tt(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=(V=e.audioStream.getState())!=null?V:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(_=[...this.audioStreamsMap.keys()].find(({id:M})=>M===(f==null?void 0:f.id)))!=null?_:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let M=Fs(n,d,(k=this.audioStreamsMap.get(b))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(w=M==null?void 0:M.bitrate)!=null?w:-1/0)}if(o){let M=Fs(o,d,(H=this.audioStreamsMap.get(b))!=null?H:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(J=M==null?void 0:M.bitrate)!=null?J:-1/0)}}let v=Mt(d,{container:this.elementSize$.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}),S=r?v!=null?v:n:n!=null?n:v,y=b&&yg(S,d,(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}),E=(T=this.videoTracksMap.get(S))==null?void 0:T.representation,I=y&&((O=this.audioTracksMap.get(y))==null?void 0:O.representation);if(E&&I)return[E,I];if(E&&!I&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ye(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:Bl.DOM,thrown:e}))}destroy(){var e;this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),(e=this.textTracksManager)==null||e.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ge(this.video),this.tracer.end()}};var Ra=class extends pr{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 Sy,interval as T0,map as yy}from"@vkontakte/videoplayer-shared/es2018";var $a=class extends pr{constructor(e){super(e),this.liveOffset=new ot,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(yy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Sy({interval:T0(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(Sy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(yy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=JS(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Iy=B(Os(),1);import{assertNever as La,assertNonNullable as Ty,debounce as I0,ErrorCategory as yn,filter as E0,isNonNullable as x0,isNullable as P0,map as Tn,merge as A0,Observable as w0,observableFrom as k0,Subscription as R0,videoSizeToQuality as $0}from"@vkontakte/videoplayer-shared/es2018";var We={};var Zr=(a,e)=>new w0(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ma=class{constructor(e){this.subscription=new R0;this.videoState=new L("initializing");this.textTracksManager=new Oe;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:La(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:La(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:La(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:La(e)}break;default:La(t)}};this.video=be(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ge(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:yn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Iy.default)(import("hls.js").then(i=>{e||(We.Hls=i.default,We.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Ty(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Ty(We.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:yn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Se(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(Ze(this.video,e.isLooped,r)),this.subscription.add(ve(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(De(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ve(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Tn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Zr(this.hls,We.Events.ERROR).subscribe(l=>{var d;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:yn.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(Zr(this.hls,We.Events.MANIFEST_PARSED).pipe(Tn(({levels:l})=>l.reduce((d,c)=>{var S,y;let p=c.name||c.height.toString(10),{width:h,height:f}=c,b=(y=$t((S=c.attrs.QUALITY)!=null?S:""))!=null?y:$0({width:h,height:f});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),s(Zr(this.hls,We.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(Zr(this.hls,We.Events.LEVEL_LOADING).pipe(Tn(({url:l})=>ie(l))),t.hostname$),s(Zr(this.hls,We.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(wt(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=Zr(this.hls,We.Events.LEVEL_SWITCHED).pipe(Tn(({level:l})=>n(this.hls.levels[l])));o.pipe(E0(x0)).subscribe(t.currentVideoTrack$,r),this.subscription.add(wt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(P0(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=A0(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,k0(["init"])).pipe(I0(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await ye(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:yn.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 Ey="X-Playback-Duration",_l=async a=>{var i;let e=await lt(a),t=await e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Ey)?parseInt(e.headers.get(Ey),10):void 0};import{assertNever as B0,combine as V0,debounce as _0,ErrorCategory as En,filter as N0,filterChanged as F0,isNonNullable as Py,isNullable as xn,map as Ay,merge as q0,observableFrom as U0,Subscription as H0,ValueSubject as ql,VideoQuality as j0}from"@vkontakte/videoplayer-shared/es2018";var Fl=B(Qo(),1);import{videoSizeToQuality as L0,getExponentialDelay as M0}from"@vkontakte/videoplayer-shared/es2018";var C0=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=L0({width:t,height:r})}return e!=null?e:null},D0=(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,Fl.default)(l[1].split(",").map(S=>S.split("="))),p=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,h=C0(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[S,y]=c.RESOLUTION.split("x").map(E=>parseInt(E,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(d){let c=(0,Fl.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}},O0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Nl=0,xy=async(a,e=a,t)=>{let i=await(await lt(a)).text();Nl+=1;try{let{qualityManifests:s,textTracks:n}=D0(i,e);return{qualityManifests:s,textTracks:n}}catch(s){if(Nl<=t.manifestRetryMaxCount)return await O0(M0(Nl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),xy(a,e,t)}return{qualityManifests:[],textTracks:[]}},In=xy;var Ca=class{constructor(e){this.subscription=new H0;this.videoState=new L("stopped");this.textTracksManager=new Oe;this.manifests$=new ql([]);this.liveOffset=new ot;this.manifestStartTime$=new ql(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 B0(t)}};var t;this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:j0.INVARIANT,url:this.params.source.url},In(ce(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:En.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:En.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(ie(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ql((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:En.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Se(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(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(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(F0(),Ay(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&&Py(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(ie(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(V0({startTime:this.manifestStartTime$.pipe(N0(Py)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Ay(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=q0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,U0(["init"])).pipe(_0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var o,u;let e=this.selectManifest();if(xn(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=ce(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),_l(n).then(l=>{var d;if(!xn(l))this.maxSeekBackTime$.next(l);else{let c=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();if(xn(c)||!isFinite(c))try{lt(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();_l(b).then(g=>{xn(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){ye(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:En.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 G0,debounce as Q0,ErrorCategory as Ul,fromEvent as Hl,isNonNullable as W0,isNullable as Y0,map as wy,merge as ky,observableFrom as Ry,Subscription as z0,ValueSubject as K0,VideoQuality as J0,clientChecker as X0}from"@vkontakte/videoplayer-shared/es2018";var Da=class{constructor(e){this.subscription=new z0;this.videoState=new L("stopped");this.textTracksManager=new Oe;this.manifests$=new K0([]);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 G0(t)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:J0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),In(ce(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:Ul.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:Ul.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Se(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(wy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ze(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(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&&W0(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(ie(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(wy(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)),!X0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(ky(Hl(o,"addtrack"),Hl(o,"removetrack"),Hl(o,"change"),Ry(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=ky(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ry(["init"])).pipe(Q0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ge(this.video)}prepare(){var s,n;let e=this.selectManifest();if(Y0(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(){ye(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:Ul.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Cy=B(Lr(),1),Oa=B(Li(),1);import{assertNever as Z0,assertNonNullable as $y,debounce as eC,ErrorCategory as Ly,isHigher as tC,isHigherOrEqual as rC,isInvariantQuality as My,isLowerOrEqual as iC,isNonNullable as aC,merge as sC,observableFrom as nC,Subscription as oC,map as uC}from"@vkontakte/videoplayer-shared/es2018";var Ba=class{constructor(e){this.subscription=new oC;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Oe;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 Z0(e)}};this.params=e,this.video=be(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Cy.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,Oa.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:Ly.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Se(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(uC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ze(this.video,t.isLooped,r)),this.subscription.add(ve(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ve(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&&aC(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=sC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,nC(["init"])).pipe(eC(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),ge(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;$y(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];$y(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Sa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ie(t))}playIfAllowed(){ye(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:Ly.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,Oa.default)(this.trackUrls).find(c=>!My(c.track.quality)&&iC(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&&rC(d.quality,u.quality)&&(t=u),!t){let c=(0,Oa.default)(this.trackUrls).filter(h=>!My(h.track.quality)&&tC(h.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Oa.default)(this.trackUrls).map(l=>l.track);t=Mt(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 Oy,debounce as pC,merge as By,observableFrom as hC,Subscription as fC,map as Vy,ValueSubject as mC,ErrorCategory as Gl,VideoQuality as bC}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as lC}from"@vkontakte/videoplayer-shared/es2018";var Dy=["stun:videostun.mycdn.me:80"],cC=1e3,dC=3,jl=()=>null,Pn=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=jl;this.externalStopCallback=jl;this.externalErrorCallback=jl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:Dy}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:lC.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),cC)}normalizeOptions(e={}){let t={stunServerList:Dy,maxRetryNumber:dC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Va=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new mC(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 Oy(e)}};this.subscription=new fC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=be(e.container,e.tuning),this.liveStreamClient=new Pn(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),ge(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Gl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};By(this.videoState.stateChangeStarted$.pipe(Vy(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Vy(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Se(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(Ve(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(ve(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 Oy(n.to)}},r)).add(By(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,hC(["init"])).pipe(pC(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ie(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:bC.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:Gl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ye(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:Gl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var _a=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 Fa,assertNonNullable as _t,ErrorCategory as An,filter as Hy,isNonNullable as jy,isNullable as xC,map as PC,merge as AC,once as wC,Subject as Ee,Subscription as Gy,ValueSubject as D,flattenObject as Qy}from"@vkontakte/videoplayer-shared/es2018";import{Observable as gC,map as _y,Subscription as vC,Subject as SC}from"@vkontakte/videoplayer-shared/es2018";var Ny=a=>new gC(e=>{let t=new vC,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(_y(({from:l,to:d})=>`${l}-${d}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(_y(({type:l})=>l!==void 0)),n=new SC,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 yC,Subscription as TC,combine as IC,filter as qy,once as Uy}from"@vkontakte/videoplayer-shared/es2018";function Fy(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as EC}from"@vkontakte/videoplayer-shared/es2018";var Na=class Na{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new ke;this.subscriptions=new TC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(qy(s=>!!s.type),Uy()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){EC.isSafari&&e!=="MPEG"||this.subscriptions.add(IC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(qy(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),Uy()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=Fy();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Na.errorId,category:yC.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Na.errorId} exception`,thrown:e})}};Na.errorId="VolumeMultiplierManager";var ei=Na;var kC={chunkDuration:5e3,maxParallelRequests:5},qa=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new Ee;this.noAvailableProvidersError$=new Ee;this.volumeMultiplierError$=new Ee;this.providerOutput={position$:new D(0),duration$:new D(1/0),volume$:new D({muted:!1,volume:1}),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableVideoTracks$:new D([]),currentVideoTrack$:new D(void 0),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0),isAudioAvailable$:new D(!0),autoVideoTrackLimitingAvailable$:new D(!1),autoVideoTrackLimits$:new D(void 0),currentBuffer$:new D(void 0),isBuffering$:new D(!0),error$:new Ee,warning$:new Ee,willSeekEvent$:new Ee,soundProhibitedEvent$:new Ee,seekedEvent$:new Ee,loopedEvent$:new Ee,endedEvent$:new Ee,firstBytesEvent$:new Ee,loadedMetadataEvent$:new Ee,firstFrameEvent$:new Ee,canplay$:new Ee,isLive$:new D(void 0),isLowLatency$:new D(!1),canChangePlaybackSpeed$:new D(!0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),inPiP$:new D(!1),inFullscreen$:new D(!1),element$:new D(void 0),elementVisible$:new D(!0),availableSources$:new D(void 0),is3DVideo$:new D(!1),playbackState$:new D("")};this.subscription=new Gy;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=gv([...Sv(this.params.tuning),...vv(this.params.tuning)],this.params.tuning).filter(l=>jy(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,Ql.default)(i,l)),...t.filter(l=>(0,Ql.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Qy(s)),this.screenFormatsIterator=new _a(s);let n=[...rl(!0),...rl(!1)];this.chromecastFormatsIterator=new _a(n.filter(l=>jy(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ei.isSupported()&&(this.volumeMultiplierManager=new ei(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(xC(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:An.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 Fa(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 _t(o),new Ra({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return _t(o),new $a({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return _t(o),Wr||!this.params.tuning.useHlsJs?new Da({...n,source:o}):new Ma({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return _t(o),new Ca({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return _t(o),new Ba({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return _t(o),new Og({...n,source:o,config:{...kC,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return _t(o),new Va({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 Fa(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 _t(o),new $i({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 Fa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Fa(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 Fa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:r(e.url)}}return(0,Yy.default)((0,Wy.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new Gy,t=!1,r=0;return e.add(AC(this.providerOutput.error$.pipe(Hy(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),Ny({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(PC(i=>({id:`ProviderHangup:${i}`,category:An.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(Hy(({to:s})=>s==="playing"),wC()).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===An.NETWORK,u=i.category===An.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={...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",Qy(n))})),e}};import{fromEvent as wn,once as RC,combine as $C,Subscription as zy,ValueSubject as Wl,map as LC,filter as MC,isNonNullable as kn,now as $e,safeStorage as Yl}from"@vkontakte/videoplayer-shared/es2018";var CC=5e3,Ky="one_video_throughput",Jy="one_video_rtt",ht=window.navigator.connection,Xy=()=>{let a=ht==null?void 0:ht.downlink;if(kn(a)&&a!==10)return a*1e3},Zy=()=>{let a=ht==null?void 0:ht.rtt;if(kn(a)&&a!==3e3)return a},eT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},zl=class a{constructor(e){this.subscription=new zy;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(Ky)||(e.useBrowserEstimation?Xy():void 0)||CC,r=(s=(i=a.load(Jy))!=null?i:e.useBrowserEstimation?Zy():void 0)!=null?s:0;if(this.throughput$=new Wl(t),this.rtt$=new Wl(r),this.rttAdjustedThroughput$=new Wl(eT(t,r,e.rttPenaltyRequestSize)),this.throughput=ur.getSmoothedValue(t,-1,e),this.rtt=ur.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=Xy();u&&this.throughput.next(u);let l=Zy();kn(l)&&this.rtt.next(l)};ht&&"onchange"in ht&&this.subscription.add(wn(ht,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Yl.set(Ky,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Yl.set(Jy,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add($C({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(LC(({throughput:n,rtt:o})=>eT(n,o,e.rttPenaltyRequestSize)),MC(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=$e(),i=new zy;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(wn(e,"progress").pipe(RC()).subscribe(s=>{t=s.loaded,r=$e()}));break;case 1:case 0:i.add(wn(e,"loadstart").subscribe(()=>{t=0,r=$e()}));break}i.add(wn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=$e(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=$e(),n=0,o=$e(),u=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(i,$e()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=$e();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,s=$e()}else n+=c.byteLength;o=$e()}else i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&$e()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,$e()-o,this.concurrentDownloads.size),n=0,o=$e());await(r==null?void 0:r.read().then(l,u))}};this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Yl.get(e);if(kn(t))return(r=parseInt(t,10))!=null?r:void 0}},tT=zl;import{fillWithDefault as DC,VideoQuality as rT}from"@vkontakte/videoplayer-shared/es2018";var iT={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:rT.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:rT.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},aT=a=>{var e;return{...DC(a,iT),configName:[...(e=a.configName)!=null?e:[],...iT.configName]}};import{assertNonNullable as Rn,combine as ft,ErrorCategory as $n,filter as fe,filterChanged as q,fromEvent as Jl,isNonNullable as qC,isNullable as UC,Logger as HC,map as N,mapTo as uT,merge as Nt,now as Ln,once as rt,Subject as j,Subscription as lT,tap as cT,ValueSubject as P,isHigher as jC,isInvariantQuality as dT,flattenObject as Ft,throttle as Xl,getTraceSubscriptionMethod as pT,Tracer as GC,InternalsExposure as QC}from"@vkontakte/videoplayer-shared/es2018";import{merge as OC,map as BC,filter as sT,isNonNullable as VC}from"@vkontakte/videoplayer-shared/es2018";var Kl=({seekState:a,position$:e})=>OC(a.stateChangeEnded$.pipe(BC(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),sT(VC)),e.pipe(sT(()=>a.getState().state==="none")));import{assertNonNullable as _C}from"@vkontakte/videoplayer-shared/es2018";var nT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return _C(e,`Wrong container or containerId {${a.container}}`),e};import{filter as NC,once as FC}from"@vkontakte/videoplayer-shared/es2018";var oT=(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(NC(i=>i.length>0),FC()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Mn=class{constructor(e={configName:[]},t=GC.createRootTracer(!1)){this.subscription=new lT;this.logger=new HC;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),isLowLatency:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,autoplaySoundProhibited$:new j,firstBytes$:new j,loadedMetadata$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:cg};if(this.initLogs(),this.tuning=aT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new os({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new tT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new QC("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,hT.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:$n.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var i,s,n,o;this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Ft(r)),this.domContainer=nT(e),this.chromecastInitializer.contentId=(i=e.meta)==null?void 0:i.videoId,this.providerContainer=new qa({sources:e.sources,meta:(s=e.meta)!=null?s:{},failoverHosts:(n=e.failoverHosts)!=null?n:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(o=this.internalsExposure)==null||o.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Fi()?(this.tracer.log("request play from hidden tab"),Jl(document,"visibilitychange").pipe(rt()).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){Rn(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(fe(r=>r.length>0),rt()).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",Ft(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Rn(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",Ft(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return oT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(UC(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return qC(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(Nt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(N(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(fe(({from:e})=>e==="stopped"),rt()).subscribe(()=>{this.initedAt=Ln(),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",Ft(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:$n.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(rt()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Ft(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(N(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(N(n=>n.destination),q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ft({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(N(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>dT(u)?1:dT(l)?-1:jC(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(q()).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(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(q()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(N(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.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(ft({hasLiveOffsetByPaused:Nt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(N(n=>n.to),q(),N(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(ft({atLiveEdge:ft({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(N(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),q(),cT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(N(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ft({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(N(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),q(),cT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(N(n=>n.muted),q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(N(n=>n.volume),q()).subscribe(this.info.volume$)).add(Kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Nt(e.providerOutput.endedEvent$.pipe(uT(!0)),e.providerOutput.seekedEvent$.pipe(uT(!1))).pipe(q()).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(N(n=>({id:n?`No${n}`:"NoProviders",category:$n.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(rt(),N(n=>n!=null?n:Ln()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(rt(),N(()=>Ln()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(rt(),N(()=>Ln()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(fe(({to:n})=>n==="playing"),rt()).subscribe(()=>r.next(!1)));let i=0,s=Nt(e.providerOutput.isBuffering$,t,r).pipe(N(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),q());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(Nt(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(Nt(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(N(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new lT;this.subscription.add(t),this.subscription.add(e.current$.pipe(q((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(fe(r=>r.length>0),rt()).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=Mt(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(Nt(this.desiredState.videoTrack.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(N(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(N(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(N(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Rn(this.providerContainer),Rn(e),lg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>ug(r)),this.providerContainer.current$.subscribe(({type:r})=>Di("provider",r)),e.duration$.subscribe(r=>Di("duration",r)),e.availableVideoTracks$.pipe(fe(r=>!!r.length),rt()).subscribe(r=>Di("tracks",r)),this.events.fatalError$.subscribe(new pe("fatalError")),this.events.managedError$.subscribe(new pe("managedError")),e.position$.subscribe(new pe("position")),e.currentVideoTrack$.pipe(N(r=>r==null?void 0:r.quality)).subscribe(new pe("quality")),this.info.currentBuffer$.subscribe(new pe("buffer")),e.isBuffering$.subscribe(new pe("isBuffering"))].forEach(r=>this.subscription.add(r)),Di("codecs",bv())}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(q()).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(ft({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(fe(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(fe(r=>r>0),q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(fe(r=>r>0),q()).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(ft({currentBuffer:this.info.currentBuffer$.pipe(fe(r=>r.end>0),q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(q())}).pipe(Xl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(q()).subscribe(e("canChangePlaybackSpeed"))).add(ft({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(fe(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Xl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(q(),fe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(q(),fe(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(q()).subscribe(e("muted"))).add(this.info.volume$.pipe(q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(q(),fe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ft({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(fe(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Xl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(q(),fe(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:$n.DOM,message:String(i)})})};this.subscription.add(Nt(Jl(document,"visibilitychange"),Jl(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",Ft({quality:t,availableTracks:Ft(e),track:Ft(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 rz,Observable as iz,Subject as az,ValueSubject as sz,VideoQuality as nz}from"@vkontakte/videoplayer-shared/es2018";var oz=`@vkontakte/videoplayer-core@${Cc}`;export{ts as ChromecastState,_n as HttpConnectionType,iz as Observable,me as PlaybackState,Mn as Player,oz as SDK_VERSION,az as Subject,rz as Subscription,Nn as Surface,Cc as VERSION,sz as ValueSubject,Et as VideoFormat,nz as VideoQuality};
|